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

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