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

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