source: trunk/FACT++/src/magiclidar.cc@ 18167

Last change on this file since 18167 was 16727, checked in by tbretz, 11 years ago
Make use of the new StateMachineAsio which gets the CPU consumption to basically 0 by a more intelligent event management.
File size: 16.6 KB
Line 
1#include <boost/array.hpp>
2
3#include "FACT.h"
4#include "Dim.h"
5#include "Event.h"
6#include "Shell.h"
7#include "StateMachineDim.h"
8#include "StateMachineAsio.h"
9#include "Connection.h"
10#include "LocalControl.h"
11#include "Configuration.h"
12#include "Timers.h"
13#include "Console.h"
14
15#include "tools.h"
16
17#include "HeadersMagicLidar.h"
18
19namespace ba = boost::asio;
20namespace bs = boost::system;
21namespace dummy = ba::placeholders;
22
23using namespace std;
24using namespace MagicLidar;
25
26// ------------------------------------------------------------------------
27
28class ConnectionLidar : public Connection
29{
30 uint16_t fInterval;
31
32 bool fIsVerbose;
33
34 string fSite;
35
36 virtual void UpdateLidar(const Time &, const DimLidar &)
37 {
38 }
39
40protected:
41
42 boost::array<char, 4096> fArray;
43
44 Time fLastReport;
45 Time fLastReception;
46
47 void HandleRead(const boost::system::error_code& err, size_t bytes_received)
48 {
49 // Do not schedule a new read if the connection failed.
50 if (bytes_received==0 || err)
51 {
52 if (err==ba::error::eof)
53 Warn("Connection closed by remote host.");
54
55 // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
56 // 125: Operation canceled
57 if (err && err!=ba::error::eof && // Connection closed by remote host
58 err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
59 err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
60 {
61 ostringstream str;
62 str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
63 Error(str);
64 }
65 PostClose(err!=ba::error::basic_errors::operation_aborted);
66 return;
67 }
68
69 fLastReception = Time();
70
71 const string str(fArray.data(), bytes_received);
72 memset(fArray.data(), 0, fArray.size());
73
74 if (fIsVerbose)
75 Out() << str << endl;
76
77 bool isheader = true;
78
79 DimLidar data;
80
81 int hh=0, mm=0, ss=0, y=0, m=0, d=0;
82
83 bool keepalive = false;
84 bool failed = false;
85
86 stringstream is(str);
87 string line;
88 while (getline(is, line))
89 {
90 if (line.size()==1 && line[0]==13)
91 {
92 isheader = false;
93 continue;
94 }
95
96 if (isheader)
97 {
98 const size_t p = line.find_first_of(": ");
99 if (p==string::npos)
100 continue;
101
102 std::transform(line.begin(), line.end(), line.begin(), (int(&)(int))std::tolower);
103
104 const string key = line.substr(0, p);
105 const string val = line.substr(p+2);
106
107 if (key=="connection" && val=="keep-alive")
108 keepalive = true;
109 }
110 else
111 {
112 try
113 {
114 if (line.substr(0, 3)=="ZEN")
115 data.fZd = stoi(line.substr(3));
116 if (line.substr(0, 2)=="AZ")
117 data.fAz = stof(line.substr(2));
118
119 //if (line.substr(0, 3)=="PBL")
120 // data.fPBL = stof(line.substr(3));
121 //if (line.substr(0, 3)=="CHE")
122 // data.fCHE = stof(line.substr(3));
123 //if (line.substr(0, 3)=="COT")
124 // data.fCOT = stof(line.substr(3));
125
126 if (line.substr(0, 2)=="T3")
127 data.fT3 = stof(line.substr(2));
128 if (line.substr(0, 2)=="T6")
129 data.fT6 = stof(line.substr(2));
130 if (line.substr(0, 2)=="T9")
131 data.fT9 = stof(line.substr(2));
132 if (line.substr(0, 3)=="T12")
133 data.fT12 = stof(line.substr(3));
134
135 if (line.substr(0, 4)=="HOUR")
136 hh = stoi(line.substr(4));
137 if (line.substr(0, 6)=="MINUTS")
138 mm = stoi(line.substr(6));
139 if (line.substr(0, 7)=="SECONDS")
140 ss = stoi(line.substr(7));
141
142 if (line.substr(0, 4)=="YEAR")
143 y = stoi(line.substr(4));
144 if (line.substr(0, 5)=="MONTH")
145 m = stoi(line.substr(5));
146 if (line.substr(0, 3)=="DAY")
147 d = stoi(line.substr(3));
148 }
149 catch (const exception &e)
150 {
151 Warn("Conversion of received data failed");
152 failed = true;
153 break;
154 }
155 }
156 }
157
158 if (!keepalive)
159 PostClose(false);
160
161 if (failed)
162 return;
163
164 try
165 {
166 const Time tm = Time(2000+y, m, d, hh, mm, ss);
167 if (tm==fLastReport)
168 return;
169
170 fLastReport = tm;
171
172 if (data.fT3==0 && data.fT6==0 && data.fT9==0 && data.fT12==0)
173 return;
174
175 ostringstream msg;
176 msg << tm.GetAsStr("%H:%M:%S") << ":"
177 //<< " PBL=" << data.fPBL
178 //<< " CHE=" << data.fCHE
179 //<< " COT=" << data.fCOT
180 << " T3-12=" << data.fT3
181 << "/" << data.fT6
182 << "/" << data.fT9
183 << "/" << data.fT12
184 << " Zd=" << data.fZd << "°"
185 << " Az=" << data.fAz << "°";
186 Message(msg);
187
188 UpdateLidar(tm, data);
189 }
190 catch (const exception &e)
191 {
192 Warn("Corrupted time received.");
193 }
194
195 }
196
197 void StartReadReport()
198 {
199 async_read_some(ba::buffer(fArray),
200 boost::bind(&ConnectionLidar::HandleRead, this,
201 dummy::error, dummy::bytes_transferred));
202 }
203
204 boost::asio::deadline_timer fKeepAlive;
205
206 void PostRequest()
207 {
208 const string cmd =
209 "GET "+fSite+" HTTP/1.1\r\n"
210 "Accept: */*\r\n"
211 "Content-Type: application/octet-stream\r\n"
212 "User-Agent: FACT\r\n"
213 "Host: www.fact-project.org\r\n"
214 "Pragma: no-cache\r\n"
215 "Cache-Control: no-cache\r\n"
216 "Expires: 0\r\n"
217 "Connection: Keep-Alive\r\n"
218 "Cache-Control: max-age=0\r\n"
219 "\r\n";
220
221 PostMessage(cmd);
222 }
223
224 void Request()
225 {
226 PostRequest();
227
228 fKeepAlive.expires_from_now(boost::posix_time::seconds(fInterval/2));
229 fKeepAlive.async_wait(boost::bind(&ConnectionLidar::HandleRequest,
230 this, dummy::error));
231 }
232
233 void HandleRequest(const bs::error_code &error)
234 {
235 // 125: Operation canceled (bs::error_code(125, bs::system_category))
236 if (error && error!=ba::error::basic_errors::operation_aborted)
237 {
238 ostringstream str;
239 str << "Write timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
240 Error(str);
241
242 PostClose(false);
243 return;
244 }
245
246 if (!is_open())
247 {
248 // For example: Here we could schedule a new accept if we
249 // would not want to allow two connections at the same time.
250 PostClose(true);
251 return;
252 }
253
254 // Check whether the deadline has passed. We compare the deadline
255 // against the current time since a new asynchronous operation
256 // may have moved the deadline before this actor had a chance
257 // to run.
258 if (fKeepAlive.expires_at() > ba::deadline_timer::traits_type::now())
259 return;
260
261 Request();
262 }
263
264
265private:
266 // This is called when a connection was established
267 void ConnectionEstablished()
268 {
269 Request();
270 StartReadReport();
271 }
272
273public:
274
275 static const uint16_t kMaxAddr;
276
277public:
278 ConnectionLidar(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
279 fIsVerbose(true), fLastReport(Time::none), fLastReception(Time::none), fKeepAlive(ioservice)
280 {
281 SetLogStream(&imp);
282 }
283
284 void SetVerbose(bool b)
285 {
286 fIsVerbose = b;
287 Connection::SetVerbose(b);
288 }
289
290 void SetInterval(uint16_t i)
291 {
292 fInterval = i;
293 }
294
295 void SetSite(const string &site)
296 {
297 fSite = site;
298 }
299
300 int GetState() const
301 {
302 if (fLastReport.IsValid() && fLastReport+boost::posix_time::seconds(fInterval*2)>Time())
303 return 3;
304
305 if (fLastReception.IsValid() && fLastReception+boost::posix_time::seconds(fInterval*2)>Time())
306 return 2;
307
308 return 1;
309
310 }
311};
312
313const uint16_t ConnectionLidar::kMaxAddr = 0xfff;
314
315// ------------------------------------------------------------------------
316
317#include "DimDescriptionService.h"
318
319class ConnectionDimLidar : public ConnectionLidar
320{
321private:
322
323 DimDescribedService fDimLidar;
324
325 virtual void UpdateLidar(const Time &t, const DimLidar &data)
326 {
327 fDimLidar.setData(&data, sizeof(DimLidar));
328 fDimLidar.Update(t);
329 }
330
331public:
332 ConnectionDimLidar(ba::io_service& ioservice, MessageImp &imp) :
333 ConnectionLidar(ioservice, imp),
334 fDimLidar("MAGIC_LIDAR/DATA", "F:1;F:1;F:1;F:1;F:1;F:1",
335 "|Zd[deg]:Pointing direction zenith distance"
336 "|Az[deg]:Pointing direction azimuth"
337 //"|CHE[km]:Cloud height"
338 //"|COT[1]:Cloud optical transparency at 532nm"
339 //"|PBL[100]:Planetary boundary layer normalized to 100 for clear nights"
340 "|T3[1]:Transmission below 3km normalized to 1"
341 "|T6[1]:Transmission below 6km normalized to 1"
342 "|T9[1]:Transmission below 9km normalized to 1"
343 "|T12[1]:Transmission below 12km normalized to 1")
344 {
345 }
346};
347
348// ------------------------------------------------------------------------
349
350template <class T, class S>
351class StateMachineLidar : public StateMachineAsio<T>
352{
353private:
354 S fLidar;
355
356 bool CheckEventSize(size_t has, const char *name, size_t size)
357 {
358 if (has==size)
359 return true;
360
361 ostringstream msg;
362 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
363 T::Fatal(msg);
364 return false;
365 }
366
367 int SetVerbosity(const EventImp &evt)
368 {
369 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
370 return T::kSM_FatalError;
371
372 fLidar.SetVerbose(evt.GetBool());
373
374 return T::GetCurrentState();
375 }
376/*
377 int Disconnect()
378 {
379 // Close all connections
380 fLidar.PostClose(false);
381
382 return T::GetCurrentState();
383 }
384
385 int Reconnect(const EventImp &evt)
386 {
387 // Close all connections to supress the warning in SetEndpoint
388 fLidar.PostClose(false);
389
390 // Now wait until all connection have been closed and
391 // all pending handlers have been processed
392 poll();
393
394 if (evt.GetBool())
395 fLidar.SetEndpoint(evt.GetString());
396
397 // Now we can reopen the connection
398 fLidar.PostClose(true);
399
400 return T::GetCurrentState();
401 }
402*/
403 int Execute()
404 {
405 return fLidar.GetState();
406 }
407
408
409public:
410 StateMachineLidar(ostream &out=cout) :
411 StateMachineAsio<T>(out, "MAGIC_LIDAR"), fLidar(*this, *this)
412 {
413 // State names
414 T::AddStateName(State::kDisconnected, "NoConnection",
415 "No connection to web-server could be established recently");
416
417 T::AddStateName(State::kConnected, "Invalid",
418 "Connection to webserver can be established, but received data is not recent or invalid");
419
420 T::AddStateName(State::kReceiving, "Valid",
421 "Connection to webserver can be established, receint data received");
422
423 // Verbosity commands
424 T::AddEvent("SET_VERBOSE", "B")
425 (bind(&StateMachineLidar::SetVerbosity, this, placeholders::_1))
426 ("set verbosity state"
427 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
428/*
429 // Conenction commands
430 AddEvent("DISCONNECT")
431 (bind(&StateMachineLidar::Disconnect, this))
432 ("disconnect from ethernet");
433
434 AddEvent("RECONNECT", "O")
435 (bind(&StateMachineLidar::Reconnect, this, placeholders::_1))
436 ("(Re)connect ethernet connection to FTM, a new address can be given"
437 "|[host][string]:new ethernet address in the form <host:port>");
438*/
439 }
440
441 int EvalOptions(Configuration &conf)
442 {
443 fLidar.SetVerbose(!conf.Get<bool>("quiet"));
444 fLidar.SetInterval(conf.Get<uint16_t>("interval"));
445 fLidar.SetDebugTx(conf.Get<bool>("debug-tx"));
446 fLidar.SetSite(conf.Get<string>("url"));
447 fLidar.SetEndpoint(conf.Get<string>("addr"));
448 fLidar.StartConnect();
449
450 return -1;
451 }
452};
453
454// ------------------------------------------------------------------------
455
456#include "Main.h"
457
458
459template<class T, class S, class R>
460int RunShell(Configuration &conf)
461{
462 return Main::execute<T, StateMachineLidar<S, R>>(conf);
463}
464
465void SetupConfiguration(Configuration &conf)
466{
467 po::options_description control("MAGIC lidar control options");
468 control.add_options()
469 ("no-dim,d", po_switch(), "Disable dim services")
470 ("addr,a", var<string>("www.magic.iac.es:80"), "Network address of Cosy")
471 ("url,u", var<string>("/site/weather/lidar_data.txt"), "File name and path to load")
472 ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
473 ("interval,i", var<uint16_t>(30), "Interval between two updates on the server in seconds")
474 ("debug-tx", po_bool(), "Enable debugging of ethernet transmission.")
475 ;
476
477 conf.AddOptions(control);
478}
479
480/*
481 Extract usage clause(s) [if any] for SYNOPSIS.
482 Translators: "Usage" and "or" here are patterns (regular expressions) which
483 are used to match the usage synopsis in program output. An example from cp
484 (GNU coreutils) which contains both strings:
485 Usage: cp [OPTION]... [-T] SOURCE DEST
486 or: cp [OPTION]... SOURCE... DIRECTORY
487 or: cp [OPTION]... -t DIRECTORY SOURCE...
488 */
489void PrintUsage()
490{
491 cout <<
492 "The magiclidar is an interface to the MAGIC lidar data.\n"
493 "\n"
494 "The default is that the program is started without user intercation. "
495 "All actions are supposed to arrive as DimCommands. Using the -c "
496 "option, a local shell can be initialized. With h or help a short "
497 "help message about the usuage can be brought to the screen.\n"
498 "\n"
499 "Usage: magiclidar [-c type] [OPTIONS]\n"
500 " or: magiclidar [OPTIONS]\n";
501 cout << endl;
502}
503
504void PrintHelp()
505{
506// Main::PrintHelp<StateMachineFTM<StateMachine, ConnectionFTM>>();
507
508 /* Additional help text which is printed after the configuration
509 options goes here */
510
511 /*
512 cout << "bla bla bla" << endl << endl;
513 cout << endl;
514 cout << "Environment:" << endl;
515 cout << "environment" << endl;
516 cout << endl;
517 cout << "Examples:" << endl;
518 cout << "test exam" << endl;
519 cout << endl;
520 cout << "Files:" << endl;
521 cout << "files" << endl;
522 cout << endl;
523 */
524}
525
526int main(int argc, const char* argv[])
527{
528 Configuration conf(argv[0]);
529 conf.SetPrintUsage(PrintUsage);
530 Main::SetupConfiguration(conf);
531 SetupConfiguration(conf);
532
533 if (!conf.DoParse(argc, argv, PrintHelp))
534 return 127;
535
536 //try
537 {
538 // No console access at all
539 if (!conf.Has("console"))
540 {
541 if (conf.Get<bool>("no-dim"))
542 return RunShell<LocalStream, StateMachine, ConnectionLidar>(conf);
543 else
544 return RunShell<LocalStream, StateMachineDim, ConnectionDimLidar>(conf);
545 }
546 // Cosole access w/ and w/o Dim
547 if (conf.Get<bool>("no-dim"))
548 {
549 if (conf.Get<int>("console")==0)
550 return RunShell<LocalShell, StateMachine, ConnectionLidar>(conf);
551 else
552 return RunShell<LocalConsole, StateMachine, ConnectionLidar>(conf);
553 }
554 else
555 {
556 if (conf.Get<int>("console")==0)
557 return RunShell<LocalShell, StateMachineDim, ConnectionDimLidar>(conf);
558 else
559 return RunShell<LocalConsole, StateMachineDim, ConnectionDimLidar>(conf);
560 }
561 }
562 /*catch (std::exception& e)
563 {
564 cerr << "Exception: " << e.what() << endl;
565 return -1;
566 }*/
567
568 return 0;
569}
Note: See TracBrowser for help on using the repository browser.