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

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