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

Last change on this file since 12405 was 12405, checked in by tbretz, 13 years ago
Replaced START_RUN by START_TRIGGER
File size: 14.9 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#include "DimServiceInfoList.h"
10
11#include "tools.h"
12
13#include "LocalControl.h"
14
15#include "HeadersFTM.h"
16#include "HeadersFAD.h"
17
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
29// ------------------------------------------------------------------------
30
31class StateMachineMCP : public StateMachineDim, public DimInfoHandler
32{
33 /*
34 int Wrap(boost::function<void()> f)
35 {
36 f();
37 return T::GetCurrentState();
38 }
39
40 boost::function<int(const EventImp &)> Wrapper(boost::function<void()> func)
41 {
42 return bind(&StateMachineMCP::Wrap, this, func);
43 }*/
44
45private:
46 enum states_t
47 {
48 kStateDimNetworkNA = 1,
49 kStateDisconnected,
50 kStateConnecting,
51 kStateConnected,
52 kStateIdle,
53 kStateReadyForDataTaking,
54 kStateConfiguring1,
55 kStateConfiguring2,
56 kStateConfiguring3,
57 kStateConfigured,
58// kStateRunInProgress,
59 };
60
61 DimServiceInfoList fNetwork;
62
63 pair<Time, int> fStatusDim;
64 pair<Time, int> fStatusFTM;
65 pair<Time, int> fStatusFAD;
66 pair<Time, int> fStatusLog;
67
68 DimStampedInfo fDim;
69 DimStampedInfo fFTM;
70 DimStampedInfo fFAD;
71 DimStampedInfo fLog;
72
73 pair<Time, int> GetNewState(DimStampedInfo &info) const
74 {
75 const bool disconnected = info.getSize()==0;
76
77 // Make sure getTimestamp is called _before_ getTimestampMillisecs
78 const int tsec = info.getTimestamp();
79 const int tms = info.getTimestampMillisecs();
80
81 return make_pair(Time(tsec, tms*1000),
82 disconnected ? -2 : info.getQuality());
83 }
84
85 void infoHandler()
86 {
87 DimInfo *curr = getInfo(); // get current DimInfo address
88 if (!curr)
89 return;
90
91 if (curr==&fFTM)
92 {
93 fStatusFTM = GetNewState(fFTM);
94 return;
95 }
96
97 if (curr==&fFAD)
98 {
99 fStatusFAD = GetNewState(fFAD);
100 return;
101 }
102
103 if (curr==&fLog)
104 {
105 fStatusLog = GetNewState(fLog);
106 return;
107 }
108
109 if (curr==&fDim)
110 {
111 fStatusDim = GetNewState(fDim);
112 fStatusDim.second = curr->getSize()==4 ? curr->getInt() : 0;
113 return;
114 }
115
116 }
117
118 bool CheckEventSize(size_t has, const char *name, size_t size)
119 {
120 if (has==size)
121 return true;
122
123 ostringstream msg;
124 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
125 Fatal(msg);
126 return false;
127 }
128
129 int SetVerbosity(const EventImp &)
130 {
131 /*
132 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
133 return T::kSM_FatalError;
134
135 fFSC.SetVerbose(evt.GetBool());
136
137 */
138
139 return GetCurrentState();
140 }
141
142
143 void PrintState(const pair<Time,int> &state, const char *server)
144 {
145 const State rc = fNetwork.GetState(server, state.second);
146
147 Out() << state.first.GetAsStr("%H:%M:%S.%f").substr(0, 12) << " - ";
148 Out() << kBold << server << ": ";
149 Out() << rc.name << "[" << rc.index << "]";
150 Out() << kReset << " - " << kBlue << rc.comment << endl;
151 }
152
153 int Print()
154 {
155 Out() << fStatusDim.first.GetAsStr("%H:%M:%S.%f").substr(0, 12) << " - ";
156 Out() << kBold << "DIM_DNS: ";
157 if (fStatusDim.second==0)
158 Out() << "Offline" << endl;
159 else
160 Out() << "V" << fStatusDim.second/100 << 'r' << fStatusDim.second%100 << endl;
161
162 PrintState(fStatusFTM, "FTM_CONTROL");
163 PrintState(fStatusFAD, "FAD_CONTROL");
164 PrintState(fStatusLog, "DATA_LOGGER");
165
166 return GetCurrentState();
167 }
168
169 int GetReady()
170 {
171
172 return GetCurrentState();
173 }
174
175 int StopRun(const EventImp &)
176 {
177 if (fStatusFTM.second==FTM::kTriggerOn)
178 {
179 Message("Stopping FTM");
180 Dim::SendCommand("FTM_CONTROL/STOP_TRIGGER");
181 }
182
183 // FIXME: Do step 2 only when FTM is stopped
184 if (fStatusFAD.second==FAD::kConnected)
185 {
186 //Dim::SendCommand("FAD_CONTROL/ENABLE_TRIGGER_LINE", bool(false));
187 Message("Stopping FAD");
188 Dim::SendCommand("FAD_CONTROL/ENABLE_CONTINOUS_TRIGGER", bool(false));
189 }
190
191 return GetCurrentState();
192 }
193
194 int Reset(const EventImp &)
195 {
196 fRunType = "";
197 Message("Reseting configuration states of FAD and FTM");
198 Dim::SendCommand("FTM_CONTROL/RESET_CONFIGURE");
199 Dim::SendCommand("FAD_CONTROL/RESET_CONFIGURE");
200 return kStateIdle;
201 /*
202 // FIMXE: Handle error states!
203 if (fStatusLog.second>=20)//kSM_NightlyOpen
204 Dim::SendCommand("DATA_LOGGER/STOP");
205
206 if (fStatusLog.second==0)
207 Dim::SendCommand("DATA_LOGGER/WAIT_FOR_RUN_NUMBER");
208
209 if (fStatusFAD.second==FAD::kConnected)
210 {
211 Dim::SendCommand("FAD_CONTROL/ENABLE_TRIGGER_LINE", bool(false));
212 Dim::SendCommand("FAD_CONTROL/ENABLE_CONTINOUS_TRIGGER", bool(false));
213 }
214
215 if (fStatusFTM.second==FTM::kTakingData)
216 Dim::SendCommand("FTM_CONTROL/STOP");
217
218 return GetCurrentState(); */
219 }
220
221 uint64_t fMaxTime;
222 uint64_t fNumEvents;
223 string fRunType;
224
225 int StartRun(const EventImp &evt)
226 {
227 fMaxTime = evt.Get<int64_t>();
228 fNumEvents = evt.Get<int64_t>(8);
229 fRunType = evt.Ptr<char>(16);
230
231 ostringstream str;
232 str << "Starting configuration '" << fRunType << "' for new run";
233 if (fNumEvents>0 || fMaxTime>0)
234 str << " [";
235 if (fNumEvents>0)
236 str << fNumEvents << " events";
237 if (fNumEvents>0 && fMaxTime>0)
238 str << " / ";
239 if (fMaxTime>0)
240 str << fMaxTime << "s";
241 if (fNumEvents>0 || fMaxTime>0)
242 str << "]";
243 Message(str);
244
245 return kStateConfiguring1;
246 }
247
248 void ConfigureFAD()
249 {
250 struct Value
251 {
252 uint64_t time;
253 uint64_t nevts;
254 char type[];
255 };
256
257 const size_t len = sizeof(Value)+fRunType.length()+1;
258
259 char *buf = new char[len];
260
261 Value *val = reinterpret_cast<Value*>(buf);
262
263 val->time = fMaxTime;
264 val->nevts = fNumEvents;
265
266 strcpy(val->type, fRunType.c_str());
267
268 Message("Configuring FAD");
269 Dim::SendCommand("FAD_CONTROL/CONFIGURE", buf, len);
270
271 delete buf;
272 }
273
274 int Execute()
275 {
276 // Dispatch (execute) at most one handler from the queue. In contrary
277 // to run_one(), it doesn't wait until a handler is available
278 // which can be dispatched, so poll_one() might return with 0
279 // handlers dispatched. The handlers are always dispatched/executed
280 // synchronously, i.e. within the call to poll_one()
281 //poll_one();
282
283 if (fStatusDim.second==0)
284 return kStateDimNetworkNA;
285
286 if (fStatusFTM.second >= FTM::kConnected &&
287 fStatusFAD.second >= FAD::kConnected &&
288 fStatusLog.second >= kSM_Ready)
289 {
290 if (GetCurrentState()==kStateConfiguring1)
291 {
292 if (fStatusLog.second<30/*kSM_WaitForRun*/)
293 {
294 Message("Starting datalogger");
295 Dim::SendCommand("DATA_LOGGER/START_RUN_LOGGING");
296 }
297 Message("Configuring Trigger (FTM)");
298 Dim::SendCommand("FTM_CONTROL/CONFIGURE", fRunType);
299 return kStateConfiguring2;
300 }
301
302 if (GetCurrentState()==kStateConfiguring2)
303 {
304 // FIMXE: Reset in case of error
305 if ((fStatusFTM.second != FTM::kConfiguring2 &&
306 fStatusFTM.second != FTM::kConfigured) ||
307 fStatusLog.second<30 || fStatusLog.second>0xff)
308 return GetCurrentState();
309
310 Message("Starting FAD");
311 ConfigureFAD();
312 return kStateConfiguring3;
313 }
314
315 if (GetCurrentState()==kStateConfiguring3)
316 {
317 if (fStatusFTM.second != FTM::kConfigured ||
318 fStatusFAD.second != FAD::kConfigured)
319 return GetCurrentState();
320
321 Message("Starting Trigger (FTM)");
322 Dim::SendCommand("FTM_CONTROL/START_TRIGGER");
323 return kStateConfigured;
324 }
325
326 if (GetCurrentState()==kStateConfigured)
327 {
328 if (fStatusFTM.second != FTM::kTriggerOn)
329 return GetCurrentState();
330
331 // Now we are taking data... we could now wait for
332 // the fad to go back to -1
333 }
334
335 return kStateIdle;
336 }
337
338 /*
339 if (fStatusFTM.second >= FTM::kConnected &&
340 fStatusFAD.second >= FAD::kConnected &&
341 fStatusLog.second >= kSM_Ready)
342 return kStateIdle;
343 */
344 if (fStatusFTM.second >-2 &&
345 fStatusFAD.second >-2 &&
346 fStatusLog.second >-2)
347 return kStateConnected;
348
349 if (fStatusFTM.second >-2 ||
350 fStatusFAD.second >-2 ||
351 fStatusLog.second >-2)
352 return kStateConnecting;
353
354 return kStateDisconnected;
355 }
356
357public:
358 StateMachineMCP(ostream &out=cout) : StateMachineDim(out, "MCP"),
359 fStatusDim(make_pair(Time(), -2)),
360 fStatusFTM(make_pair(Time(), -2)),
361 fStatusFAD(make_pair(Time(), -2)),
362 fStatusLog(make_pair(Time(), -2)),
363 fDim("DIS_DNS/VERSION_NUMBER", (void*)NULL, 0, this),
364 fFTM("FTM_CONTROL/STATE", (void*)NULL, 0, this),
365 fFAD("FAD_CONTROL/STATE", (void*)NULL, 0, this),
366 fLog("DATA_LOGGER/STATE", (void*)NULL, 0, this)
367 {
368 // ba::io_service::work is a kind of keep_alive for the loop.
369 // It prevents the io_service to go to stopped state, which
370 // would prevent any consecutive calls to run()
371 // or poll() to do nothing. reset() could also revoke to the
372 // previous state but this might introduce some overhead of
373 // deletion and creation of threads and more.
374
375 // State names
376 AddStateName(kStateDimNetworkNA, "DimNetworkNotAvailable",
377 ".");
378
379 AddStateName(kStateDisconnected, "Disconnected",
380 ".");
381
382 AddStateName(kStateConnecting, "Connecting",
383 ".");
384
385 AddStateName(kStateConnected, "Connected",
386 ".");
387
388 AddStateName(kStateIdle, "Idle",
389 ".");
390
391 AddStateName(kStateReadyForDataTaking, "ReadyForDataTaking",
392 ".");
393
394 AddStateName(kStateConfiguring1, "Configuring1",
395 ".");
396
397 AddStateName(kStateConfiguring2, "Configuring2",
398 "Waiting for FTM and Datalogger to get ready");
399
400 AddStateName(kStateConfiguring3, "Configuring3",
401 "Waiting for FAD to get ready");
402
403 AddStateName(kStateConfigured, "Configured",
404 ".");
405
406
407 AddEvent("START", "X:2;C")//, kStateIdle)
408 (bind(&StateMachineMCP::StartRun, this, placeholders::_1))
409 ("");
410
411 AddEvent("STOP")
412 (bind(&StateMachineMCP::StopRun, this, placeholders::_1))
413 ("");
414
415 AddEvent("RESET", kStateConfiguring1, kStateConfiguring2, kStateConfiguring3, kStateConfigured)
416 (bind(&StateMachineMCP::Reset, this, placeholders::_1))
417 ("");
418
419 // Verbosity commands
420 AddEvent("SET_VERBOSE", "B:1")
421 (bind(&StateMachineMCP::SetVerbosity, this, placeholders::_1))
422 ("set verbosity state"
423 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
424
425 AddEvent("PRINT")
426 (bind(&StateMachineMCP::Print, this))
427 ("");
428 }
429
430 int EvalOptions(Configuration &)
431 {
432 //SetEndpoint(conf.Get<string>("addr"));
433
434 //fFSC.SetVerbose(!conf.Get<bool>("quiet"));
435
436 return -1;
437 }
438};
439
440// ------------------------------------------------------------------------
441
442#include "Main.h"
443
444template<class T>
445int RunShell(Configuration &conf)
446{
447 return Main::execute<T, StateMachineMCP>(conf);
448}
449
450/*
451 Extract usage clause(s) [if any] for SYNOPSIS.
452 Translators: "Usage" and "or" here are patterns (regular expressions) which
453 are used to match the usage synopsis in program output. An example from cp
454 (GNU coreutils) which contains both strings:
455 Usage: cp [OPTION]... [-T] SOURCE DEST
456 or: cp [OPTION]... SOURCE... DIRECTORY
457 or: cp [OPTION]... -t DIRECTORY SOURCE...
458 */
459void PrintUsage()
460{
461 cout <<
462 "The ftmctrl controls the FSC (FACT Slow Control) board.\n"
463 "\n"
464 "The default is that the program is started without user intercation. "
465 "All actions are supposed to arrive as DimCommands. Using the -c "
466 "option, a local shell can be initialized. With h or help a short "
467 "help message about the usuage can be brought to the screen.\n"
468 "\n"
469 "Usage: fscctrl [-c type] [OPTIONS]\n"
470 " or: fscctrl [OPTIONS]\n";
471 cout << endl;
472}
473
474void PrintHelp()
475{
476 Main::PrintHelp<StateMachineMCP>();
477
478 /* Additional help text which is printed after the configuration
479 options goes here */
480
481 /*
482 cout << "bla bla bla" << endl << endl;
483 cout << endl;
484 cout << "Environment:" << endl;
485 cout << "environment" << endl;
486 cout << endl;
487 cout << "Examples:" << endl;
488 cout << "test exam" << endl;
489 cout << endl;
490 cout << "Files:" << endl;
491 cout << "files" << endl;
492 cout << endl;
493 */
494}
495
496int main(int argc, const char* argv[])
497{
498 Configuration conf(argv[0]);
499 conf.SetPrintUsage(PrintUsage);
500 Main::SetupConfiguration(conf);
501
502 if (!conf.DoParse(argc, argv, PrintHelp))
503 return -1;
504
505 //try
506 {
507 // No console access at all
508 if (!conf.Has("console"))
509 {
510// if (conf.Get<bool>("no-dim"))
511// return RunShell<LocalStream, StateMachine, ConnectionFSC>(conf);
512// else
513 return RunShell<LocalStream>(conf);
514 }
515 // Cosole access w/ and w/o Dim
516/* if (conf.Get<bool>("no-dim"))
517 {
518 if (conf.Get<int>("console")==0)
519 return RunShell<LocalShell, StateMachine, ConnectionFSC>(conf);
520 else
521 return RunShell<LocalConsole, StateMachine, ConnectionFSC>(conf);
522 }
523 else
524*/ {
525 if (conf.Get<int>("console")==0)
526 return RunShell<LocalShell>(conf);
527 else
528 return RunShell<LocalConsole>(conf);
529 }
530 }
531 /*catch (std::exception& e)
532 {
533 cerr << "Exception: " << e.what() << endl;
534 return -1;
535 }*/
536
537 return 0;
538}
Note: See TracBrowser for help on using the repository browser.