source: trunk/FACT++/src/dclient5.cc@ 10278

Last change on this file since 10278 was 10269, checked in by tbretz, 14 years ago
File size: 18.2 KB
Line 
1#include <boost/bind.hpp>
2#include <boost/thread.hpp>
3#include <boost/asio/deadline_timer.hpp>
4
5#include "Event.h"
6#include "Shell.h"
7#include "StateMachineDim.h"
8#include "Connection.h"
9#include "Configuration.h"
10#include "Timers.h"
11#include "Console.h"
12
13#include "tools.h"
14
15namespace ba = boost::asio;
16namespace bs = boost::system;
17
18using ba::deadline_timer;
19using ba::ip::tcp;
20
21using namespace std;
22
23
24// ------------------------------------------------------------------------
25
26#include "LocalControl.h"
27
28// ------------------------------------------------------------------------
29
30class ConnectionFAD : public Connection
31{
32 MessageImp &fMsg;
33
34 int state;
35
36public:
37 void ConnectionEstablished()
38 {
39 StartAsyncRead();
40 }
41
42 void HandleReadTimeout(const bs::error_code &error)
43 {
44 return;
45 if (!is_open())
46 {
47 // For example: Here we could schedule a new accept if we
48 // would not want to allow two connections at the same time.
49 return;
50 }
51
52 // 125: Operation canceled
53
54 if (error && error!=bs::error_code(125, bs::system_category))
55 {
56 stringstream str;
57
58 str << "HandleReadTimeout: " << error.message() << " (" << error << ")";// << endl;
59 if (error==bs::error_code(2, ba::error::misc_category))
60 Warn(str); // Connection: EOF (closed by remote host)
61 else
62 Error(str);
63 }
64
65 // Check whether the deadline has passed. We compare the deadline
66 // against the current time since a new asynchronous operation
67 // may have moved the deadline before this actor had a chance
68 // to run.
69 if (fInTimeout.expires_at() > deadline_timer::traits_type::now())
70 return;
71
72 Error("fInTimeout has expired...");
73
74 CloseImp();
75 }
76
77 void HandleReceivedData(const bs::error_code& error, size_t bytes_received, int type)
78 {
79 // Do not schedule a new read if the connection failed.
80 if (bytes_received==0 || error)
81 {
82 // 107: Transport endpoint is not connected
83 // 125: Operation canceled
84 if (error && error!=bs::error_code(107, bs::system_category))
85 {
86 stringstream str;
87 str << "Reading from " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
88 Error(str);
89 }
90 CloseImp(error!=bs::error_code(125, bs::system_category));
91 return;
92 }
93
94 string txt;
95
96 if (bytes_received==2)
97 {
98 txt = string(fReadBuffer, bytes_received);
99 //std::vector<char> buf(128);
100 //bytes_transferred = sock.receive(boost::asio::buffer(d3));
101
102 fMsg() << "Received b=" << bytes_received << ": " << (int)fReadBuffer[0] << " " << (int)txt[0] << " '" << txt << "' " << " " << error.message() << " (" << error << ")" << endl;
103
104 if (fReadBuffer[0]=='T')
105 {
106 // AsyncRead + Deadline
107 // Do all manipulation to the buffer BEFORE this call!
108 AsyncRead(ba::buffer(fReadBuffer+2, 21)/*,
109 &Connection::HandleReceivedData*/);
110 AsyncWait(fInTimeout, 5000, &Connection::HandleReadTimeout);
111 }
112 else
113 {
114 // AsyncRead + Deadline
115 // Do all manipulation to the buffer BEFORE this call!
116 AsyncRead(ba::buffer(fReadBuffer+2, 35)/*,
117 &Connection::HandleReceivedData*/);
118 AsyncWait(fInTimeout, 5000, &Connection::HandleReadTimeout);
119 }
120 }
121 else
122 {
123 txt = string(fReadBuffer, bytes_received+2);
124 const int s = atoi(fReadBuffer+35);
125 if (s==9)
126 Info("Requested time received: "+txt);
127 else
128 state = s;
129
130 Out() << "Received b=" << bytes_received << ": " << (int)fReadBuffer[0] << " " << (int)txt[0] << " '" << txt << "' " << " " << error.message() << " (" << error << ")" << endl;
131 memset(fReadBuffer, 0, 100);
132
133 // Do all manipulation to the buffer BEFORE this call!
134 AsyncRead(ba::buffer(fReadBuffer, 2)/*,
135 &Connection::HandleReceivedData*/);
136
137
138 }
139 }
140
141 int GetState() const { return state; }
142
143 void StartAsyncRead()
144 {
145 // Start also a dealine_time for a proper timeout
146 // Therefore we must know how often we expect messages
147 // FIXME: Add deadline_counter
148
149 memset(fReadBuffer, 0, 100);
150
151 // AsyncRead + Deadline
152 AsyncRead(ba::buffer(fReadBuffer, 2)/*,
153 &Connection::HandleReceivedData*/);
154 AsyncWait(fInTimeout, 5000, &Connection::HandleReadTimeout);
155 }
156
157 /*
158 ConnectionFAD(ba::io_service& io_service, const string &addr, int port) :
159 Connection(io_service, addr, port), state(0) { }
160 ConnectionFAD(ba::io_service& io_service, const string &addr, const string &port) :
161 Connection(io_service, addr, port), state(0) { }
162 */
163
164 ConnectionFAD(ba::io_service& ioservice, MessageImp &imp) :
165 Connection(ioservice, imp()), fMsg(imp), state(0)
166 {
167 }
168};
169
170template <class T>
171class StateMachineFAD : public T, public ba::io_service
172{
173public:
174 enum states_t
175 {
176 kSM_Disconnected = 1,
177 kSM_Connecting,
178 kSM_Connected,
179 kSM_Running,
180 kSM_SomeRunning,
181 kSM_Starting,
182 kSM_Stopping,
183 kSM_Reconnect,
184 kSM_SetUrl,
185 };
186
187 ConnectionFAD c1;
188 ConnectionFAD c2;
189 ConnectionFAD c3;
190 ConnectionFAD c4;
191 ConnectionFAD c5;
192 ConnectionFAD c6;
193 ConnectionFAD c7;
194 ConnectionFAD c8;
195 ConnectionFAD c9;
196
197 /*
198 int Write(const Time &time, const char *txt, int qos)
199 {
200 return T::Write(time, txt, qos);
201 }
202 */
203 Timers fTimers;
204
205 StateMachineFAD(const string &name="", ostream &out=cout) :
206 T(out, name),
207 c1(*this, *this), c2(*this, *this), c3(*this, *this), c4(*this, *this),
208 c5(*this, *this), c6(*this, *this), c7(*this, *this), c8(*this, *this),
209 c9(*this, *this), fTimers(out)
210 {
211// c1.SetEndpoint();
212 c2.SetEndpoint("localhost", 4001);
213 c3.SetEndpoint("ftmboard1.ethz.ch", 5000);
214 c4.SetEndpoint("localhost", 4003);
215 c5.SetEndpoint("localhost", 4004);
216 c6.SetEndpoint("localhost", 4005);
217 c7.SetEndpoint("localhost", 4006);
218 c8.SetEndpoint("localhost", 4007);
219 c9.SetEndpoint("localhost", 4008);
220
221 c1.SetLogStream(this);
222 c2.SetLogStream(this);
223 c3.SetLogStream(this);
224 c4.SetLogStream(this);
225 c5.SetLogStream(this);
226 c6.SetLogStream(this);
227 c7.SetLogStream(this);
228 c8.SetLogStream(this);
229 c9.SetLogStream(this);
230
231 c1.StartConnect(); // This sets the connection to "open"
232 c2.StartConnect(); // This sets the connection to "open"
233 c3.StartConnect(); // This sets the connection to "open"
234 //c4.StartConnect(); // This sets the connection to "open"
235 //c5.StartConnect(); // This sets the connection to "open"
236 //c6.StartConnect(); // This sets the connection to "open"
237 //c7.StartConnect(); // This sets the connection to "open"
238 //c8.StartConnect(); // This sets the connection to "open"
239 //c9.StartConnect(); // This sets the connection to "open"
240
241 AddStateName(kSM_Disconnected, "Disconnected");
242 AddStateName(kSM_Connecting, "Connecting"); // Some connected
243 AddStateName(kSM_Connected, "Connected");
244 AddStateName(kSM_Running, "Running");
245 AddStateName(kSM_SomeRunning, "SomeRunning");
246 AddStateName(kSM_Starting, "Starting");
247 AddStateName(kSM_Stopping, "Stopping");
248
249 AddTransition(kSM_Running, "START", kSM_Connected)
250 ->AssignFunction(boost::bind(&StateMachineFAD::Start, this, _1, 5));
251 AddTransition(kSM_Connected, "STOP", kSM_Running);
252
253 AddConfiguration("TIME", kSM_Running);
254 AddConfiguration("LED", kSM_Connected);
255
256 T::AddConfiguration("TESTI", "I");
257 T::AddConfiguration("TESTI2", "I:2");
258 T::AddConfiguration("TESTIF", "I:2;F:2");
259 T::AddConfiguration("TESTIC", "I:2;C");
260
261 T::AddConfiguration("CMD", "C")
262 ->AssignFunction(boost::bind(&StateMachineFAD::Command, this, _1));
263
264 AddTransition(kSM_Reconnect, "RECONNECT");
265
266 AddTransition(kSM_SetUrl, "SETURL", "C");
267
268 T::PrintListOfEvents();
269 }
270
271 int Command(const EventImp &evt)
272 {
273 string cmd = evt.GetText();
274
275 size_t p0 = cmd.find_first_of(' ');
276 if (p0==string::npos)
277 p0 = cmd.length();
278
279 T::Out() << "\nCommand: '" << cmd.substr(0, p0) << "'" << cmd.substr(p0)<< "'" << endl;
280 /*
281 const Converter c(T::Out(), "B:5;I:2;F;W;O;C", "yes no false 0 1 31 42 11.12 \"test hallo\" ");
282
283 T::Out() << c.GetRc() << endl;
284 T::Out() << c.N() << endl;
285 T::Out() << c.Get<bool>(0) << endl;
286 T::Out() << c.Get<bool>(1) << endl;
287 T::Out() << c.Get<bool>(2) << endl;
288 T::Out() << c.Get<bool>(3) << endl;
289 T::Out() << c.Get<bool>(4) << endl;
290 T::Out() << c.Get<int>(5) << endl;
291 T::Out() << c.Get<int>(6) << endl;
292 T::Out() << c.Get<float>(7) << endl;
293 T::Out() << c.Get<int>(7) << endl;
294 T::Out() << c.Get<string>(8) << endl;
295 T::Out() << c.Get<string>(9) << endl;
296 T::Out() << c.Get<string>(10) << endl;
297 */
298 return T::GetCurrentState();
299 }
300 int Start(const EventImp &evt, int i)
301 {
302 switch (evt.GetTargetState())
303 {
304 case kSM_Running: // We are coming from kRunning
305 case kSM_Starting: // We are coming from kConnected
306 T::Out() << "Received Start(" << i << ")" << endl;
307 c1.PostMessage("START", 10);
308 c2.PostMessage("START", 10);
309 // We could introduce a "waiting for execution" state
310 return T::GetCurrentState();
311 }
312 return T::kSM_FatalError;
313 }
314
315 void Close()
316 {
317 c1.PostClose();
318 c2.PostClose();
319 c3.PostClose();
320 c4.PostClose();
321 c5.PostClose();
322 c6.PostClose();
323 c7.PostClose();
324 c8.PostClose();
325 c9.PostClose();
326 }
327
328
329 int Execute()
330 {
331 // Dispatch at most one handler from the queue. In contrary
332 // to run_run(), it doesn't wait until a handler is available
333 // which can be dispatched, so poll_one() might return with 0
334 // handlers dispatched. The handlers are always dispatched
335 // synchronously.
336
337 fTimers.SetT();
338 const int n = poll_one();
339 fTimers.Proc(n==0 && T::IsQueueEmpty());
340
341// return c3.IsConnected() ? kSM_Connected : kSM_Disconnected;
342
343
344 // None is connected
345 if (!c1.IsConnected() && !c2.IsConnected())
346 return kSM_Disconnected;
347
348 // Some are connected
349 if (c1.IsConnected()!=c2.IsConnected())
350 return kSM_Connecting;
351
352 if (c1.GetState()==0 && c2.GetState()==0 && T::GetCurrentState()!=kSM_Starting)
353 return kSM_Connected;
354
355 if (c1.GetState()==1 && c2.GetState()==1 && T::GetCurrentState()!=kSM_Stopping)
356 return kSM_Running;
357
358 return kSM_SomeRunning;//GetCurrentState();
359 }
360
361 int Transition(const Event &evt)
362 {
363 ConnectionFAD *con1 = &c1;
364 ConnectionFAD *con2 = &c2;
365
366 switch (evt.GetTargetState())
367 {
368 case kSM_SetUrl:
369 T::Out() << evt.GetText() << endl;
370 c1.SetEndpoint(evt.GetText());
371 return T::GetCurrentState();
372 case kSM_Reconnect:
373 // Close all connections
374 c1.PostClose(false);
375 c2.PostClose(false);
376 c3.PostClose(false);
377
378 // Now wait until all connection have been closed and
379 // all pending handlers have been processed
380 poll();
381
382 // Now we can reopen the connection
383 c1.PostClose(true);
384 c2.PostClose(true);
385 c3.PostClose(true);
386
387
388 //c4.PostClose(true);
389 //c5.PostClose(true);
390 //c6.PostClose(true);
391 //c7.PostClose(true);
392 //c8.PostClose(true);
393 //c9.PostClose(true);
394 return T::GetCurrentState();
395 case kSM_Running: // We are coming from kRunning
396 case kSM_Starting: // We are coming from kConnected
397 T::Out() << "Received START" << endl;
398 con1->PostMessage("START", 10);
399 con2->PostMessage("START", 10);
400 // We could introduce a "waiting for execution" state
401 return T::GetCurrentState();
402 return kSM_Starting; //GetCurrentState();
403
404 case kSM_Connected: // We are coming from kConnected
405 case kSM_Stopping: // We are coming from kRunning
406 T::Out() << "Received STOP" << endl;
407 con1->PostMessage("STOP", 10);
408 con2->PostMessage("STOP", 10);
409 // We could introduce a "waiting for execution" state
410 return T::GetCurrentState();
411 return kSM_Stopping;//GetCurrentState();
412 }
413
414 return T::kSM_FatalError; //evt.GetTargetState();
415 }
416 int Configure(const Event &evt)
417 {
418 if (evt.GetName()=="TIME")
419 {
420 c1.PostMessage("TIME", 10);
421 c2.PostMessage("TIME", 10);
422 }
423
424 vector<char> v(2);
425 v[0] = 0xc0;
426 v[1] = 0x00;
427
428 if (evt.GetName()=="LED")
429 c3.PostMessage(v);
430
431 return T::GetCurrentState();
432 }
433};
434
435// ------------------------------------------------------------------------
436
437template<class S>
438int RunDim(Configuration &conf)
439{
440 /*
441 initscr(); // Start curses mode
442 cbreak(); // Line buffering disabled, Pass on
443 intrflush(stdscr, FALSE);
444 start_color(); // Initialize ncurses colors
445 use_default_colors(); // Assign terminal default colors to -1
446 for (int i=1; i<8; i++)
447 init_pair(i, i, -1); // -1: def background
448 scrollok(stdscr, true);
449 */
450
451 WindowLog wout;
452
453 //log.SetWindow(stdscr);
454 if (conf.Has("log"))
455 if (!wout.OpenLogFile(conf.Get<string>("log")))
456 wout << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
457
458 // Start io_service.Run to use the StateMachineImp::Run() loop
459 // Start io_service.run to only use the commandHandler command detaching
460 StateMachineFAD<S> io_service("DATA_LOGGER", wout);
461 io_service.Run();
462
463 return 0;
464}
465
466template<class T, class S>
467int RunShell(Configuration &conf)
468{
469 static T shell(conf.GetName().c_str(), conf.Get<int>("console")!=1);
470
471 WindowLog &win = shell.GetStreamIn();
472 WindowLog &wout = shell.GetStreamOut();
473
474 if (conf.Has("log"))
475 if (!wout.OpenLogFile(conf.Get<string>("log")))
476 win << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
477
478 StateMachineFAD<S> io_service("DATA_LOGGER", wout);
479 shell.SetReceiver(io_service);
480
481 boost::thread t(boost::bind(&StateMachineFAD<S>::Run, &io_service));
482
483 //io_service.SetReady();
484
485 shell.Run(); // Run the shell
486 io_service.Stop(); // Signal Loop-thread to stop
487 // io_service.Close(); // Obsolete, done by the destructor
488 // wout << "join: " << t.timed_join(boost::posix_time::milliseconds(0)) << endl;
489
490 // Wait until the StateMachine has finished its thread
491 // before returning and destroying the dim objects which might
492 // still be in use.
493 t.join();
494
495 return 0;
496}
497
498void SetupConfiguration(Configuration &conf)
499{
500 const string n = conf.GetName()+".log";
501
502 po::options_description config("Program options");
503 config.add_options()
504 ("dns", var<string>("localhost"), "Dim nameserver host name (Overwites DIM_DNS_NODE environment variable)")
505 ("log,l", var<string>(n), "Write log-file")
506 ("no-dim,d", po_switch(), "Disable dim services")
507 ("console,c", var<int>(), "Use console (0=shell, 1=simple buffered, X=simple unbuffered)")
508 ;
509
510 conf.AddEnv("dns", "DIM_DNS_NODE");
511
512 conf.AddOptions(config);
513}
514
515int main(int argc, char* argv[])
516{
517 Configuration conf(argv[0]);
518 SetupConfiguration(conf);
519
520 po::variables_map vm;
521 try
522 {
523 vm = conf.Parse(argc, argv);
524 }
525 catch (std::exception &e)
526 {
527#if BOOST_VERSION > 104000
528 po::multiple_occurrences *MO = dynamic_cast<po::multiple_occurrences*>(&e);
529 if (MO)
530 cout << "Error: " << e.what() << " of '" << MO->get_option_name() << "' option." << endl;
531 else
532#endif
533 cout << "Error: " << e.what() << endl;
534 cout << endl;
535
536 return -1;
537 }
538
539 if (conf.HasHelp() || conf.HasPrint())
540 return -1;
541
542 // To allow overwriting of DIM_DNS_NODE set 0 to 1
543 setenv("DIM_DNS_NODE", conf.Get<string>("dns").c_str(), 1);
544
545 try
546 {
547 // No console access at all
548 if (!conf.Has("console"))
549 {
550 if (conf.Get<bool>("no-dim"))
551 return RunDim<StateMachine>(conf);
552 else
553 return RunDim<StateMachineDim>(conf);
554 }
555 // Cosole access w/ and w/o Dim
556 if (conf.Get<bool>("no-dim"))
557 {
558 if (conf.Get<int>("console")==0)
559 return RunShell<LocalShell, StateMachine>(conf);
560 else
561 return RunShell<LocalConsole, StateMachine>(conf);
562 }
563 else
564 {
565 if (conf.Get<int>("console")==0)
566 return RunShell<LocalShell, StateMachineDim>(conf);
567 else
568 return RunShell<LocalConsole, StateMachineDim>(conf);
569 }
570 }
571 catch (std::exception& e)
572 {
573 std::cerr << "Exception: " << e.what() << "\n";
574 }
575
576 return 0;
577}
578
579/*
580class FADctrlDim : public StateMachineFAD<StateMachineDim>
581{
582public:
583FADctrlDim(const std::string &name="DATA_LOGGER", std::ostream &out=std::cout)
584: StateMachineFAD<StateMachineDim>(out, name) { }
585};
586
587 class FADctrlLocalShell : public StateMachineFAD<StateMachine>
588{
589public:
590 ostream &win;
591
592 FADctrlLocalShell(std::ostream &out, std::ostream &out2)
593 : StateMachineFAD<StateMachine>(out), win(out2) { }
594
595 FADctrlLocalShell(std::ostream &out=std::cout)
596 : StateMachineFAD<StateMachine>(out), win(out) { }
597
598};
599*/
Note: See TracBrowser for help on using the repository browser.