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

Last change on this file since 14967 was 14964, checked in by tbretz, 12 years ago
Removed obsolete old variables.
File size: 17.5 KB
Line 
1#include <boost/bind.hpp>
2
3//#include <string> // std::string
4//#include <algorithm> // std::transform
5//#include <cctype> // std::tolower
6
7#include "FACT.h"
8#include "Dim.h"
9#include "Event.h"
10#include "Shell.h"
11#include "StateMachineDim.h"
12#include "Connection.h"
13#include "LocalControl.h"
14#include "Configuration.h"
15#include "Timers.h"
16#include "Console.h"
17
18#include "tools.h"
19
20#include "HeadersMagicLidar.h"
21
22namespace ba = boost::asio;
23namespace bs = boost::system;
24namespace dummy = ba::placeholders;
25
26using namespace std;
27using namespace MagicLidar;
28
29// ------------------------------------------------------------------------
30
31class ConnectionLidar : public Connection
32{
33 uint16_t fInterval;
34
35 bool fIsVerbose;
36
37 string fSite;
38
39 virtual void UpdateLidar(const Time &, const DimLidar &)
40 {
41 }
42
43protected:
44
45 boost::array<char, 4096> fArray;
46
47 Time fLastReport;
48 Time fLastReception;
49
50 void HandleRead(const boost::system::error_code& err, size_t bytes_received)
51 {
52 // Do not schedule a new read if the connection failed.
53 if (bytes_received==0 || err)
54 {
55 if (err==ba::error::eof)
56 Warn("Connection closed by remote host.");
57
58 // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
59 // 125: Operation canceled
60 if (err && err!=ba::error::eof && // Connection closed by remote host
61 err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
62 err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
63 {
64 ostringstream str;
65 str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
66 Error(str);
67 }
68 PostClose(err!=ba::error::basic_errors::operation_aborted);
69 return;
70 }
71
72 fLastReception = Time();
73
74 const string str(fArray.data(), bytes_received);
75 memset(fArray.data(), 0, fArray.size());
76
77 if (fIsVerbose)
78 Out() << str << endl;
79
80 bool isheader = true;
81
82 DimLidar data;
83
84 int hh=0, mm=0, ss=0, y=0, m=0, d=0;
85
86 bool keepalive = false;
87 bool failed = false;
88
89 stringstream is(str);
90 string line;
91 while (getline(is, line))
92 {
93 if (line.size()==1 && line[0]==13)
94 {
95 isheader = false;
96 continue;
97 }
98
99 if (isheader)
100 {
101 const size_t p = line.find_first_of(": ");
102 if (p==string::npos)
103 continue;
104
105 std::transform(line.begin(), line.end(), line.begin(), (int(&)(int))std::tolower);
106
107 const string key = line.substr(0, p);
108 const string val = line.substr(p+2);
109
110 if (key=="connection" && val=="keep-alive")
111 keepalive = true;
112 }
113 else
114 {
115 try
116 {
117 if (line.substr(0, 3)=="ZEN")
118 data.fZd = stoi(line.substr(3));
119 if (line.substr(0, 2)=="AZ")
120 data.fAz = stof(line.substr(2));
121
122 //if (line.substr(0, 3)=="PBL")
123 // data.fPBL = stof(line.substr(3));
124 //if (line.substr(0, 3)=="CHE")
125 // data.fCHE = stof(line.substr(3));
126 //if (line.substr(0, 3)=="COT")
127 // data.fCOT = stof(line.substr(3));
128
129 if (line.substr(0, 2)=="T3")
130 data.fT3 = stof(line.substr(2));
131 if (line.substr(0, 2)=="T6")
132 data.fT6 = stof(line.substr(2));
133 if (line.substr(0, 2)=="T9")
134 data.fT9 = stof(line.substr(2));
135 if (line.substr(0, 3)=="T12")
136 data.fT12 = stof(line.substr(3));
137
138 if (line.substr(0, 4)=="HOUR")
139 hh = stoi(line.substr(4));
140 if (line.substr(0, 6)=="MINUTS")
141 mm = stoi(line.substr(6));
142 if (line.substr(0, 7)=="SECONDS")
143 ss = stoi(line.substr(7));
144
145 if (line.substr(0, 4)=="YEAR")
146 y = stoi(line.substr(4));
147 if (line.substr(0, 5)=="MONTH")
148 m = stoi(line.substr(5));
149 if (line.substr(0, 3)=="DAY")
150 d = stoi(line.substr(3));
151 }
152 catch (const exception &e)
153 {
154 Warn("Conversion of received data failed");
155 failed = true;
156 break;
157 }
158 }
159 }
160
161 if (!keepalive)
162 PostClose(false);
163
164 if (failed)
165 return;
166
167 try
168 {
169 const Time tm = Time(2000+y, m, d, hh, mm, ss);
170 if (tm==fLastReport)
171 return;
172
173 ostringstream msg;
174 msg << tm.GetAsStr("%H:%M:%S") << ":"
175 //<< " PBL=" << data.fPBL
176 //<< " CHE=" << data.fCHE
177 //<< " COT=" << data.fCOT
178 << " T3-12=" << data.fT3
179 << "/" << data.fT6
180 << "/" << data.fT9
181 << "/" << data.fT12
182 << " Zd=" << data.fZd << "°"
183 << " Az=" << data.fAz << "°";
184 Message(msg);
185
186 UpdateLidar(tm, data);
187
188 fLastReport = tm;
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;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 T, public ba::io_service, public ba::io_service::work
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 // Dispatch (execute) at most one handler from the queue. In contrary
406 // to run_one(), it doesn't wait until a handler is available
407 // which can be dispatched, so poll_one() might return with 0
408 // handlers dispatched. The handlers are always dispatched/executed
409 // synchronously, i.e. within the call to poll_one()
410 poll_one();
411
412 return fLidar.GetState();
413 }
414
415
416public:
417 StateMachineLidar(ostream &out=cout) :
418 T(out, "MAGIC_LIDAR"), ba::io_service::work(static_cast<ba::io_service&>(*this)),
419 fLidar(*this, *this)
420 {
421 // ba::io_service::work is a kind of keep_alive for the loop.
422 // It prevents the io_service to go to stopped state, which
423 // would prevent any consecutive calls to run()
424 // or poll() to do nothing. reset() could also revoke to the
425 // previous state but this might introduce some overhead of
426 // deletion and creation of threads and more.
427
428 // State names
429 T::AddStateName(State::kDisconnected, "NoConnection",
430 "No connection to web-server could be established recently");
431
432 T::AddStateName(State::kConnected, "Invalid",
433 "Connection to webserver can be established, but received data is not recent or invalid");
434
435 T::AddStateName(State::kReceiving, "Valid",
436 "Connection to webserver can be established, receint data received");
437
438 // Verbosity commands
439 T::AddEvent("SET_VERBOSE", "B")
440 (bind(&StateMachineLidar::SetVerbosity, this, placeholders::_1))
441 ("set verbosity state"
442 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
443/*
444 // Conenction commands
445 AddEvent("DISCONNECT")
446 (bind(&StateMachineLidar::Disconnect, this))
447 ("disconnect from ethernet");
448
449 AddEvent("RECONNECT", "O")
450 (bind(&StateMachineLidar::Reconnect, this, placeholders::_1))
451 ("(Re)connect ethernet connection to FTM, a new address can be given"
452 "|[host][string]:new ethernet address in the form <host:port>");
453*/
454 }
455
456 int EvalOptions(Configuration &conf)
457 {
458 fLidar.SetVerbose(!conf.Get<bool>("quiet"));
459 fLidar.SetInterval(conf.Get<uint16_t>("interval"));
460 fLidar.SetDebugTx(conf.Get<bool>("debug-tx"));
461 fLidar.SetSite(conf.Get<string>("url"));
462 fLidar.SetEndpoint(conf.Get<string>("addr"));
463 fLidar.StartConnect();
464
465 return -1;
466 }
467};
468
469// ------------------------------------------------------------------------
470
471#include "Main.h"
472
473
474template<class T, class S, class R>
475int RunShell(Configuration &conf)
476{
477 return Main::execute<T, StateMachineLidar<S, R>>(conf);
478}
479
480void SetupConfiguration(Configuration &conf)
481{
482 po::options_description control("MAGIC lidar control options");
483 control.add_options()
484 ("no-dim,d", po_switch(), "Disable dim services")
485 ("addr,a", var<string>("www.magic.iac.es:80"), "Network address of Cosy")
486 ("url,u", var<string>("/site/weather/lidar_data.txt"), "File name and path to load")
487 ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
488 ("interval,i", var<uint16_t>(30), "Interval between two updates on the server in seconds")
489 ("debug-tx", po_bool(), "Enable debugging of ethernet transmission.")
490 ;
491
492 conf.AddOptions(control);
493}
494
495/*
496 Extract usage clause(s) [if any] for SYNOPSIS.
497 Translators: "Usage" and "or" here are patterns (regular expressions) which
498 are used to match the usage synopsis in program output. An example from cp
499 (GNU coreutils) which contains both strings:
500 Usage: cp [OPTION]... [-T] SOURCE DEST
501 or: cp [OPTION]... SOURCE... DIRECTORY
502 or: cp [OPTION]... -t DIRECTORY SOURCE...
503 */
504void PrintUsage()
505{
506 cout <<
507 "The magiclidar is an interface to the MAGIC lidar data.\n"
508 "\n"
509 "The default is that the program is started without user intercation. "
510 "All actions are supposed to arrive as DimCommands. Using the -c "
511 "option, a local shell can be initialized. With h or help a short "
512 "help message about the usuage can be brought to the screen.\n"
513 "\n"
514 "Usage: magiclidar [-c type] [OPTIONS]\n"
515 " or: magiclidar [OPTIONS]\n";
516 cout << endl;
517}
518
519void PrintHelp()
520{
521// Main::PrintHelp<StateMachineFTM<StateMachine, ConnectionFTM>>();
522
523 /* Additional help text which is printed after the configuration
524 options goes here */
525
526 /*
527 cout << "bla bla bla" << endl << endl;
528 cout << endl;
529 cout << "Environment:" << endl;
530 cout << "environment" << endl;
531 cout << endl;
532 cout << "Examples:" << endl;
533 cout << "test exam" << endl;
534 cout << endl;
535 cout << "Files:" << endl;
536 cout << "files" << endl;
537 cout << endl;
538 */
539}
540
541int main(int argc, const char* argv[])
542{
543 Configuration conf(argv[0]);
544 conf.SetPrintUsage(PrintUsage);
545 Main::SetupConfiguration(conf);
546 SetupConfiguration(conf);
547
548 if (!conf.DoParse(argc, argv, PrintHelp))
549 return 127;
550
551 //try
552 {
553 // No console access at all
554 if (!conf.Has("console"))
555 {
556 if (conf.Get<bool>("no-dim"))
557 return RunShell<LocalStream, StateMachine, ConnectionLidar>(conf);
558 else
559 return RunShell<LocalStream, StateMachineDim, ConnectionDimLidar>(conf);
560 }
561 // Cosole access w/ and w/o Dim
562 if (conf.Get<bool>("no-dim"))
563 {
564 if (conf.Get<int>("console")==0)
565 return RunShell<LocalShell, StateMachine, ConnectionLidar>(conf);
566 else
567 return RunShell<LocalConsole, StateMachine, ConnectionLidar>(conf);
568 }
569 else
570 {
571 if (conf.Get<int>("console")==0)
572 return RunShell<LocalShell, StateMachineDim, ConnectionDimLidar>(conf);
573 else
574 return RunShell<LocalConsole, StateMachineDim, ConnectionDimLidar>(conf);
575 }
576 }
577 /*catch (std::exception& e)
578 {
579 cerr << "Exception: " << e.what() << endl;
580 return -1;
581 }*/
582
583 return 0;
584}
Note: See TracBrowser for help on using the repository browser.