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

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