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

Last change on this file since 14177 was 14009, checked in by tbretz, 13 years ago
Exit with 127 if parsing of command line options failed.
File size: 19.3 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 "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 time.SetFromStr(obj, "%Y-%m-%dT%H:%M:%S");
177
178 /*
179 Out() << "S: " << (*it).subject().toString().toStdString() << endl;
180 Out() << "P: " << (*it).predicate().toString().toStdString() << endl;
181 Out() << "O: " << (*it).object().toString().toStdString() << endl;
182 Out() << "C: " << (*it).context().toString().toStdString() << endl;
183 */
184 }
185
186 if (!time.IsValid())
187 throw runtime_error("time invalid");
188
189 if (time!=fLastReport && fIsVerbose)
190 {
191 Out() << endl;
192 Out() << "Date: " << time << endl;
193 Out() << "Seeing: " << w.fSeeing << endl;
194 Out() << "DustTotal: " << w.fDustTotal << endl;
195 Out() << "DeltaM1: " << w.fDeltaM1 << endl;
196 Out() << "AirPressure: " << w.fAirPressure << endl;
197 Out() << "DewPoint: " << w.fDewPoint << endl;
198 Out() << "WindDirection: " << w.fWindDirection << endl;
199 Out() << "WindSpeed: " << w.fWindSpeed << endl;
200 Out() << "Humidity: " << w.fHumidity << endl;
201 Out() << "TempGround: " << w.fTempGround << endl;
202 Out() << "Temp2M: " << w.fTemp2M << endl;
203 Out() << "Temp5M: " << w.fTemp5M << endl;
204 Out() << "Temp10M: " << w.fTemp10M << endl;
205 Out() << endl;
206 }
207
208 fLastReport = time;
209
210 UpdateWeather(time, w);
211
212 if (fDust==w.fDustTotal)
213 return;
214
215 UpdateDust(time, w.fDustTotal);
216 fDust = w.fDustTotal;
217
218 ostringstream out;
219 out << setprecision(3) << "Dust: " << fDust << "ug/m^3 [" << time << "]";
220 Message(out);
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), fDust(-1),
314 fLastReport(Time::none), fLastReception(Time::none),
315 fKeepAlive(ioservice)
316 {
317 SetLogStream(&imp);
318 }
319
320 void SetVerbose(bool b)
321 {
322 fIsVerbose = b;
323 Connection::SetVerbose(b);
324 }
325
326 void SetInterval(uint16_t i)
327 {
328 fInterval = i;
329 }
330
331 void SetSite(const string &site)
332 {
333 fSite = site;
334 }
335
336 int GetState() const
337 {
338 if (fLastReport.IsValid() && fLastReport+boost::posix_time::seconds(fInterval*2)>Time())
339 return 3;
340
341 if (fLastReception.IsValid() && fLastReception+boost::posix_time::seconds(fInterval*2)>Time())
342 return 2;
343
344 return 1;
345 }
346};
347
348const uint16_t ConnectionWeather::kMaxAddr = 0xfff;
349
350// ------------------------------------------------------------------------
351
352#include "DimDescriptionService.h"
353
354class ConnectionDimWeather : public ConnectionWeather
355{
356private:
357 DimDescribedService fDimWeather;
358 DimDescribedService fDimAtmosphere;
359
360 virtual void UpdateWeather(const Time &t, const DimWeather &data)
361 {
362 fDimWeather.setData(&data, sizeof(DimWeather));
363 fDimWeather.Update(t);
364 }
365
366 virtual void UpdateDust(const Time &t, const float &dust)
367 {
368 fDimAtmosphere.setData(&dust, sizeof(float));
369 fDimAtmosphere.Update(t);
370 }
371
372public:
373 ConnectionDimWeather(ba::io_service& ioservice, MessageImp &imp) :
374 ConnectionWeather(ioservice, imp),
375 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",
376 "|T_10M[deg C]:Temperature 10m above ground"
377 "|T_5M[deg C]:Temperature 5m above ground"
378 "|T_2M[deg C]:Temperature 2m above ground"
379 "|T_0[deg C]:Temperature at ground"
380 "|T_dew[deg C]:Dew point"
381 "|H[%]:Humidity"
382 "|P[mbar]:Air pressure"
383 "|v[km/h]:Wind speed"
384 "|d[deg]:Wind direction (N-E)"
385 "|DeltaM1"
386 "|Dust[ug/m^3]:Dust (total)"
387 "|Seeing[W/m^2]:Seeing"),
388 fDimAtmosphere("TNG_WEATHER/DUST", "F:1",
389 "|Dust[ug/m^3]:Dust (total)")
390 {
391 }
392};
393
394// ------------------------------------------------------------------------
395
396template <class T, class S>
397class StateMachineWeather : public T, public ba::io_service, public ba::io_service::work
398{
399private:
400 S fWeather;
401
402 bool CheckEventSize(size_t has, const char *name, size_t size)
403 {
404 if (has==size)
405 return true;
406
407 ostringstream msg;
408 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
409 T::Fatal(msg);
410 return false;
411 }
412
413 int SetVerbosity(const EventImp &evt)
414 {
415 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
416 return T::kSM_FatalError;
417
418 fWeather.SetVerbose(evt.GetBool());
419
420 return T::GetCurrentState();
421 }
422/*
423 int Disconnect()
424 {
425 // Close all connections
426 fWeather.PostClose(false);
427
428 return T::GetCurrentState();
429 }
430
431 int Reconnect(const EventImp &evt)
432 {
433 // Close all connections to supress the warning in SetEndpoint
434 fWeather.PostClose(false);
435
436 // Now wait until all connection have been closed and
437 // all pending handlers have been processed
438 poll();
439
440 if (evt.GetBool())
441 fWeather.SetEndpoint(evt.GetString());
442
443 // Now we can reopen the connection
444 fWeather.PostClose(true);
445
446 return T::GetCurrentState();
447 }
448*/
449 int Execute()
450 {
451 // Dispatch (execute) at most one handler from the queue. In contrary
452 // to run_one(), it doesn't wait until a handler is available
453 // which can be dispatched, so poll_one() might return with 0
454 // handlers dispatched. The handlers are always dispatched/executed
455 // synchronously, i.e. within the call to poll_one()
456 poll_one();
457
458 return fWeather.GetState();
459 }
460
461
462public:
463 StateMachineWeather(ostream &out=cout) :
464 T(out, "TNG_WEATHER"), ba::io_service::work(static_cast<ba::io_service&>(*this)),
465 fWeather(*this, *this)
466 {
467 // ba::io_service::work is a kind of keep_alive for the loop.
468 // It prevents the io_service to go to stopped state, which
469 // would prevent any consecutive calls to run()
470 // or poll() to do nothing. reset() could also revoke to the
471 // previous state but this might introduce some overhead of
472 // deletion and creation of threads and more.
473
474 // State names
475 T::AddStateName(State::kDisconnected, "NoConnection",
476 "No connection to web-server could be established recently");
477
478 T::AddStateName(State::kConnected, "Invalid",
479 "Connection to webserver can be established, but received data is not recent or invalid");
480
481 T::AddStateName(State::kReceiving, "Valid",
482 "Connection to webserver can be established, receint data received");
483
484 // Verbosity commands
485 T::AddEvent("SET_VERBOSE", "B")
486 (bind(&StateMachineWeather::SetVerbosity, this, placeholders::_1))
487 ("set verbosity state"
488 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
489/*
490 // Conenction commands
491 AddEvent("DISCONNECT")
492 (bind(&StateMachineWeather::Disconnect, this))
493 ("disconnect from ethernet");
494
495 AddEvent("RECONNECT", "O")
496 (bind(&StateMachineWeather::Reconnect, this, placeholders::_1))
497 ("(Re)connect ethernet connection to FTM, a new address can be given"
498 "|[host][string]:new ethernet address in the form <host:port>");
499*/
500 }
501
502 int EvalOptions(Configuration &conf)
503 {
504 fWeather.SetVerbose(!conf.Get<bool>("quiet"));
505 fWeather.SetInterval(conf.Get<uint16_t>("interval"));
506 fWeather.SetDebugTx(conf.Get<bool>("debug-tx"));
507 fWeather.SetSite(conf.Get<string>("url"));
508 fWeather.SetEndpoint(conf.Get<string>("addr"));
509 fWeather.StartConnect();
510
511 return -1;
512 }
513};
514
515// ------------------------------------------------------------------------
516
517#include "Main.h"
518
519
520template<class T, class S, class R>
521int RunShell(Configuration &conf)
522{
523 return Main::execute<T, StateMachineWeather<S, R>>(conf);
524}
525
526void SetupConfiguration(Configuration &conf)
527{
528 po::options_description control("TNG weather control options");
529 control.add_options()
530 ("no-dim,d", po_switch(), "Disable dim services")
531 ("addr,a", var<string>("tngweb.tng.iac.es:80"), "Network address of Cosy")
532 ("url,u", var<string>("/weather/rss/"), "File name and path to load")
533 ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
534 ("interval,i", var<uint16_t>(300), "Interval between two updates on the server in seconds")
535 ("debug-tx", po_bool(), "Enable debugging of ethernet transmission.")
536 ;
537
538 conf.AddOptions(control);
539}
540
541/*
542 Extract usage clause(s) [if any] for SYNOPSIS.
543 Translators: "Usage" and "or" here are patterns (regular expressions) which
544 are used to match the usage synopsis in program output. An example from cp
545 (GNU coreutils) which contains both strings:
546 Usage: cp [OPTION]... [-T] SOURCE DEST
547 or: cp [OPTION]... SOURCE... DIRECTORY
548 or: cp [OPTION]... -t DIRECTORY SOURCE...
549 */
550void PrintUsage()
551{
552 cout <<
553 "The tngweather is an interface to the TNG weather data.\n"
554 "\n"
555 "The default is that the program is started without user intercation. "
556 "All actions are supposed to arrive as DimCommands. Using the -c "
557 "option, a local shell can be initialized. With h or help a short "
558 "help message about the usuage can be brought to the screen.\n"
559 "\n"
560 "Usage: tngweather [-c type] [OPTIONS]\n"
561 " or: tngweather [OPTIONS]\n";
562 cout << endl;
563}
564
565void PrintHelp()
566{
567// Main::PrintHelp<StateMachineFTM<StateMachine, ConnectionFTM>>();
568
569 /* Additional help text which is printed after the configuration
570 options goes here */
571
572 /*
573 cout << "bla bla bla" << endl << endl;
574 cout << endl;
575 cout << "Environment:" << endl;
576 cout << "environment" << endl;
577 cout << endl;
578 cout << "Examples:" << endl;
579 cout << "test exam" << endl;
580 cout << endl;
581 cout << "Files:" << endl;
582 cout << "files" << endl;
583 cout << endl;
584 */
585}
586
587int main(int argc, const char* argv[])
588{
589 Configuration conf(argv[0]);
590 conf.SetPrintUsage(PrintUsage);
591 Main::SetupConfiguration(conf);
592 SetupConfiguration(conf);
593
594 if (!conf.DoParse(argc, argv, PrintHelp))
595 return 127;
596
597 //try
598 {
599 // No console access at all
600 if (!conf.Has("console"))
601 {
602 if (conf.Get<bool>("no-dim"))
603 return RunShell<LocalStream, StateMachine, ConnectionWeather>(conf);
604 else
605 return RunShell<LocalStream, StateMachineDim, ConnectionDimWeather>(conf);
606 }
607 // Cosole access w/ and w/o Dim
608 if (conf.Get<bool>("no-dim"))
609 {
610 if (conf.Get<int>("console")==0)
611 return RunShell<LocalShell, StateMachine, ConnectionWeather>(conf);
612 else
613 return RunShell<LocalConsole, StateMachine, ConnectionWeather>(conf);
614 }
615 else
616 {
617 if (conf.Get<int>("console")==0)
618 return RunShell<LocalShell, StateMachineDim, ConnectionDimWeather>(conf);
619 else
620 return RunShell<LocalConsole, StateMachineDim, ConnectionDimWeather>(conf);
621 }
622 }
623 /*catch (std::exception& e)
624 {
625 cerr << "Exception: " << e.what() << endl;
626 return -1;
627 }*/
628
629 return 0;
630}
Note: See TracBrowser for help on using the repository browser.