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

Last change on this file since 15034 was 14978, checked in by tbretz, 12 years ago
Added include for array.hpp - needed for newer boost versions
File size: 17.5 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 ostringstream msg;
175 msg << tm.GetAsStr("%H:%M:%S") << ":"
176 //<< " PBL=" << data.fPBL
177 //<< " CHE=" << data.fCHE
178 //<< " COT=" << data.fCOT
179 << " T3-12=" << data.fT3
180 << "/" << data.fT6
181 << "/" << data.fT9
182 << "/" << data.fT12
183 << " Zd=" << data.fZd << "°"
184 << " Az=" << data.fAz << "°";
185 Message(msg);
186
187 UpdateLidar(tm, data);
188
189 fLastReport = tm;
190 }
191 catch (const exception &e)
192 {
193 Warn("Corrupted time received.");
194 }
195
196 }
197
198 void StartReadReport()
199 {
200 async_read_some(ba::buffer(fArray),
201 boost::bind(&ConnectionLidar::HandleRead, this,
202 dummy::error, dummy::bytes_transferred));
203 }
204
205 boost::asio::deadline_timer fKeepAlive;
206
207 void PostRequest()
208 {
209 const string cmd =
210 "GET "+fSite+" HTTP/1.1\r\n"
211 "Accept: */*\r\n"
212 "Content-Type: application/octet-stream\r\n"
213 "User-Agent: FACT\r\n"
214 "Host: www.fact-project.org\r\n"
215 "Pragma: no-cache\r\n"
216 "Cache-Control: no-cache\r\n"
217 "Expires: 0\r\n"
218 "Connection: Keep-Alive\r\n"
219 "Cache-Control: max-age=0\r\n"
220 "\r\n";
221
222 PostMessage(cmd);
223 }
224
225 void Request()
226 {
227 PostRequest();
228
229 fKeepAlive.expires_from_now(boost::posix_time::seconds(fInterval/2));
230 fKeepAlive.async_wait(boost::bind(&ConnectionLidar::HandleRequest,
231 this, dummy::error));
232 }
233
234 void HandleRequest(const bs::error_code &error)
235 {
236 // 125: Operation canceled (bs::error_code(125, bs::system_category))
237 if (error && error!=ba::error::basic_errors::operation_aborted)
238 {
239 ostringstream str;
240 str << "Write timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
241 Error(str);
242
243 PostClose(false);
244 return;
245 }
246
247 if (!is_open())
248 {
249 // For example: Here we could schedule a new accept if we
250 // would not want to allow two connections at the same time.
251 PostClose(true);
252 return;
253 }
254
255 // Check whether the deadline has passed. We compare the deadline
256 // against the current time since a new asynchronous operation
257 // may have moved the deadline before this actor had a chance
258 // to run.
259 if (fKeepAlive.expires_at() > ba::deadline_timer::traits_type::now())
260 return;
261
262 Request();
263 }
264
265
266private:
267 // This is called when a connection was established
268 void ConnectionEstablished()
269 {
270 Request();
271 StartReadReport();
272 }
273
274public:
275
276 static const uint16_t kMaxAddr;
277
278public:
279 ConnectionLidar(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
280 fIsVerbose(true), fLastReport(Time::none), fLastReception(Time::none), fKeepAlive(ioservice)
281 {
282 SetLogStream(&imp);
283 }
284
285 void SetVerbose(bool b)
286 {
287 fIsVerbose = b;
288 Connection::SetVerbose(b);
289 }
290
291 void SetInterval(uint16_t i)
292 {
293 fInterval = i;
294 }
295
296 void SetSite(const string &site)
297 {
298 fSite = site;
299 }
300
301 int GetState() const
302 {
303 if (fLastReport.IsValid() && fLastReport+boost::posix_time::seconds(fInterval*2)>Time())
304 return 3;
305
306 if (fLastReception.IsValid() && fLastReception+boost::posix_time::seconds(fInterval*2)>Time())
307 return 2;
308
309 return 1;
310
311 }
312};
313
314const uint16_t ConnectionLidar::kMaxAddr = 0xfff;
315
316// ------------------------------------------------------------------------
317
318#include "DimDescriptionService.h"
319
320class ConnectionDimLidar : public ConnectionLidar
321{
322private:
323
324 DimDescribedService fDimLidar;
325
326 virtual void UpdateLidar(const Time &t, const DimLidar &data)
327 {
328 fDimLidar.setData(&data, sizeof(DimLidar));
329 fDimLidar.Update(t);
330 }
331
332public:
333 ConnectionDimLidar(ba::io_service& ioservice, MessageImp &imp) :
334 ConnectionLidar(ioservice, imp),
335 fDimLidar("MAGIC_LIDAR/DATA", "F:1;F:1;F:1;F:1;F:1;F:1;F:1;F:1;F:1",
336 "|Zd[deg]:Pointing direction zenith distance"
337 "|Az[deg]:Pointing direction azimuth"
338 //"|CHE[km]:Cloud height"
339 //"|COT[1]:Cloud optical transparency at 532nm"
340 //"|PBL[100]:Planetary boundary layer normalized to 100 for clear nights"
341 "|T3[1]:Transmission below 3km normalized to 1"
342 "|T6[1]:Transmission below 6km normalized to 1"
343 "|T9[1]:Transmission below 9km normalized to 1"
344 "|T12[1]:Transmission below 12km normalized to 1")
345 {
346 }
347};
348
349// ------------------------------------------------------------------------
350
351template <class T, class S>
352class StateMachineLidar : public T, public ba::io_service, public ba::io_service::work
353{
354private:
355 S fLidar;
356
357 bool CheckEventSize(size_t has, const char *name, size_t size)
358 {
359 if (has==size)
360 return true;
361
362 ostringstream msg;
363 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
364 T::Fatal(msg);
365 return false;
366 }
367
368 int SetVerbosity(const EventImp &evt)
369 {
370 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
371 return T::kSM_FatalError;
372
373 fLidar.SetVerbose(evt.GetBool());
374
375 return T::GetCurrentState();
376 }
377/*
378 int Disconnect()
379 {
380 // Close all connections
381 fLidar.PostClose(false);
382
383 return T::GetCurrentState();
384 }
385
386 int Reconnect(const EventImp &evt)
387 {
388 // Close all connections to supress the warning in SetEndpoint
389 fLidar.PostClose(false);
390
391 // Now wait until all connection have been closed and
392 // all pending handlers have been processed
393 poll();
394
395 if (evt.GetBool())
396 fLidar.SetEndpoint(evt.GetString());
397
398 // Now we can reopen the connection
399 fLidar.PostClose(true);
400
401 return T::GetCurrentState();
402 }
403*/
404 int Execute()
405 {
406 // Dispatch (execute) at most one handler from the queue. In contrary
407 // to run_one(), it doesn't wait until a handler is available
408 // which can be dispatched, so poll_one() might return with 0
409 // handlers dispatched. The handlers are always dispatched/executed
410 // synchronously, i.e. within the call to poll_one()
411 poll_one();
412
413 return fLidar.GetState();
414 }
415
416
417public:
418 StateMachineLidar(ostream &out=cout) :
419 T(out, "MAGIC_LIDAR"), ba::io_service::work(static_cast<ba::io_service&>(*this)),
420 fLidar(*this, *this)
421 {
422 // ba::io_service::work is a kind of keep_alive for the loop.
423 // It prevents the io_service to go to stopped state, which
424 // would prevent any consecutive calls to run()
425 // or poll() to do nothing. reset() could also revoke to the
426 // previous state but this might introduce some overhead of
427 // deletion and creation of threads and more.
428
429 // State names
430 T::AddStateName(State::kDisconnected, "NoConnection",
431 "No connection to web-server could be established recently");
432
433 T::AddStateName(State::kConnected, "Invalid",
434 "Connection to webserver can be established, but received data is not recent or invalid");
435
436 T::AddStateName(State::kReceiving, "Valid",
437 "Connection to webserver can be established, receint data received");
438
439 // Verbosity commands
440 T::AddEvent("SET_VERBOSE", "B")
441 (bind(&StateMachineLidar::SetVerbosity, this, placeholders::_1))
442 ("set verbosity state"
443 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
444/*
445 // Conenction commands
446 AddEvent("DISCONNECT")
447 (bind(&StateMachineLidar::Disconnect, this))
448 ("disconnect from ethernet");
449
450 AddEvent("RECONNECT", "O")
451 (bind(&StateMachineLidar::Reconnect, this, placeholders::_1))
452 ("(Re)connect ethernet connection to FTM, a new address can be given"
453 "|[host][string]:new ethernet address in the form <host:port>");
454*/
455 }
456
457 int EvalOptions(Configuration &conf)
458 {
459 fLidar.SetVerbose(!conf.Get<bool>("quiet"));
460 fLidar.SetInterval(conf.Get<uint16_t>("interval"));
461 fLidar.SetDebugTx(conf.Get<bool>("debug-tx"));
462 fLidar.SetSite(conf.Get<string>("url"));
463 fLidar.SetEndpoint(conf.Get<string>("addr"));
464 fLidar.StartConnect();
465
466 return -1;
467 }
468};
469
470// ------------------------------------------------------------------------
471
472#include "Main.h"
473
474
475template<class T, class S, class R>
476int RunShell(Configuration &conf)
477{
478 return Main::execute<T, StateMachineLidar<S, R>>(conf);
479}
480
481void SetupConfiguration(Configuration &conf)
482{
483 po::options_description control("MAGIC lidar control options");
484 control.add_options()
485 ("no-dim,d", po_switch(), "Disable dim services")
486 ("addr,a", var<string>("www.magic.iac.es:80"), "Network address of Cosy")
487 ("url,u", var<string>("/site/weather/lidar_data.txt"), "File name and path to load")
488 ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
489 ("interval,i", var<uint16_t>(30), "Interval between two updates on the server in seconds")
490 ("debug-tx", po_bool(), "Enable debugging of ethernet transmission.")
491 ;
492
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 magiclidar is an interface to the MAGIC lidar data.\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: magiclidar [-c type] [OPTIONS]\n"
516 " or: magiclidar [OPTIONS]\n";
517 cout << endl;
518}
519
520void PrintHelp()
521{
522// Main::PrintHelp<StateMachineFTM<StateMachine, ConnectionFTM>>();
523
524 /* Additional help text which is printed after the configuration
525 options goes here */
526
527 /*
528 cout << "bla bla bla" << endl << endl;
529 cout << endl;
530 cout << "Environment:" << endl;
531 cout << "environment" << endl;
532 cout << endl;
533 cout << "Examples:" << endl;
534 cout << "test exam" << endl;
535 cout << endl;
536 cout << "Files:" << endl;
537 cout << "files" << endl;
538 cout << endl;
539 */
540}
541
542int main(int argc, const char* argv[])
543{
544 Configuration conf(argv[0]);
545 conf.SetPrintUsage(PrintUsage);
546 Main::SetupConfiguration(conf);
547 SetupConfiguration(conf);
548
549 if (!conf.DoParse(argc, argv, PrintHelp))
550 return 127;
551
552 //try
553 {
554 // No console access at all
555 if (!conf.Has("console"))
556 {
557 if (conf.Get<bool>("no-dim"))
558 return RunShell<LocalStream, StateMachine, ConnectionLidar>(conf);
559 else
560 return RunShell<LocalStream, StateMachineDim, ConnectionDimLidar>(conf);
561 }
562 // Cosole access w/ and w/o Dim
563 if (conf.Get<bool>("no-dim"))
564 {
565 if (conf.Get<int>("console")==0)
566 return RunShell<LocalShell, StateMachine, ConnectionLidar>(conf);
567 else
568 return RunShell<LocalConsole, StateMachine, ConnectionLidar>(conf);
569 }
570 else
571 {
572 if (conf.Get<int>("console")==0)
573 return RunShell<LocalShell, StateMachineDim, ConnectionDimLidar>(conf);
574 else
575 return RunShell<LocalConsole, StateMachineDim, ConnectionDimLidar>(conf);
576 }
577 }
578 /*catch (std::exception& e)
579 {
580 cerr << "Exception: " << e.what() << endl;
581 return -1;
582 }*/
583
584 return 0;
585}
Note: See TracBrowser for help on using the repository browser.