source: trunk/FACT++/src/tngweather.cc@ 16736

Last change on this file since 16736 was 16727, checked in by tbretz, 11 years ago
Make use of the new StateMachineAsio which gets the CPU consumption to basically 0 by a more intelligent event management.
File size: 18.9 KB
Line 
1#include <boost/array.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 "StateMachineAsio.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 "HeadersTNGWeather.h"
22
23#include <Soprano/Soprano>
24
25namespace ba = boost::asio;
26namespace bs = boost::system;
27namespace dummy = ba::placeholders;
28
29using namespace std;
30using namespace TNGWeather;
31
32
33class ConnectionWeather : public Connection
34{
35 uint16_t fInterval;
36
37 bool fIsVerbose;
38
39 string fSite;
40
41 virtual void UpdateWeather(const Time &, const DimWeather &)
42 {
43 }
44
45 virtual void UpdateDust(const Time &, const float &)
46 {
47 }
48
49 string fRdfData;
50 float fDust;
51
52protected:
53
54 boost::array<char, 4096> fArray;
55
56 Time fLastReport;
57 Time fLastReception;
58
59 void HandleRead(const boost::system::error_code& err, size_t bytes_received)
60 {
61 // Do not schedule a new read if the connection failed.
62 if (bytes_received==0 || err)
63 {
64 if (err==ba::error::eof)
65 Warn("Connection closed by remote host.");
66
67 // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
68 // 125: Operation canceled
69 if (err && err!=ba::error::eof && // Connection closed by remote host
70 err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
71 err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
72 {
73 ostringstream str;
74 str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
75 Error(str);
76 }
77 PostClose(err!=ba::error::basic_errors::operation_aborted);
78
79 fRdfData = "";
80 return;
81 }
82
83 fRdfData += string(fArray.data(), bytes_received);
84
85 const size_t end = fRdfData.find("\r\n\r\n");
86 if (end==string::npos)
87 {
88 Out() << "Received data corrupted [1]." << endl;
89 Out() << fRdfData << endl;
90 return;
91 }
92
93 string data(fRdfData);
94 data.erase(0, end+4);
95
96 size_t pos = 0;
97 while (1)
98 {
99 const size_t chunk = data.find("\r\n", pos);
100 if (chunk==0 || chunk==string::npos)
101 {
102 StartReadReport();
103 return;
104 }
105
106 size_t len = 0;
107 stringstream val(data.substr(pos, chunk-pos));
108 val >> hex >> len;
109
110 data.erase(pos, chunk-pos+2);
111 if (len==0)
112 break;
113
114 pos += len+2; // Count trailing \r\n of chunk
115 }
116
117
118 fLastReception = Time();
119 fRdfData = "";
120 PostClose(false);
121
122 if (fIsVerbose)
123 {
124 Out() << "------------------------------------------------------" << endl;
125 Out() << data << endl;
126 Out() << "------------------------------------------------------" << endl;
127 }
128
129 const Soprano::Parser* p = Soprano::PluginManager::instance()->discoverParserForSerialization( Soprano::SerializationRdfXml );
130 Soprano::StatementIterator it = p->parseString(QString(data.c_str()), QUrl(""), Soprano::SerializationRdfXml );
131
132
133 DimWeather w;
134 Time time(Time::none);
135 try
136 {
137 while (it.next())
138 {
139 const string pre = (*it).predicate().toString().toStdString();
140 const string obj = (*it).object().toString().toStdString();
141
142 const size_t slash = pre.find_last_of('/');
143 if (slash==string::npos)
144 continue;
145
146 const string id = pre.substr(slash+1);
147
148 if (obj=="N/A")
149 continue;
150
151 if (id=="dimmSeeing")
152 w.fSeeing = stof(obj);
153 if (id=="dustTotal")
154 w.fDustTotal = stof(obj);
155 if (id=="deltaM1")
156 w.fDeltaM1 = stof(obj);
157 if (id=="airPressure")
158 w.fAirPressure = stof(obj);
159 if (id=="dewPoint")
160 w.fDewPoint = stof(obj);
161 if (id=="windDirection")
162 w.fWindDirection = stof(obj);
163 if (id=="windSpeed")
164 w.fWindSpeed = stof(obj)*3.6;
165 if (id=="hum")
166 w.fHumidity = stof(obj);
167 if (id=="tempGround")
168 w.fTempGround = stof(obj);
169 if (id=="temp2M")
170 w.fTemp2M = stof(obj);
171 if (id=="temp5M")
172 w.fTemp5M = stof(obj);
173 if (id=="temp10M")
174 w.fTemp10M = stof(obj);
175 if (id=="date")
176 {
177 time.SetFromStr(obj, "%Y-%m-%dT%H:%M:%S");
178
179 if (!time.IsValid())
180 {
181 struct tm tm;
182
183 vector<char> buf(255);
184 if (strptime(obj.c_str(), "%c", &tm))
185 time = Time(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
186 tm.tm_hour, tm.tm_min, tm.tm_sec);
187 }
188 }
189
190 /*
191 Out() << "S: " << (*it).subject().toString().toStdString() << endl;
192 Out() << "P: " << (*it).predicate().toString().toStdString() << endl;
193 Out() << "O: " << (*it).object().toString().toStdString() << endl;
194 Out() << "C: " << (*it).context().toString().toStdString() << endl;
195 */
196 }
197
198 if (!time.IsValid())
199 throw runtime_error("time invalid");
200
201 if (time!=fLastReport && fIsVerbose)
202 {
203 Out() << endl;
204 Out() << "Date: " << time << endl;
205 Out() << "Seeing: " << w.fSeeing << endl;
206 Out() << "DustTotal: " << w.fDustTotal << endl;
207 Out() << "DeltaM1: " << w.fDeltaM1 << endl;
208 Out() << "AirPressure: " << w.fAirPressure << endl;
209 Out() << "DewPoint: " << w.fDewPoint << endl;
210 Out() << "WindDirection: " << w.fWindDirection << endl;
211 Out() << "WindSpeed: " << w.fWindSpeed << endl;
212 Out() << "Humidity: " << w.fHumidity << endl;
213 Out() << "TempGround: " << w.fTempGround << endl;
214 Out() << "Temp2M: " << w.fTemp2M << endl;
215 Out() << "Temp5M: " << w.fTemp5M << endl;
216 Out() << "Temp10M: " << w.fTemp10M << endl;
217 Out() << endl;
218 }
219
220 fLastReport = time;
221
222 UpdateWeather(time, w);
223
224 if (fDust==w.fDustTotal)
225 return;
226
227 UpdateDust(time, w.fDustTotal);
228 fDust = w.fDustTotal;
229
230 ostringstream out;
231 out << setprecision(3) << "Dust: " << fDust << "ug/m^3 [" << time << "]";
232 Message(out);
233 }
234
235 catch (const exception &e)
236 {
237 Out() << "Corrupted data received: " << e.what() << endl;
238 fLastReport = Time(Time::none);
239 return;
240 }
241 }
242
243 void StartReadReport()
244 {
245 async_read_some(ba::buffer(fArray),
246 boost::bind(&ConnectionWeather::HandleRead, this,
247 dummy::error, dummy::bytes_transferred));
248 }
249
250 boost::asio::deadline_timer fKeepAlive;
251
252 void PostRequest()
253 {
254 const string cmd =
255 "GET "+fSite+" HTTP/1.1\r\n"
256 "Accept: */*\r\n"
257 "Content-Type: application/octet-stream\r\n"
258 "User-Agent: FACT\r\n"
259 "Host: www.fact-project.org\r\n"
260 "Pragma: no-cache\r\n"
261 "Cache-Control: no-cache\r\n"
262 "Expires: 0\r\n"
263 "Connection: Keep-Alive\r\n"
264 "Cache-Control: max-age=0\r\n"
265 "\r\n";
266
267 PostMessage(cmd);
268 }
269
270 void Request()
271 {
272 PostRequest();
273
274 fKeepAlive.expires_from_now(boost::posix_time::seconds(fInterval));
275 fKeepAlive.async_wait(boost::bind(&ConnectionWeather::HandleRequest,
276 this, dummy::error));
277 }
278
279 void HandleRequest(const bs::error_code &error)
280 {
281 // 125: Operation canceled (bs::error_code(125, bs::system_category))
282 if (error && error!=ba::error::basic_errors::operation_aborted)
283 {
284 ostringstream str;
285 str << "Write timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
286 Error(str);
287
288 PostClose(false);
289 return;
290 }
291
292 if (!is_open())
293 {
294 // For example: Here we could schedule a new accept if we
295 // would not want to allow two connections at the same time.
296 PostClose(true);
297 return;
298 }
299
300 // Check whether the deadline has passed. We compare the deadline
301 // against the current time since a new asynchronous operation
302 // may have moved the deadline before this actor had a chance
303 // to run.
304 if (fKeepAlive.expires_at() > ba::deadline_timer::traits_type::now())
305 return;
306
307 Request();
308 }
309
310
311private:
312 // This is called when a connection was established
313 void ConnectionEstablished()
314 {
315 Request();
316 StartReadReport();
317 }
318
319public:
320
321 static const uint16_t kMaxAddr;
322
323public:
324 ConnectionWeather(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
325 fIsVerbose(true), fDust(-1),
326 fLastReport(Time::none), fLastReception(Time::none),
327 fKeepAlive(ioservice)
328 {
329 SetLogStream(&imp);
330 }
331
332 void SetVerbose(bool b)
333 {
334 fIsVerbose = b;
335 Connection::SetVerbose(b);
336 }
337
338 void SetInterval(uint16_t i)
339 {
340 fInterval = i;
341 }
342
343 void SetSite(const string &site)
344 {
345 fSite = site;
346 }
347
348 int GetState() const
349 {
350 if (fLastReport.IsValid() && fLastReport+boost::posix_time::seconds(fInterval*2)>Time())
351 return 3; // receiving
352
353 if (fLastReception.IsValid() && fLastReception+boost::posix_time::seconds(fInterval*2)>Time())
354 return 2; // connected
355
356 return 1; // Disconnected
357 }
358};
359
360const uint16_t ConnectionWeather::kMaxAddr = 0xfff;
361
362// ------------------------------------------------------------------------
363
364#include "DimDescriptionService.h"
365
366class ConnectionDimWeather : public ConnectionWeather
367{
368private:
369 DimDescribedService fDimWeather;
370 DimDescribedService fDimAtmosphere;
371
372 virtual void UpdateWeather(const Time &t, const DimWeather &data)
373 {
374 fDimWeather.setData(&data, sizeof(DimWeather));
375 fDimWeather.Update(t);
376 }
377
378 virtual void UpdateDust(const Time &t, const float &dust)
379 {
380 fDimAtmosphere.setData(&dust, sizeof(float));
381 fDimAtmosphere.Update(t);
382 }
383
384public:
385 ConnectionDimWeather(ba::io_service& ioservice, MessageImp &imp) :
386 ConnectionWeather(ioservice, imp),
387 fDimWeather("TNG_WEATHER/DATA", "F:1;F:1;F:1;F:1;F:1;F:1;F:1;F:1;F:1;F:1;F:1;F:1",
388 "|T_10M[deg C]:Temperature 10m above ground"
389 "|T_5M[deg C]:Temperature 5m above ground"
390 "|T_2M[deg C]:Temperature 2m above ground"
391 "|T_0[deg C]:Temperature at ground"
392 "|T_dew[deg C]:Dew point"
393 "|H[%]:Humidity"
394 "|P[mbar]:Air pressure"
395 "|v[km/h]:Wind speed"
396 "|d[deg]:Wind direction (N-E)"
397 "|DeltaM1"
398 "|Dust[ug/m^3]:Dust (total)"
399 "|Seeing[W/m^2]:Seeing"),
400 fDimAtmosphere("TNG_WEATHER/DUST", "F:1",
401 "|Dust[ug/m^3]:Dust (total)")
402 {
403 }
404};
405
406// ------------------------------------------------------------------------
407
408template <class T, class S>
409class StateMachineWeather : public StateMachineAsio<T>
410{
411private:
412 S fWeather;
413
414 bool CheckEventSize(size_t has, const char *name, size_t size)
415 {
416 if (has==size)
417 return true;
418
419 ostringstream msg;
420 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
421 T::Fatal(msg);
422 return false;
423 }
424
425 int SetVerbosity(const EventImp &evt)
426 {
427 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
428 return T::kSM_FatalError;
429
430 fWeather.SetVerbose(evt.GetBool());
431
432 return T::GetCurrentState();
433 }
434/*
435 int Disconnect()
436 {
437 // Close all connections
438 fWeather.PostClose(false);
439
440 return T::GetCurrentState();
441 }
442
443 int Reconnect(const EventImp &evt)
444 {
445 // Close all connections to supress the warning in SetEndpoint
446 fWeather.PostClose(false);
447
448 // Now wait until all connection have been closed and
449 // all pending handlers have been processed
450 poll();
451
452 if (evt.GetBool())
453 fWeather.SetEndpoint(evt.GetString());
454
455 // Now we can reopen the connection
456 fWeather.PostClose(true);
457
458 return T::GetCurrentState();
459 }
460*/
461 int Execute()
462 {
463 return fWeather.GetState();
464 }
465
466
467public:
468 StateMachineWeather(ostream &out=cout) :
469 StateMachineAsio<T>(out, "TNG_WEATHER"), fWeather(*this, *this)
470 {
471 // State names
472 T::AddStateName(State::kDisconnected, "NoConnection",
473 "No connection to web-server could be established recently");
474
475 T::AddStateName(State::kConnected, "Invalid",
476 "Connection to webserver can be established, but received data is not recent or invalid");
477
478 T::AddStateName(State::kReceiving, "Valid",
479 "Connection to webserver can be established, receint data received");
480
481 // Verbosity commands
482 T::AddEvent("SET_VERBOSE", "B")
483 (bind(&StateMachineWeather::SetVerbosity, this, placeholders::_1))
484 ("set verbosity state"
485 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
486/*
487 // Conenction commands
488 AddEvent("DISCONNECT")
489 (bind(&StateMachineWeather::Disconnect, this))
490 ("disconnect from ethernet");
491
492 AddEvent("RECONNECT", "O")
493 (bind(&StateMachineWeather::Reconnect, this, placeholders::_1))
494 ("(Re)connect ethernet connection to FTM, a new address can be given"
495 "|[host][string]:new ethernet address in the form <host:port>");
496*/
497 }
498
499 int EvalOptions(Configuration &conf)
500 {
501 fWeather.SetVerbose(!conf.Get<bool>("quiet"));
502 fWeather.SetInterval(conf.Get<uint16_t>("interval"));
503 fWeather.SetDebugTx(conf.Get<bool>("debug-tx"));
504 fWeather.SetSite(conf.Get<string>("url"));
505 fWeather.SetEndpoint(conf.Get<string>("addr"));
506 fWeather.StartConnect();
507
508 return -1;
509 }
510};
511
512// ------------------------------------------------------------------------
513
514#include "Main.h"
515
516
517template<class T, class S, class R>
518int RunShell(Configuration &conf)
519{
520 return Main::execute<T, StateMachineWeather<S, R>>(conf);
521}
522
523void SetupConfiguration(Configuration &conf)
524{
525 po::options_description control("TNG weather control options");
526 control.add_options()
527 ("no-dim,d", po_switch(), "Disable dim services")
528 ("addr,a", var<string>("tngweb.tng.iac.es:80"), "Network address of Cosy")
529 ("url,u", var<string>("/weather/rss/"), "File name and path to load")
530 ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
531 ("interval,i", var<uint16_t>(300), "Interval between two updates on the server in seconds")
532 ("debug-tx", po_bool(), "Enable debugging of ethernet transmission.")
533 ;
534
535 conf.AddOptions(control);
536}
537
538/*
539 Extract usage clause(s) [if any] for SYNOPSIS.
540 Translators: "Usage" and "or" here are patterns (regular expressions) which
541 are used to match the usage synopsis in program output. An example from cp
542 (GNU coreutils) which contains both strings:
543 Usage: cp [OPTION]... [-T] SOURCE DEST
544 or: cp [OPTION]... SOURCE... DIRECTORY
545 or: cp [OPTION]... -t DIRECTORY SOURCE...
546 */
547void PrintUsage()
548{
549 cout <<
550 "The tngweather is an interface to the TNG weather data.\n"
551 "\n"
552 "The default is that the program is started without user intercation. "
553 "All actions are supposed to arrive as DimCommands. Using the -c "
554 "option, a local shell can be initialized. With h or help a short "
555 "help message about the usuage can be brought to the screen.\n"
556 "\n"
557 "Usage: tngweather [-c type] [OPTIONS]\n"
558 " or: tngweather [OPTIONS]\n";
559 cout << endl;
560}
561
562void PrintHelp()
563{
564// Main::PrintHelp<StateMachineFTM<StateMachine, ConnectionFTM>>();
565
566 /* Additional help text which is printed after the configuration
567 options goes here */
568
569 /*
570 cout << "bla bla bla" << endl << endl;
571 cout << endl;
572 cout << "Environment:" << endl;
573 cout << "environment" << endl;
574 cout << endl;
575 cout << "Examples:" << endl;
576 cout << "test exam" << endl;
577 cout << endl;
578 cout << "Files:" << endl;
579 cout << "files" << endl;
580 cout << endl;
581 */
582}
583
584int main(int argc, const char* argv[])
585{
586 Configuration conf(argv[0]);
587 conf.SetPrintUsage(PrintUsage);
588 Main::SetupConfiguration(conf);
589 SetupConfiguration(conf);
590
591 if (!conf.DoParse(argc, argv, PrintHelp))
592 return 127;
593
594 //try
595 {
596 // No console access at all
597 if (!conf.Has("console"))
598 {
599 if (conf.Get<bool>("no-dim"))
600 return RunShell<LocalStream, StateMachine, ConnectionWeather>(conf);
601 else
602 return RunShell<LocalStream, StateMachineDim, ConnectionDimWeather>(conf);
603 }
604 // Cosole access w/ and w/o Dim
605 if (conf.Get<bool>("no-dim"))
606 {
607 if (conf.Get<int>("console")==0)
608 return RunShell<LocalShell, StateMachine, ConnectionWeather>(conf);
609 else
610 return RunShell<LocalConsole, StateMachine, ConnectionWeather>(conf);
611 }
612 else
613 {
614 if (conf.Get<int>("console")==0)
615 return RunShell<LocalShell, StateMachineDim, ConnectionDimWeather>(conf);
616 else
617 return RunShell<LocalConsole, StateMachineDim, ConnectionDimWeather>(conf);
618 }
619 }
620 /*catch (std::exception& e)
621 {
622 cerr << "Exception: " << e.what() << endl;
623 return -1;
624 }*/
625
626 return 0;
627}
Note: See TracBrowser for help on using the repository browser.