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

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