source: trunk/FACT++/src/mcp.cc@ 15324

Last change on this file since 15324 was 15239, checked in by tbretz, 12 years ago
Fixed a race-condition during configuration with the states of the ratecontrol.
File size: 22.5 KB
Line 
1#include "Dim.h"
2#include "Event.h"
3#include "Shell.h"
4#include "StateMachineDim.h"
5#include "Connection.h"
6#include "Configuration.h"
7#include "Console.h"
8
9#include "tools.h"
10
11#include "LocalControl.h"
12
13#include "HeadersFTM.h"
14#include "HeadersFAD.h"
15#include "HeadersMCP.h"
16#include "HeadersRateControl.h"
17
18namespace ba = boost::asio;
19namespace bs = boost::system;
20namespace dummy = ba::placeholders;
21
22using namespace std;
23
24// ------------------------------------------------------------------------
25
26#include "DimDescriptionService.h"
27#include "DimState.h"
28
29// ------------------------------------------------------------------------
30
31class StateMachineMCP : public StateMachineDim
32{
33private:
34 vector<bool> fFadConnected;
35 vector<bool> fFadNeedsReset;
36
37 vector<bool> fFadCratesForReset;
38 vector<bool> fFadBoardsForConnection;
39
40 uint16_t fNumConnectedFtu;
41 uint16_t fNumConnectedFad;
42
43 uint16_t fNumReset;
44
45 DimVersion fDim;
46 DimDescribedState fDimFTM;
47 DimDescribedState fDimFAD;
48 DimDescribedState fDimLog;
49 DimDescribedState fDimRC;
50
51 DimDescribedService fService;
52
53 Time fFadTimeout;
54
55 int HandleFadConnections(const EventImp &d)
56 {
57 if (d.GetSize()!=41)
58 return GetCurrentState();
59
60 const uint8_t *ptr = d.Ptr<uint8_t>();
61
62 fNumConnectedFad = 0;
63 fFadConnected.assign(40, false);
64
65 vector<bool> reset(4);
66
67 for (int i=0; i<40; i++)
68 {
69 const uint8_t stat1 = ptr[i]&3;
70 const uint8_t stat2 = ptr[i]>>3;
71
72 // disconnected: ignore
73 if (stat1==0 && stat2==0)
74 continue;
75
76 fFadConnected[i] = true;
77
78 if (stat1>=2 && stat2==8)
79 fNumConnectedFad++;
80
81 // Does not need reset
82 if (stat1>2 && stat2==8)
83 continue;
84
85 // Not configured (stat1==2?kLedGreen:kLedGreenCheck)
86 // Connection problem (stat1==1&&stat2==1?kLedRed:kLedOrange)
87 reset[i/10] = true;
88 }
89 return GetCurrentState();
90 }
91
92 int HandleFtmStaticData(const EventImp &d)
93 {
94 if (d.GetSize()!=sizeof(FTM::DimStaticData))
95 return GetCurrentState();
96
97 const FTM::DimStaticData &sdata = d.Ref<FTM::DimStaticData>();
98
99 fNumConnectedFtu = 0;
100 for (int i=0; i<40; i++)
101 {
102 if (sdata.IsActive(i))
103 fNumConnectedFtu++;
104 }
105 return GetCurrentState();
106 }
107
108 int Print() const
109 {
110 Out() << fDim << endl;
111 Out() << fDimFTM << endl;
112 Out() << fDimFAD << endl;
113 Out() << fDimLog << endl;
114 Out() << fDimRC << endl;
115
116 return GetCurrentState();
117 }
118
119 int GetReady()
120 {
121 return GetCurrentState();
122 }
123
124 int StopRun()
125 {
126 if (fDimFTM.state()==FTM::State::kTriggerOn)
127 {
128 Message("Stopping FTM");
129 Dim::SendCommandNB("FTM_CONTROL/STOP_TRIGGER");
130 }
131
132 // FIXME: Do step 2 only when FTM is stopped
133 if (fDimFAD.state()==FAD::State::kConnected)
134 {
135 //Dim::SendCommand("FAD_CONTROL/ENABLE_TRIGGER_LINE", bool(false));
136 Message("Stopping FAD");
137 Dim::SendCommandNB("FAD_CONTROL/ENABLE_CONTINOUS_TRIGGER", bool(false));
138 }
139
140 return GetCurrentState();
141 }
142
143 int Reset()
144 {
145 if (GetCurrentState()<MCP::State::kConfiguring1 ||
146 GetCurrentState()>MCP::State::kConfigured)
147 return GetCurrentState();
148
149 fRunType = "";
150 Message("Reseting configuration states of FAD and FTM");
151
152 Dim::SendCommandNB("FTM_CONTROL/RESET_CONFIGURE");
153 Dim::SendCommandNB("FAD_CONTROL/RESET_CONFIGURE");
154
155 Update(MCP::State::kIdle);
156 return MCP::State::kIdle;
157 /*
158 // FIMXE: Handle error states!
159 if (fDimLog.state()>=20)//kSM_NightlyOpen
160 Dim::SendCommand("DATA_LOGGER/STOP");
161
162 if (fDimLog.state()==0)
163 Dim::SendCommand("DATA_LOGGER/WAIT_FOR_RUN_NUMBER");
164
165 if (fDimFAD.state()==FAD::State::kConnected)
166 {
167 Dim::SendCommand("FAD_CONTROL/ENABLE_TRIGGER_LINE", bool(false));
168 Dim::SendCommand("FAD_CONTROL/ENABLE_CONTINOUS_TRIGGER", bool(false));
169 }
170
171 if (fDimFTM.state()==FTM::State::kTakingData)
172 Dim::SendCommand("FTM_CONTROL/STOP");
173
174 return GetCurrentState(); */
175 }
176
177 int64_t fMaxTime;
178 int64_t fNumEvents;
179 string fRunType;
180
181 int StartRun(const EventImp &evt)
182 {
183 if (!fDimFTM.online())
184 {
185 Error("No connection to ftmcontrol (see PRINT).");
186 return GetCurrentState();
187 }
188 if (!fDimFAD.online())
189 {
190 Warn("No connection to fadcontrol (see PRINT).");
191 return GetCurrentState();
192 }
193 if (!fDimLog.online())
194 {
195 Warn("No connection to datalogger (see PRINT).");
196 return GetCurrentState();
197 }
198 if (!fDimRC.online())
199 {
200 Warn("No connection to ratecontrol (see PRINT).");
201 return GetCurrentState();
202 }
203
204 fMaxTime = evt.Get<int64_t>();
205 fNumEvents = evt.Get<int64_t>(8);
206 fRunType = evt.Ptr<char>(16);
207
208 fNumReset = 0;
209
210 ostringstream str;
211 str << "Starting configuration '" << fRunType << "' for new run";
212 if (fNumEvents>0 || fMaxTime>0)
213 str << " [";
214 if (fNumEvents>0)
215 str << fNumEvents << " events";
216 if (fNumEvents>0 && fMaxTime>0)
217 str << " / ";
218 if (fMaxTime>0)
219 str << fMaxTime << "s";
220 if (fNumEvents>0 || fMaxTime>0)
221 str << "]";
222 Message(str);
223
224 Update(MCP::State::kConfiguring1);
225
226 return MCP::State::kConfiguring1;
227 }
228
229 struct Value
230 {
231 uint64_t time;
232 uint64_t nevts;
233 char type[];
234 };
235
236 Value *GetBuffer()
237 {
238 const size_t len = sizeof(Value)+fRunType.length()+1;
239
240 char *buf = new char[len];
241
242 Value *val = reinterpret_cast<Value*>(buf);
243
244 val->time = fMaxTime;
245 val->nevts = fNumEvents;
246
247 strcpy(val->type, fRunType.c_str());
248
249 return val;
250 }
251
252 void Update(int newstate)
253 {
254 Value *buf = GetBuffer();
255 fService.setQuality(newstate);
256 fService.setData(buf, sizeof(Value)+fRunType.length()+1);
257 fService.Update();
258 delete buf;
259 }
260
261 void ConfigureFAD()
262 {
263 Value *buf = GetBuffer();
264
265 Message("Configuring FAD");
266 Dim::SendCommandNB("FAD_CONTROL/CONFIGURE", buf, sizeof(Value)+fRunType.length()+1);
267
268 delete buf;
269 }
270
271 int HandleStateChange()
272 {
273 if (!fDim.online())
274 return MCP::State::kDimNetworkNA;
275
276 if (fDimFTM.state() >= FTM::State::kConnected &&
277 fDimFAD.state() >= FAD::State::kConnected &&
278 fDimLog.state() >= kSM_Ready)
279 return GetCurrentState()<=MCP::State::kIdle ? MCP::State::kIdle : GetCurrentState();
280
281 if (fDimFTM.state() >-2 &&
282 fDimFAD.state() >-2 &&
283 fDimLog.state() >-2 &&
284 fDimRC.state() >-2)
285 return MCP::State::kConnected;
286
287 if (fDimFTM.state() >-2 ||
288 fDimFAD.state() >-2 ||
289 fDimLog.state() >-2 ||
290 fDimRC.state() >-2)
291 return MCP::State::kConnecting;
292
293 return MCP::State::kDisconnected;
294 }
295
296 int Execute()
297 {
298 // ========================================================
299
300 if (GetCurrentState()==MCP::State::kConfiguring1)
301 {
302 if (fDimLog.state()<30/*kSM_WaitForRun*/)
303 {
304 Message("Starting datalogger");
305 Dim::SendCommandNB("DATA_LOGGER/START_RUN_LOGGING");
306 }
307
308 Message("Configuring Trigger (FTM)");
309 Dim::SendCommandNB("FTM_CONTROL/CONFIGURE", fRunType);
310
311 // That's a bit stupid, but we have to stop the ratecontrol
312 // first, otherwise it might be detected to be
313 // in a state larger than Connected in Configuring3
314 // (because it still was) before the state change introduced
315 // by the Configuring2 state is even received. If instead
316 // we wait in Configuring2 for the rate control to be connected,
317 // we can be sure that it works.
318 Message("Stopping ratecontrol");
319 Dim::SendCommandNB("RATE_CONTROL/STOP");
320
321 Update(MCP::State::kConfiguring2);
322 return MCP::State::kConfiguring2;
323 }
324
325 // --------------------------------------------------------
326
327 if (GetCurrentState()==MCP::State::kConfiguring2)
328 {
329 // FIMXE: Reset in case of error
330 if ((/*fDimFTM.state() != FTM::State::kConfiguring2 &&*/
331 fDimFTM.state() != FTM::State::kConfigured) ||
332 fDimLog.state()<30 || fDimLog.state()>0xff ||
333 fDimRC.state()!=RateControl::State::kConnected)
334 return MCP::State::kConfiguring2;
335
336 // FIMXE: This is to make sure that the rate control
337 // has received the correct trigger setup already...
338 //usleep(1000000);
339
340 Message("Starting Rate Control");
341 // State of RC is not reported back fast enough!
342 Dim::SendCommandNB("RATE_CONTROL/CALIBRATE_RUN", fRunType);
343
344 ConfigureFAD();
345
346 fFadTimeout = Time();
347
348 Update(MCP::State::kConfiguring3);
349 return MCP::State::kConfiguring3;
350 }
351
352 // --------------------------------------------------------
353
354 if (GetCurrentState()==MCP::State::kConfiguring3)
355 {
356 /*
357 // If everything is configured but the FADs
358 // we run into a timeout and some FAD need to be reset
359 // then we start an automatic crate reset
360 if (fDimFTM.state() == FTM::State::kConfigured &&
361 fDimFAD.state() != FAD::State::kConfigured &&
362 //fDimRC.state() > RateControl::State::kSettingGlobalThreshold &&
363 fFadTimeout+boost::posix_time::seconds(15)<Time() &&
364 count(fFadNeedsReset.begin(), fFadNeedsReset.end(), true)>0)
365 {
366 Update(MCP::State::kCrateReset0);
367 return MCP::State::kCrateReset0;
368 }
369 */
370 // If something is not yet properly configured: keep state
371 if (fDimFTM.state() != FTM::State::kConfigured ||
372 fDimFAD.state() != FAD::State::kConfigured ||
373 fDimRC.state() <= RateControl::State::kSettingGlobalThreshold)
374 return MCP::State::kConfiguring3;
375
376 Message("Starting Trigger (FTM)");
377 Dim::SendCommandNB("FTM_CONTROL/START_TRIGGER");
378
379 Update(MCP::State::kConfigured);
380 return MCP::State::kConfigured;
381 }
382
383 // --------------------------------------------------------
384
385 if (GetCurrentState()==MCP::State::kConfigured)
386 {
387 if (fDimFTM.state() != FTM::State::kTriggerOn)
388 return MCP::State::kConfigured;
389
390 Update(MCP::State::kTriggerOn);
391 return MCP::State::kTriggerOn;
392 }
393
394 // --------------------------------------------------------
395
396 if (GetCurrentState()==MCP::State::kTriggerOn)
397 {
398 if (fDimFTM.state() != FTM::State::kTriggerOn)
399 {
400 Update(MCP::State::kIdle);
401 return MCP::State::kIdle;
402 }
403
404 if (fDimFAD.state() != FAD::State::kWritingData)
405 return MCP::State::kTriggerOn;
406
407 Update(MCP::State::kTakingData);
408 return MCP::State::kTakingData;
409 }
410
411 // --------------------------------------------------------
412
413 if (GetCurrentState()==MCP::State::kTakingData)
414 {
415 if (fDimFTM.state()==FTM::State::kTriggerOn &&
416 fDimFAD.state()==FAD::State::kWritingData)
417 return MCP::State::kTakingData;
418
419 Update(MCP::State::kIdle);
420 return MCP::State::kIdle;
421 }
422
423 // ========================================================
424 /*
425 if (GetCurrentState()==MCP::State::kCrateReset0)
426 {
427 static const struct Data { int32_t id; char on; } __attribute__((__packed__)) d = { -1, 0 };
428
429 Dim::SendCommandNB("FTM_CONTROL/ENABLE_FTU", &d, sizeof(Data));
430
431 fFadCratesForReset = fFadNeedsReset;
432 fFadBoardsForConnection = fFadConnected;
433
434 for (int c=0; c<4; c++)
435 if (fFadNeedsReset[c])
436 for (int b=0; b<10; b++)
437 Dim::SendCommandNB("FAD_CONTROL/DISCONNECT", uint16_t(c*10+b));
438
439 fNumReset++;
440
441 Update(MCP::State::kCrateReset1);
442 return MCP::State::kCrateReset1;
443 }
444
445 // --------------------------------------------------------
446
447 if (GetCurrentState()==MCP::State::kCrateReset1)
448 {
449 if (fNumConnectedFtu>0 || count(fFadNeedsReset.begin(), fFadNeedsReset.end(), true)>0)
450 return MCP::State::kCrateReset1;
451
452 for (int i=0; i<4; i++)
453 if (fFadCratesForReset[i])
454 Dim::SendCommandNB("FAD_CONTROL/RESET_CRATE", uint16_t(i));
455
456 fFadTimeout = Time();
457
458 Update(MCP::State::kCrateReset2);
459 return MCP::State::kCrateReset2;
460 }
461
462 // --------------------------------------------------------
463
464 if (GetCurrentState()==MCP::State::kCrateReset2)
465 {
466 if (fFadTimeout+boost::posix_time::seconds(45)>Time())
467 return MCP::State::kCrateReset2;
468
469 static const struct Data { int32_t id; char on; } __attribute__((__packed__)) d = { -1, 1 };
470
471 Dim::SendCommandNB("FTM_CONTROL/ENABLE_FTU", &d, sizeof(Data));
472
473 for (int c=0; c<4; c++)
474 if (fFadCratesForReset[c])
475 for (int b=0; b<10; b++)
476 if (fFadBoardsForConnection[c*10+b])
477 Dim::SendCommandNB("FAD_CONTROL/CONNECT", uint16_t(c*10+b));
478
479 Update(MCP::State::kCrateReset3);
480 return MCP::State::kCrateReset3;
481 }
482
483 // --------------------------------------------------------
484
485 if (GetCurrentState()==MCP::State::kCrateReset3)
486 {
487 if (fNumConnectedFtu<40 || fFadBoardsForConnection!=fFadConnected)
488 return MCP::State::kCrateReset3;
489
490 if (count(fFadNeedsReset.begin(), fFadNeedsReset.end(), true)>0 && fNumReset<6)
491 {
492 Update(MCP::State::kCrateReset0);
493 return MCP::State::kCrateReset0;
494 }
495
496 // restart configuration
497 Update(MCP::State::kConfiguring1);
498 return MCP::State::kConfiguring1;
499 }
500 */
501 // ========================================================
502
503 return GetCurrentState();
504 }
505
506public:
507 StateMachineMCP(ostream &out=cout) : StateMachineDim(out, "MCP"),
508 fFadNeedsReset(4), fNumConnectedFtu(40),
509 fDimFTM("FTM_CONTROL"),
510 fDimFAD("FAD_CONTROL"),
511 fDimLog("DATA_LOGGER"),
512 fDimRC("RATE_CONTROL"),
513 fService("MCP/CONFIGURATION", "X:1;X:1;C", "Run configuration information"
514 "|MaxTime[s]:Maximum time before the run gets stopped"
515 "|MaxEvents[num]:Maximum number of events before the run gets stopped"
516 "|Name[text]:Name of the chosen configuration")
517 {
518 // ba::io_service::work is a kind of keep_alive for the loop.
519 // It prevents the io_service to go to stopped state, which
520 // would prevent any consecutive calls to run()
521 // or poll() to do nothing. reset() could also revoke to the
522 // previous state but this might introduce some overhead of
523 // deletion and creation of threads and more.
524
525 fDim.Subscribe(*this);
526 fDimFTM.Subscribe(*this);
527 fDimFAD.Subscribe(*this);
528 fDimLog.Subscribe(*this);
529 fDimRC.Subscribe(*this);
530
531 fDim.SetCallback(bind(&StateMachineMCP::HandleStateChange, this));
532 fDimFTM.SetCallback(bind(&StateMachineMCP::HandleStateChange, this));
533 fDimFAD.SetCallback(bind(&StateMachineMCP::HandleStateChange, this));
534 fDimLog.SetCallback(bind(&StateMachineMCP::HandleStateChange, this));
535 fDimRC.SetCallback(bind(&StateMachineMCP::HandleStateChange, this));
536
537 Subscribe("FAD_CONTROL/CONNECTIONS")
538 (bind(&StateMachineMCP::HandleFadConnections, this, placeholders::_1));
539 Subscribe("FTM_CONTROL/STATIC_DATA")
540 (bind(&StateMachineMCP::HandleFtmStaticData, this, placeholders::_1));
541
542 // State names
543 AddStateName(MCP::State::kDimNetworkNA, "DimNetworkNotAvailable",
544 "DIM dns server not available.");
545 AddStateName(MCP::State::kDisconnected, "Disconnected",
546 "Neither ftmctrl, fadctrl, datalogger nor rate control online.");
547 AddStateName(MCP::State::kConnecting, "Connecting",
548 "Either ftmctrl, fadctrl, datalogger or rate control not online.");
549 AddStateName(MCP::State::kConnected, "Connected",
550 "All needed subsystems online.");
551 AddStateName(MCP::State::kIdle, "Idle",
552 "Waiting for next configuration command");
553 AddStateName(MCP::State::kConfiguring1, "Configuring1",
554 "Starting configuration procedure, checking Datalogger state");
555 AddStateName(MCP::State::kConfiguring2, "Configuring2",
556 "Waiting for FTM and Datalogger to get ready");
557 AddStateName(MCP::State::kConfiguring3, "Configuring3",
558 "Waiting for FADs and rate control to get ready");
559 /*
560 AddStateName(MCP::State::kCrateReset0, "CrateReset0",
561 "Disabling FTUs, disconnecting FADs");
562 AddStateName(MCP::State::kCrateReset1, "CrateReset1",
563 "Waiting for FTUs to be disabled and for FADs to be disconnected");
564 AddStateName(MCP::State::kCrateReset2, "CrateReset2",
565 "Waiting 45s");
566 AddStateName(MCP::State::kCrateReset3, "CrateReset3",
567 "Waiting for FTUs to be enabled and for FADs to be re-connected");
568 */
569 AddStateName(MCP::State::kConfigured, "Configured",
570 "Everything is configured, trigger will be switched on now");
571 AddStateName(MCP::State::kTriggerOn, "TriggerOn",
572 "The trigger is switched on, waiting for FAD to receive data");
573 AddStateName(MCP::State::kTakingData, "TakingData",
574 "The trigger is switched on, FADs are sending data");
575
576
577 AddEvent("START", "X:2;C")//, MCP::State::kIdle)
578 (bind(&StateMachineMCP::StartRun, this, placeholders::_1))
579 ("Start the configuration and data taking for a run-type of a pre-defined setup"
580 "|TimeMax[s]:Maximum number of seconds before the run will be closed automatically"
581 "|NumMax[count]:Maximum number events before the run will be closed automatically"
582 "|Name[text]:Name of the configuration to be used for taking data");
583
584 AddEvent("STOP")
585 (bind(&StateMachineMCP::StopRun, this))
586 ("Stops the trigger (either disables the FTM trigger or the internal DRS trigger)");
587
588 AddEvent("RESET")
589 (bind(&StateMachineMCP::Reset, this))
590 ("If a configuration blockes because a system cannot configure itself properly, "
591 "this command can be called to leave the configuration procedure. The command "
592 "is also propagated to FTM and FAD");
593
594 AddEvent("PRINT")
595 (bind(&StateMachineMCP::Print, this))
596 ("Print the states and connection status of all systems connected to the MCP.");
597 }
598
599 int EvalOptions(Configuration &)
600 {
601 return -1;
602 }
603};
604
605// ------------------------------------------------------------------------
606
607#include "Main.h"
608
609template<class T>
610int RunShell(Configuration &conf)
611{
612 return Main::execute<T, StateMachineMCP>(conf);
613}
614
615/*
616 Extract usage clause(s) [if any] for SYNOPSIS.
617 Translators: "Usage" and "or" here are patterns (regular expressions) which
618 are used to match the usage synopsis in program output. An example from cp
619 (GNU coreutils) which contains both strings:
620 Usage: cp [OPTION]... [-T] SOURCE DEST
621 or: cp [OPTION]... SOURCE... DIRECTORY
622 or: cp [OPTION]... -t DIRECTORY SOURCE...
623 */
624void PrintUsage()
625{
626 cout <<
627 "The ftmctrl controls the FSC (FACT Slow Control) board.\n"
628 "\n"
629 "The default is that the program is started without user intercation. "
630 "All actions are supposed to arrive as DimCommands. Using the -c "
631 "option, a local shell can be initialized. With h or help a short "
632 "help message about the usuage can be brought to the screen.\n"
633 "\n"
634 "Usage: fscctrl [-c type] [OPTIONS]\n"
635 " or: fscctrl [OPTIONS]\n";
636 cout << endl;
637}
638
639void PrintHelp()
640{
641 Main::PrintHelp<StateMachineMCP>();
642
643 /* Additional help text which is printed after the configuration
644 options goes here */
645
646 /*
647 cout << "bla bla bla" << endl << endl;
648 cout << endl;
649 cout << "Environment:" << endl;
650 cout << "environment" << endl;
651 cout << endl;
652 cout << "Examples:" << endl;
653 cout << "test exam" << endl;
654 cout << endl;
655 cout << "Files:" << endl;
656 cout << "files" << endl;
657 cout << endl;
658 */
659}
660
661int main(int argc, const char* argv[])
662{
663 Configuration conf(argv[0]);
664 conf.SetPrintUsage(PrintUsage);
665 Main::SetupConfiguration(conf);
666
667 if (!conf.DoParse(argc, argv, PrintHelp))
668 return 127;
669
670 //try
671 {
672 // No console access at all
673 if (!conf.Has("console"))
674 {
675// if (conf.Get<bool>("no-dim"))
676// return RunShell<LocalStream, StateMachine, ConnectionFSC>(conf);
677// else
678 return RunShell<LocalStream>(conf);
679 }
680 // Cosole access w/ and w/o Dim
681/* if (conf.Get<bool>("no-dim"))
682 {
683 if (conf.Get<int>("console")==0)
684 return RunShell<LocalShell, StateMachine, ConnectionFSC>(conf);
685 else
686 return RunShell<LocalConsole, StateMachine, ConnectionFSC>(conf);
687 }
688 else
689*/ {
690 if (conf.Get<int>("console")==0)
691 return RunShell<LocalShell>(conf);
692 else
693 return RunShell<LocalConsole>(conf);
694 }
695 }
696 /*catch (std::exception& e)
697 {
698 cerr << "Exception: " << e.what() << endl;
699 return -1;
700 }*/
701
702 return 0;
703}
Note: See TracBrowser for help on using the repository browser.