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

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