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

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