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

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