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

Last change on this file since 11494 was 11494, checked in by tbretz, 13 years ago
Added some code to stop the ftm and the fads.
File size: 17.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 &evt)
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 &evt)
175 {
176 if (fStatusFTM.second==FTM::kTakingData)
177 Dim::SendCommand("FTM_CONTROL/STOP");
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 &evt)
190 {
191 fRunType = "";
192 return kStateIdle;
193 /*
194 // FIMXE: Handle error states!
195 if (fStatusLog.second>=20)//kSM_NightlyOpen
196 Dim::SendCommand("DATA_LOGGER/STOP");
197
198 if (fStatusLog.second==0)
199 Dim::SendCommand("DATA_LOGGER/WAIT_FOR_RUN_NUMBER");
200
201 if (fStatusFAD.second==FAD::kConnected)
202 {
203 Dim::SendCommand("FAD_CONTROL/ENABLE_TRIGGER_LINE", bool(false));
204 Dim::SendCommand("FAD_CONTROL/ENABLE_CONTINOUS_TRIGGER", bool(false));
205 }
206
207 if (fStatusFTM.second==FTM::kTakingData)
208 Dim::SendCommand("FTM_CONTROL/STOP");
209
210 return GetCurrentState(); */
211 }
212
213 string fRunType;
214
215 int StartRun(const EventImp &evt)
216 {
217 Message("Starting configuration '"+evt.GetString()+"' for new run.");
218 fRunType = evt.GetString();
219 return kStateConfiguring1;
220 }
221
222 int Execute()
223 {
224 // Dispatch (execute) at most one handler from the queue. In contrary
225 // to run_one(), it doesn't wait until a handler is available
226 // which can be dispatched, so poll_one() might return with 0
227 // handlers dispatched. The handlers are always dispatched/executed
228 // synchronously, i.e. within the call to poll_one()
229 //poll_one();
230
231 if (fStatusDim.second==0)
232 return kStateDimNetworkNA;
233
234 if (fStatusFTM.second >= FTM::kConnected &&
235 fStatusFAD.second >= FAD::kConnected &&
236 fStatusLog.second >= kSM_Ready)
237 {
238 if (GetCurrentState()==kStateConfiguring1)
239 {
240 if (fStatusLog.second!=30/*kSM_WaitForRun*/)
241 Dim::SendCommand("DATA_LOGGER/WAIT_FOR_RUN_NUMBER");
242 Dim::SendCommand("FTM_CONTROL/CONFIGURE", fRunType);
243 return kStateConfiguring2;
244 }
245
246 if (GetCurrentState()==kStateConfiguring2)
247 {
248 if ((fStatusFTM.second != FTM::kConfiguring2 &&
249 fStatusFTM.second != FTM::kConfigured) ||
250 fStatusLog.second != 30/*kSM_WaitForRun*/)
251 return GetCurrentState();
252
253 Dim::SendCommand("FAD_CONTROL/CONFIGURE", fRunType);
254 return kStateConfiguring3;
255 }
256
257 if (GetCurrentState()==kStateConfiguring3)
258 {
259 if (fStatusFTM.second != FTM::kConfigured ||
260 fStatusFAD.second != FAD::kConfigured)
261 return GetCurrentState();
262
263 Message("START DATA TAKING");
264 Fatal("Distribute run-number to start datalogger!");
265 //Fatal("Must configure if FTM should be started or not?");
266 Dim::SendCommand("FTM_CONTROL/START_RUN");
267 return kStateConfigured;
268 }
269
270 if (GetCurrentState()==kStateConfigured)
271 return GetCurrentState();
272
273 return kStateIdle;
274 }
275
276 /*
277 if (fStatusFTM.second >= FTM::kConnected &&
278 fStatusFAD.second >= FAD::kConnected &&
279 fStatusLog.second >= kSM_Ready)
280 return kStateIdle;
281 */
282 if (fStatusFTM.second >-2 &&
283 fStatusFAD.second >-2 &&
284 fStatusLog.second >-2)
285 return kStateConnected;
286
287 if (fStatusFTM.second >-2 ||
288 fStatusFAD.second >-2 ||
289 fStatusLog.second >-2)
290 return kStateConnecting;
291
292 return kStateDisconnected;
293 }
294
295public:
296 StateMachineMCP(ostream &out=cout) : StateMachineDim(out, "MCP"),
297 fStatusDim(make_pair(Time(), -2)),
298 fStatusFTM(make_pair(Time(), -2)),
299 fStatusFAD(make_pair(Time(), -2)),
300 fStatusLog(make_pair(Time(), -2)),
301 fDim("DIS_DNS/VERSION_NUMBER", (void*)NULL, 0, this),
302 fFTM("FTM_CONTROL/STATE", (void*)NULL, 0, this),
303 fFAD("FAD_CONTROL/STATE", (void*)NULL, 0, this),
304 fLog("DATA_LOGGER/STATE", (void*)NULL, 0, this)
305 {
306 // ba::io_service::work is a kind of keep_alive for the loop.
307 // It prevents the io_service to go to stopped state, which
308 // would prevent any consecutive calls to run()
309 // or poll() to do nothing. reset() could also revoke to the
310 // previous state but this might introduce some overhead of
311 // deletion and creation of threads and more.
312
313 // State names
314 AddStateName(kStateDimNetworkNA, "DimNetworkNotAvailable",
315 ".");
316
317 AddStateName(kStateDisconnected, "Disconnected",
318 ".");
319
320 AddStateName(kStateConnecting, "Connecting",
321 ".");
322
323 AddStateName(kStateConnected, "Connected",
324 ".");
325
326 AddStateName(kStateIdle, "Idle",
327 ".");
328
329 AddStateName(kStateReadyForDataTaking, "ReadyForDataTaking",
330 ".");
331
332 AddStateName(kStateConfiguring1, "Configuring1",
333 ".");
334
335 AddStateName(kStateConfiguring2, "Configuring2",
336 ".");
337
338 AddStateName(kStateConfiguring3, "Configuring3",
339 ".");
340
341 AddStateName(kStateConfigured, "Configured",
342 ".");
343
344
345 AddEvent("START", "C", kStateIdle)
346 (bind(&StateMachineMCP::StartRun, this, placeholders::_1))
347 ("");
348
349 AddEvent("STOP")
350 (bind(&StateMachineMCP::StopRun, this, placeholders::_1))
351 ("");
352
353 AddEvent("RESET", kStateConfiguring1, kStateConfiguring2, kStateConfigured)
354 (bind(&StateMachineMCP::Reset, this, placeholders::_1))
355 ("");
356
357 // Verbosity commands
358 AddEvent("SET_VERBOSE", "B:1")
359 (bind(&StateMachineMCP::SetVerbosity, this, placeholders::_1))
360 ("set verbosity state"
361 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
362
363 AddEvent("PRINT")
364 (bind(&StateMachineMCP::Print, this))
365 ("");
366 }
367
368 int EvalOptions(Configuration &conf)
369 {
370 //SetEndpoint(conf.Get<string>("addr"));
371
372 //fFSC.SetVerbose(!conf.Get<bool>("quiet"));
373
374 return -1;
375 }
376};
377
378// ------------------------------------------------------------------------
379
380#include "Main.h"
381
382/*
383void RunThread(StateMachineImp *io_service)
384{
385 // This is necessary so that the StateMachien Thread can signal the
386 // Readline to exit
387 io_service->Run();
388 Readline::Stop();
389}
390*/
391/*
392template<class S, class T>
393int RunDim(Configuration &conf)
394{
395 WindowLog wout;
396
397 ReadlineColor::PrintBootMsg(wout, conf.GetName(), false);
398
399
400 if (conf.Has("log"))
401 if (!wout.OpenLogFile(conf.Get<string>("log")))
402 wout << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
403
404 // Start io_service.Run to use the StateMachineImp::Run() loop
405 // Start io_service.run to only use the commandHandler command detaching
406 StateMachineMCP<S, T> io_service(wout);
407 if (!io_service.EvalConfiguration(conf))
408 return -1;
409
410 io_service.Run();
411
412 return 0;
413}
414*/
415
416template<class T>
417int RunShell(Configuration &conf)
418{
419 return Main<T, StateMachineMCP>(conf);
420/*
421 static T shell(conf.GetName().c_str(), conf.Get<int>("console")!=1);
422
423 WindowLog &win = shell.GetStreamIn();
424 WindowLog &wout = shell.GetStreamOut();
425
426 if (conf.Has("log"))
427 if (!wout.OpenLogFile(conf.Get<string>("log")))
428 win << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
429
430 StateMachineMCP<S, R> io_service(wout);
431 if (!io_service.EvalConfiguration(conf))
432 return -1;
433
434 shell.SetReceiver(io_service);
435
436 boost::thread t(bind(RunThread, &io_service));
437 // boost::thread t(bind(&StateMachineMCP<S>::Run, &io_service));
438
439 if (conf.Has("cmd"))
440 {
441 const vector<string> v = conf.Get<vector<string>>("cmd");
442 for (vector<string>::const_iterator it=v.begin(); it!=v.end(); it++)
443 shell.ProcessLine(*it);
444 }
445
446 if (conf.Has("exec"))
447 {
448 const vector<string> v = conf.Get<vector<string>>("exec");
449 for (vector<string>::const_iterator it=v.begin(); it!=v.end(); it++)
450 shell.Execute(*it);
451 }
452
453 if (conf.Get<bool>("quit"))
454 shell.Stop();
455
456 shell.Run(); // Run the shell
457 io_service.Stop(); // Signal Loop-thread to stop
458 // io_service.Close(); // Obsolete, done by the destructor
459
460 // Wait until the StateMachine has finished its thread
461 // before returning and destroying the dim objects which might
462 // still be in use.
463 t.join();
464
465 return 0;
466*/
467}
468
469void SetupConfiguration(Configuration &conf)
470{
471 const string n = conf.GetName()+".log";
472
473 po::options_description config("Program options");
474 config.add_options()
475 ("dns", var<string>("localhost"), "Dim nameserver host name (Overwites DIM_DNS_NODE environment variable)")
476 ("log,l", var<string>(n), "Write log-file")
477// ("no-dim,d", po_bool(), "Disable dim services")
478 ("console,c", var<int>(), "Use console (0=shell, 1=simple buffered, X=simple unbuffered)")
479 ("cmd", vars<string>(), "Execute one or more commands at startup")
480 ("exec,e", vars<string>(), "Execute one or more scrips at startup")
481 ("quit,q", po_switch(), "Quit after startup");
482 ;
483/*
484 po::options_description control("FTM control options");
485 control.add_options()
486 ("addr,a", var<string>("localhost:5000"), "Network address of FTM")
487 ("quiet,q", po_bool(), "Disable printing contents of all received messages (except dynamic data) in clear text.")
488 ;
489*/
490 conf.AddEnv("dns", "DIM_DNS_NODE");
491
492 conf.AddOptions(config);
493// conf.AddOptions(control);
494}
495
496/*
497 Extract usage clause(s) [if any] for SYNOPSIS.
498 Translators: "Usage" and "or" here are patterns (regular expressions) which
499 are used to match the usage synopsis in program output. An example from cp
500 (GNU coreutils) which contains both strings:
501 Usage: cp [OPTION]... [-T] SOURCE DEST
502 or: cp [OPTION]... SOURCE... DIRECTORY
503 or: cp [OPTION]... -t DIRECTORY SOURCE...
504 */
505void PrintUsage()
506{
507 cout <<
508 "The ftmctrl controls the FSC (FACT Slow Control) board.\n"
509 "\n"
510 "The default is that the program is started without user intercation. "
511 "All actions are supposed to arrive as DimCommands. Using the -c "
512 "option, a local shell can be initialized. With h or help a short "
513 "help message about the usuage can be brought to the screen.\n"
514 "\n"
515 "Usage: fscctrl [-c type] [OPTIONS]\n"
516 " or: fscctrl [OPTIONS]\n";
517 cout << endl;
518}
519
520void PrintHelp()
521{
522 /* Additional help text which is printed after the configuration
523 options goes here */
524
525 /*
526 cout << "bla bla bla" << endl << endl;
527 cout << endl;
528 cout << "Environment:" << endl;
529 cout << "environment" << endl;
530 cout << endl;
531 cout << "Examples:" << endl;
532 cout << "test exam" << endl;
533 cout << endl;
534 cout << "Files:" << endl;
535 cout << "files" << endl;
536 cout << endl;
537 */
538}
539
540int main(int argc, const char* argv[])
541{
542 Configuration conf(argv[0]);
543 conf.SetPrintUsage(PrintUsage);
544 SetupConfiguration(conf);
545
546 po::variables_map vm;
547 try
548 {
549 vm = conf.Parse(argc, argv);
550 }
551#if BOOST_VERSION > 104000
552 catch (po::multiple_occurrences &e)
553 {
554 cerr << "Program options invalid due to: " << e.what() << " of '" << e.get_option_name() << "'." << endl;
555 return -1;
556 }
557#endif
558 catch (exception& e)
559 {
560 cerr << "Program options invalid due to: " << e.what() << endl;
561 return -1;
562 }
563
564 if (conf.HasVersion() || conf.HasPrint())
565 return -1;
566
567 if (conf.HasHelp())
568 {
569 PrintHelp();
570 return -1;
571 }
572
573 Dim::Setup(conf.Get<string>("dns"));
574
575 //try
576 {
577 // No console access at all
578 if (!conf.Has("console"))
579 {
580// if (conf.Get<bool>("no-dim"))
581// return RunShell<LocalStream, StateMachine, ConnectionFSC>(conf);
582// else
583 return RunShell<LocalStream>(conf);
584 }
585 // Cosole access w/ and w/o Dim
586/* if (conf.Get<bool>("no-dim"))
587 {
588 if (conf.Get<int>("console")==0)
589 return RunShell<LocalShell, StateMachine, ConnectionFSC>(conf);
590 else
591 return RunShell<LocalConsole, StateMachine, ConnectionFSC>(conf);
592 }
593 else
594*/ {
595 if (conf.Get<int>("console")==0)
596 return RunShell<LocalShell>(conf);
597 else
598 return RunShell<LocalConsole>(conf);
599 }
600 }
601 /*catch (std::exception& e)
602 {
603 cerr << "Exception: " << e.what() << endl;
604 return -1;
605 }*/
606
607 return 0;
608}
Note: See TracBrowser for help on using the repository browser.