source: trunk/FACT++/src/magicweather.cc@ 14098

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