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

Last change on this file since 15040 was 14978, checked in by tbretz, 12 years ago
Added include for array.hpp - needed for newer boost versions
File size: 19.7 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 "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 T, public ba::io_service, public ba::io_service::work
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 // Dispatch (execute) at most one handler from the queue. In contrary
464 // to run_one(), it doesn't wait until a handler is available
465 // which can be dispatched, so poll_one() might return with 0
466 // handlers dispatched. The handlers are always dispatched/executed
467 // synchronously, i.e. within the call to poll_one()
468 poll_one();
469
470 return fWeather.GetState();
471 }
472
473
474public:
475 StateMachineWeather(ostream &out=cout) :
476 T(out, "TNG_WEATHER"), ba::io_service::work(static_cast<ba::io_service&>(*this)),
477 fWeather(*this, *this)
478 {
479 // ba::io_service::work is a kind of keep_alive for the loop.
480 // It prevents the io_service to go to stopped state, which
481 // would prevent any consecutive calls to run()
482 // or poll() to do nothing. reset() could also revoke to the
483 // previous state but this might introduce some overhead of
484 // deletion and creation of threads and more.
485
486 // State names
487 T::AddStateName(State::kDisconnected, "NoConnection",
488 "No connection to web-server could be established recently");
489
490 T::AddStateName(State::kConnected, "Invalid",
491 "Connection to webserver can be established, but received data is not recent or invalid");
492
493 T::AddStateName(State::kReceiving, "Valid",
494 "Connection to webserver can be established, receint data received");
495
496 // Verbosity commands
497 T::AddEvent("SET_VERBOSE", "B")
498 (bind(&StateMachineWeather::SetVerbosity, this, placeholders::_1))
499 ("set verbosity state"
500 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
501/*
502 // Conenction commands
503 AddEvent("DISCONNECT")
504 (bind(&StateMachineWeather::Disconnect, this))
505 ("disconnect from ethernet");
506
507 AddEvent("RECONNECT", "O")
508 (bind(&StateMachineWeather::Reconnect, this, placeholders::_1))
509 ("(Re)connect ethernet connection to FTM, a new address can be given"
510 "|[host][string]:new ethernet address in the form <host:port>");
511*/
512 }
513
514 int EvalOptions(Configuration &conf)
515 {
516 fWeather.SetVerbose(!conf.Get<bool>("quiet"));
517 fWeather.SetInterval(conf.Get<uint16_t>("interval"));
518 fWeather.SetDebugTx(conf.Get<bool>("debug-tx"));
519 fWeather.SetSite(conf.Get<string>("url"));
520 fWeather.SetEndpoint(conf.Get<string>("addr"));
521 fWeather.StartConnect();
522
523 return -1;
524 }
525};
526
527// ------------------------------------------------------------------------
528
529#include "Main.h"
530
531
532template<class T, class S, class R>
533int RunShell(Configuration &conf)
534{
535 return Main::execute<T, StateMachineWeather<S, R>>(conf);
536}
537
538void SetupConfiguration(Configuration &conf)
539{
540 po::options_description control("TNG weather control options");
541 control.add_options()
542 ("no-dim,d", po_switch(), "Disable dim services")
543 ("addr,a", var<string>("tngweb.tng.iac.es:80"), "Network address of Cosy")
544 ("url,u", var<string>("/weather/rss/"), "File name and path to load")
545 ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
546 ("interval,i", var<uint16_t>(300), "Interval between two updates on the server in seconds")
547 ("debug-tx", po_bool(), "Enable debugging of ethernet transmission.")
548 ;
549
550 conf.AddOptions(control);
551}
552
553/*
554 Extract usage clause(s) [if any] for SYNOPSIS.
555 Translators: "Usage" and "or" here are patterns (regular expressions) which
556 are used to match the usage synopsis in program output. An example from cp
557 (GNU coreutils) which contains both strings:
558 Usage: cp [OPTION]... [-T] SOURCE DEST
559 or: cp [OPTION]... SOURCE... DIRECTORY
560 or: cp [OPTION]... -t DIRECTORY SOURCE...
561 */
562void PrintUsage()
563{
564 cout <<
565 "The tngweather is an interface to the TNG weather data.\n"
566 "\n"
567 "The default is that the program is started without user intercation. "
568 "All actions are supposed to arrive as DimCommands. Using the -c "
569 "option, a local shell can be initialized. With h or help a short "
570 "help message about the usuage can be brought to the screen.\n"
571 "\n"
572 "Usage: tngweather [-c type] [OPTIONS]\n"
573 " or: tngweather [OPTIONS]\n";
574 cout << endl;
575}
576
577void PrintHelp()
578{
579// Main::PrintHelp<StateMachineFTM<StateMachine, ConnectionFTM>>();
580
581 /* Additional help text which is printed after the configuration
582 options goes here */
583
584 /*
585 cout << "bla bla bla" << endl << endl;
586 cout << endl;
587 cout << "Environment:" << endl;
588 cout << "environment" << endl;
589 cout << endl;
590 cout << "Examples:" << endl;
591 cout << "test exam" << endl;
592 cout << endl;
593 cout << "Files:" << endl;
594 cout << "files" << endl;
595 cout << endl;
596 */
597}
598
599int main(int argc, const char* argv[])
600{
601 Configuration conf(argv[0]);
602 conf.SetPrintUsage(PrintUsage);
603 Main::SetupConfiguration(conf);
604 SetupConfiguration(conf);
605
606 if (!conf.DoParse(argc, argv, PrintHelp))
607 return 127;
608
609 //try
610 {
611 // No console access at all
612 if (!conf.Has("console"))
613 {
614 if (conf.Get<bool>("no-dim"))
615 return RunShell<LocalStream, StateMachine, ConnectionWeather>(conf);
616 else
617 return RunShell<LocalStream, StateMachineDim, ConnectionDimWeather>(conf);
618 }
619 // Cosole access w/ and w/o Dim
620 if (conf.Get<bool>("no-dim"))
621 {
622 if (conf.Get<int>("console")==0)
623 return RunShell<LocalShell, StateMachine, ConnectionWeather>(conf);
624 else
625 return RunShell<LocalConsole, StateMachine, ConnectionWeather>(conf);
626 }
627 else
628 {
629 if (conf.Get<int>("console")==0)
630 return RunShell<LocalShell, StateMachineDim, ConnectionDimWeather>(conf);
631 else
632 return RunShell<LocalConsole, StateMachineDim, ConnectionDimWeather>(conf);
633 }
634 }
635 /*catch (std::exception& e)
636 {
637 cerr << "Exception: " << e.what() << endl;
638 return -1;
639 }*/
640
641 return 0;
642}
Note: See TracBrowser for help on using the repository browser.