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

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