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

Last change on this file since 14244 was 14244, checked in by tbretz, 12 years ago
Removed a stray line left over from last commit.
File size: 21.6 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#include "Converter.h"
9
10#include "tools.h"
11
12#include "LocalControl.h"
13
14#include "HeadersFTM.h"
15#include "HeadersFAD.h"
16#include "HeadersMCP.h"
17#include "HeadersRateControl.h"
18
19namespace ba = boost::asio;
20namespace bs = boost::system;
21namespace dummy = ba::placeholders;
22
23using namespace std;
24
25// ------------------------------------------------------------------------
26
27#include "DimDescriptionService.h"
28#include "DimState.h"
29
30// ------------------------------------------------------------------------
31
32class StateMachineMCP : public StateMachineDim
33{
34private:
35 vector<bool> fFadConnected;
36 vector<bool> fFadNeedsReset;
37
38 vector<bool> fFadCratesForReset;
39 vector<bool> fFadBoardsForConnection;
40
41 uint16_t fNumConnectedFtu;
42 uint16_t fNumConnectedFad;
43
44 uint16_t fNumReset;
45
46 DimVersion fDim;
47 DimDescribedState fDimFTM;
48 DimDescribedState fDimFAD;
49 DimDescribedState fDimLog;
50 DimDescribedState fDimRC;
51
52 DimDescribedService fService;
53
54 Time fFadTimeout;
55
56 int HandleFadConnections(const EventImp &d)
57 {
58 if (d.GetSize()!=41)
59 return GetCurrentState();
60
61 const uint8_t *ptr = d.Ptr<uint8_t>();
62
63 fNumConnectedFad = 0;
64 fFadConnected.assign(40, false);
65
66 vector<bool> reset(4);
67
68 for (int i=0; i<40; i++)
69 {
70 const uint8_t stat1 = ptr[i]&3;
71 const uint8_t stat2 = ptr[i]>>3;
72
73 // disconnected: ignore
74 if (stat1==0 && stat2==0)
75 continue;
76
77 fFadConnected[i] = true;
78
79 if (stat1>=2 && stat2==8)
80 fNumConnectedFad++;
81
82 // Does not need reset
83 if (stat1>2 && stat2==8)
84 continue;
85
86 // Not configured (stat1==2?kLedGreen:kLedGreenCheck)
87 // Connection problem (stat1==1&&stat2==1?kLedRed:kLedOrange)
88 reset[i/10] = true;
89 }
90 return GetCurrentState();
91 }
92
93 int HandleFtmStaticData(const EventImp &d)
94 {
95 if (d.GetSize()!=sizeof(FTM::DimStaticData))
96 return GetCurrentState();
97
98 const FTM::DimStaticData &sdata = d.Ref<FTM::DimStaticData>();
99
100 fNumConnectedFtu = 0;
101 for (int i=0; i<40; i++)
102 {
103 if (sdata.IsActive(i))
104 fNumConnectedFtu++;
105 }
106 return GetCurrentState();
107 }
108
109 int Print() const
110 {
111 Out() << fDim << endl;
112 Out() << fDimFTM << endl;
113 Out() << fDimFAD << endl;
114 Out() << fDimLog << endl;
115 Out() << fDimRC << endl;
116
117 return GetCurrentState();
118 }
119
120 int GetReady()
121 {
122 return GetCurrentState();
123 }
124
125 int StopRun()
126 {
127 if (fDimFTM.state()==FTM::State::kTriggerOn)
128 {
129 Message("Stopping FTM");
130 Dim::SendCommandNB("FTM_CONTROL/STOP_TRIGGER");
131 }
132
133 // FIXME: Do step 2 only when FTM is stopped
134 if (fDimFAD.state()==FAD::State::kConnected)
135 {
136 //Dim::SendCommand("FAD_CONTROL/ENABLE_TRIGGER_LINE", bool(false));
137 Message("Stopping FAD");
138 Dim::SendCommandNB("FAD_CONTROL/ENABLE_CONTINOUS_TRIGGER", bool(false));
139 }
140
141 return GetCurrentState();
142 }
143
144 int Reset()
145 {
146 if (GetCurrentState()<MCP::State::kConfiguring1 ||
147 GetCurrentState()>MCP::State::kConfigured)
148 return GetCurrentState();
149
150 fRunType = "";
151 Message("Reseting configuration states of FAD and FTM");
152
153 Dim::SendCommandNB("FTM_CONTROL/RESET_CONFIGURE");
154 Dim::SendCommandNB("FAD_CONTROL/RESET_CONFIGURE");
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 Update(MCP::State::kConfiguring2);
313 return MCP::State::kConfiguring2;
314 }
315
316 // --------------------------------------------------------
317
318 if (GetCurrentState()==MCP::State::kConfiguring2)
319 {
320 // FIMXE: Reset in case of error
321 if ((/*fDimFTM.state() != FTM::State::kConfiguring2 &&*/
322 fDimFTM.state() != FTM::State::kConfigured) ||
323 fDimLog.state()<30 || fDimLog.state()>0xff)
324 return MCP::State::kConfiguring2;
325
326 // FIMXE: This is to make sure that the rate control
327 // has received the correct trigger setup already...
328 //usleep(1000000);
329
330 Message("Starting Rate Control");
331 Dim::SendCommandNB("RATE_CONTROL/CALIBRATE");
332
333 ConfigureFAD();
334
335 fFadTimeout = Time();
336
337 Update(MCP::State::kConfiguring3);
338 return MCP::State::kConfiguring3;
339 }
340
341 // --------------------------------------------------------
342
343 if (GetCurrentState()==MCP::State::kConfiguring3)
344 {
345 // If everything is configured but the FADs
346 // we run into a timeout and some FAD need to be reset
347 // then we start an automatic crate reset
348 if (fDimFTM.state() == FTM::State::kConfigured &&
349 fDimFAD.state() != FAD::State::kConfigured &&
350 fDimRC.state() >= RateControl::State::kSettingGlobalThreshold &&
351 fFadTimeout+boost::posix_time::seconds(15)<Time() &&
352 count(fFadNeedsReset.begin(), fFadNeedsReset.end(), true)>0)
353 {
354 Update(MCP::State::kCrateReset0);
355 return MCP::State::kCrateReset0;
356 }
357
358 // If something is not yet properly configured: keep state
359 if (fDimFTM.state() != FTM::State::kConfigured ||
360 fDimFAD.state() != FAD::State::kConfigured ||
361 fDimRC.state() < RateControl::State::kSettingGlobalThreshold)
362 return MCP::State::kConfiguring3;
363
364 Message("Starting Trigger (FTM)");
365 Dim::SendCommandNB("FTM_CONTROL/START_TRIGGER");
366
367 Update(MCP::State::kConfigured);
368 return MCP::State::kConfigured;
369 }
370
371 // --------------------------------------------------------
372
373 if (GetCurrentState()==MCP::State::kConfigured)
374 {
375 if (fDimFTM.state() != FTM::State::kTriggerOn)
376 return MCP::State::kConfigured;
377
378 Update(MCP::State::kTriggerOn);
379 return MCP::State::kTriggerOn;
380 }
381
382 // --------------------------------------------------------
383
384 if (GetCurrentState()==MCP::State::kTriggerOn)
385 {
386 if (fDimFAD.state() != FAD::State::kWritingData)
387 return MCP::State::kTriggerOn;
388
389 Update(MCP::State::kTakingData);
390 return MCP::State::kTakingData;
391 }
392
393 // --------------------------------------------------------
394
395 if (GetCurrentState()==MCP::State::kTakingData)
396 {
397 if (fDimFTM.state()==FTM::State::kTriggerOn &&
398 fDimFAD.state()==FAD::State::kWritingData)
399 return MCP::State::kTakingData;
400
401 Update(MCP::State::kIdle);
402 return MCP::State::kIdle;
403 }
404
405 // ========================================================
406
407 if (GetCurrentState()==MCP::State::kCrateReset0)
408 {
409 static const struct Data { int32_t id; char on; } __attribute__((__packed__)) d = { -1, 0 };
410
411 Dim::SendCommandNB("FTM_CONTROL/ENABLE_FTU", &d, sizeof(Data));
412
413 fFadCratesForReset = fFadNeedsReset;
414 fFadBoardsForConnection = fFadConnected;
415
416 for (int c=0; c<4; c++)
417 if (fFadNeedsReset[c])
418 for (int b=0; b<10; b++)
419 Dim::SendCommandNB("FAD_CONTROL/DISCONNECT", uint16_t(c*10+b));
420
421 fNumReset++;
422
423 Update(MCP::State::kCrateReset1);
424 return MCP::State::kCrateReset1;
425 }
426
427 // --------------------------------------------------------
428
429 if (GetCurrentState()==MCP::State::kCrateReset1)
430 {
431 if (fNumConnectedFtu>0 || count(fFadNeedsReset.begin(), fFadNeedsReset.end(), true)>0)
432 return MCP::State::kCrateReset1;
433
434 for (int i=0; i<4; i++)
435 if (fFadCratesForReset[i])
436 Dim::SendCommandNB("FAD_CONTROL/RESET_CRATE", uint16_t(i));
437
438 fFadTimeout = Time();
439
440 Update(MCP::State::kCrateReset2);
441 return MCP::State::kCrateReset2;
442 }
443
444 // --------------------------------------------------------
445
446 if (GetCurrentState()==MCP::State::kCrateReset2)
447 {
448 if (fFadTimeout+boost::posix_time::seconds(45)>Time())
449 return MCP::State::kCrateReset2;
450
451 static const struct Data { int32_t id; char on; } __attribute__((__packed__)) d = { -1, 1 };
452
453 Dim::SendCommandNB("FTM_CONTROL/ENABLE_FTU", &d, sizeof(Data));
454
455 for (int c=0; c<4; c++)
456 if (fFadCratesForReset[c])
457 for (int b=0; b<10; b++)
458 if (fFadBoardsForConnection[c*10+b])
459 Dim::SendCommandNB("FAD_CONTROL/CONNECT", uint16_t(c*10+b));
460
461 Update(MCP::State::kCrateReset3);
462 return MCP::State::kCrateReset3;
463 }
464
465 // --------------------------------------------------------
466
467 if (GetCurrentState()==MCP::State::kCrateReset3)
468 {
469 if (fNumConnectedFtu<40 || fFadBoardsForConnection!=fFadConnected)
470 return MCP::State::kCrateReset3;
471
472 if (count(fFadNeedsReset.begin(), fFadNeedsReset.end(), true)>0 && fNumReset<6)
473 {
474 Update(MCP::State::kCrateReset0);
475 return MCP::State::kCrateReset0;
476 }
477
478 // restart configuration
479 Update(MCP::State::kConfiguring1);
480 return MCP::State::kConfiguring1;
481 }
482
483 // ========================================================
484
485 return GetCurrentState();
486 }
487
488public:
489 StateMachineMCP(ostream &out=cout) : StateMachineDim(out, "MCP"),
490 fFadNeedsReset(4), fNumConnectedFtu(40),
491 fDimFTM("FTM_CONTROL"),
492 fDimFAD("FAD_CONTROL"),
493 fDimLog("DATA_LOGGER"),
494 fDimRC("RATE_CONTROL"),
495 fService("MCP/CONFIGURATION", "X:1;X:1;C", "Run configuration information"
496 "|MaxTime[s]:Maximum time before the run gets stopped"
497 "|MaxEvents[num]:Maximum number of events before the run gets stopped"
498 "|Name[text]:Name of the chosen configuration")
499 {
500 // ba::io_service::work is a kind of keep_alive for the loop.
501 // It prevents the io_service to go to stopped state, which
502 // would prevent any consecutive calls to run()
503 // or poll() to do nothing. reset() could also revoke to the
504 // previous state but this might introduce some overhead of
505 // deletion and creation of threads and more.
506
507 fDim.Subscribe(*this);
508 fDimFTM.Subscribe(*this);
509 fDimFAD.Subscribe(*this);
510 fDimLog.Subscribe(*this);
511 fDimRC.Subscribe(*this);
512
513 fDim.SetCallback(bind(&StateMachineMCP::HandleStateChange, this));
514 fDimFTM.SetCallback(bind(&StateMachineMCP::HandleStateChange, this));
515 fDimFAD.SetCallback(bind(&StateMachineMCP::HandleStateChange, this));
516 fDimLog.SetCallback(bind(&StateMachineMCP::HandleStateChange, this));
517 fDimRC.SetCallback(bind(&StateMachineMCP::HandleStateChange, this));
518
519 Subscribe("FAD_CONTROL/CONNECTIONS")
520 (bind(&StateMachineMCP::HandleFadConnections, this, placeholders::_1));
521 Subscribe("FTM_CONTROL/STATIC_DATA")
522 (bind(&StateMachineMCP::HandleFtmStaticData, this, placeholders::_1));
523
524 // State names
525 AddStateName(MCP::State::kDimNetworkNA, "DimNetworkNotAvailable",
526 "DIM dns server not available.");
527 AddStateName(MCP::State::kDisconnected, "Disconnected",
528 "Neither ftmctrl, fadctrl, datalogger nor rate control online.");
529 AddStateName(MCP::State::kConnecting, "Connecting",
530 "Either ftmctrl, fadctrl, datalogger or rate control not online.");
531 AddStateName(MCP::State::kConnected, "Connected",
532 "All needed subsystems online.");
533 AddStateName(MCP::State::kIdle, "Idle",
534 "Waiting for next configuration command");
535 AddStateName(MCP::State::kConfiguring1, "Configuring1",
536 "Starting configuration procedure, checking Datalogger state");
537 AddStateName(MCP::State::kConfiguring2, "Configuring2",
538 "Waiting for FTM and Datalogger to get ready");
539 AddStateName(MCP::State::kConfiguring3, "Configuring3",
540 "Waiting for FADs and rate control to get ready");
541
542 AddStateName(MCP::State::kCrateReset0, "CrateReset0",
543 "Disabling FTUs, disconnecting FADs");
544 AddStateName(MCP::State::kCrateReset1, "CrateReset1",
545 "Waiting for FTUs to be disabled and for FADs to be disconnected");
546 AddStateName(MCP::State::kCrateReset2, "CrateReset2",
547 "Waiting 45s");
548 AddStateName(MCP::State::kCrateReset3, "CrateReset3",
549 "Waiting for FTUs to be enabled and for FADs to be re-connected");
550
551 AddStateName(MCP::State::kConfigured, "Configured",
552 "Everything is configured, trigger will be switched on now");
553 AddStateName(MCP::State::kTriggerOn, "TriggerOn",
554 "The trigger is switched on, waiting for FAD to receive data");
555 AddStateName(MCP::State::kTakingData, "TakingData",
556 "The trigger is switched on, FADs are sending data");
557
558
559 AddEvent("START", "X:2;C")//, MCP::State::kIdle)
560 (bind(&StateMachineMCP::StartRun, this, placeholders::_1))
561 ("Start the configuration and data taking for a run-type of a pre-defined setup"
562 "|TimeMax[s]:Maximum number of seconds before the run will be closed automatically"
563 "|NumMax[count]:Maximum number events before the run will be closed automatically"
564 "|Name[text]:Name of the configuration to be used for taking data");
565
566 AddEvent("STOP")
567 (bind(&StateMachineMCP::StopRun, this))
568 ("Stops the trigger (either disables the FTM trigger or the internal DRS trigger)");
569
570 AddEvent("RESET")
571 (bind(&StateMachineMCP::Reset, this))
572 ("If a configuration blockes because a system cannot configure itself properly, "
573 "this command can be called to leave the configuration procedure. The command "
574 "is also propagated to FTM and FAD");
575
576 AddEvent("PRINT")
577 (bind(&StateMachineMCP::Print, this))
578 ("Print the states and connection status of all systems connected to the MCP.");
579 }
580
581 int EvalOptions(Configuration &)
582 {
583 return -1;
584 }
585};
586
587// ------------------------------------------------------------------------
588
589#include "Main.h"
590
591template<class T>
592int RunShell(Configuration &conf)
593{
594 return Main::execute<T, StateMachineMCP>(conf);
595}
596
597/*
598 Extract usage clause(s) [if any] for SYNOPSIS.
599 Translators: "Usage" and "or" here are patterns (regular expressions) which
600 are used to match the usage synopsis in program output. An example from cp
601 (GNU coreutils) which contains both strings:
602 Usage: cp [OPTION]... [-T] SOURCE DEST
603 or: cp [OPTION]... SOURCE... DIRECTORY
604 or: cp [OPTION]... -t DIRECTORY SOURCE...
605 */
606void PrintUsage()
607{
608 cout <<
609 "The ftmctrl controls the FSC (FACT Slow Control) board.\n"
610 "\n"
611 "The default is that the program is started without user intercation. "
612 "All actions are supposed to arrive as DimCommands. Using the -c "
613 "option, a local shell can be initialized. With h or help a short "
614 "help message about the usuage can be brought to the screen.\n"
615 "\n"
616 "Usage: fscctrl [-c type] [OPTIONS]\n"
617 " or: fscctrl [OPTIONS]\n";
618 cout << endl;
619}
620
621void PrintHelp()
622{
623 Main::PrintHelp<StateMachineMCP>();
624
625 /* Additional help text which is printed after the configuration
626 options goes here */
627
628 /*
629 cout << "bla bla bla" << endl << endl;
630 cout << endl;
631 cout << "Environment:" << endl;
632 cout << "environment" << endl;
633 cout << endl;
634 cout << "Examples:" << endl;
635 cout << "test exam" << endl;
636 cout << endl;
637 cout << "Files:" << endl;
638 cout << "files" << endl;
639 cout << endl;
640 */
641}
642
643int main(int argc, const char* argv[])
644{
645 Configuration conf(argv[0]);
646 conf.SetPrintUsage(PrintUsage);
647 Main::SetupConfiguration(conf);
648
649 if (!conf.DoParse(argc, argv, PrintHelp))
650 return 127;
651
652 //try
653 {
654 // No console access at all
655 if (!conf.Has("console"))
656 {
657// if (conf.Get<bool>("no-dim"))
658// return RunShell<LocalStream, StateMachine, ConnectionFSC>(conf);
659// else
660 return RunShell<LocalStream>(conf);
661 }
662 // Cosole access w/ and w/o Dim
663/* if (conf.Get<bool>("no-dim"))
664 {
665 if (conf.Get<int>("console")==0)
666 return RunShell<LocalShell, StateMachine, ConnectionFSC>(conf);
667 else
668 return RunShell<LocalConsole, StateMachine, ConnectionFSC>(conf);
669 }
670 else
671*/ {
672 if (conf.Get<int>("console")==0)
673 return RunShell<LocalShell>(conf);
674 else
675 return RunShell<LocalConsole>(conf);
676 }
677 }
678 /*catch (std::exception& e)
679 {
680 cerr << "Exception: " << e.what() << endl;
681 return -1;
682 }*/
683
684 return 0;
685}
Note: See TracBrowser for help on using the repository browser.