source: trunk/FACT++/src/temperature.cc@ 20085

Last change on this file since 20085 was 19710, checked in by tbretz, 5 years ago
Removed some obsolete code, fixed a typo.
File size: 13.9 KB
Line 
1#if BOOST_VERSION < 104600
2#include <assert.h>
3#endif
4
5#include <boost/array.hpp>
6
7#include <boost/property_tree/ptree.hpp>
8#include <boost/property_tree/json_parser.hpp>
9
10#include <string>
11
12#include "FACT.h"
13#include "Dim.h"
14#include "Event.h"
15#include "StateMachineDim.h"
16#include "StateMachineAsio.h"
17#include "Connection.h"
18#include "LocalControl.h"
19#include "Configuration.h"
20#include "Console.h"
21
22#include "tools.h"
23
24#include "HeadersTemperature.h"
25
26namespace ba = boost::asio;
27namespace bs = boost::system;
28namespace pt = boost::property_tree;
29namespace dummy = ba::placeholders;
30
31using namespace std;
32
33class ConnectionPowerSwitch : public Connection
34{
35protected:
36 bool fIsValid;
37
38private:
39 uint16_t fInterval;
40
41 bool fIsVerbose;
42 bool fDebugRx;
43
44 string fSite;
45 string fRdfData;
46
47 boost::array<char, 4096> fArray;
48
49 string fNextCommand;
50
51 Time fLastReport;
52
53 int fStatus;
54
55 virtual void Update(const vector<float> &)
56 {
57 }
58
59
60 void ProcessAnswer()
61 {
62 if (fDebugRx)
63 {
64 Out() << "------------------------------------------------------" << endl;
65 Out() << fRdfData << endl;
66 Out() << "------------------------------------------------------" << endl;
67 }
68
69 const size_t p1 = fRdfData.find("\r\n\r\n");
70 if (p1==string::npos)
71 {
72 Warn("HTTP header not found.");
73 PostClose(false);
74 return;
75 }
76
77 fRdfData.erase(0, p1+4);
78
79 vector<float> temp(3);
80 try
81 {
82 std::stringstream ss;
83 ss << fRdfData;
84
85 pt::ptree tree;
86 pt::read_json(ss, tree);
87
88 const pt::ptree sub2 = tree.get_child("sensor_values.").begin()->second;
89 const pt::ptree sub3 = sub2.get_child("values").begin()->second.begin()->second;
90
91 temp[0] = sub3.get_child("v").get_value<float>();
92
93 auto sub = sub3.get_child("st.").begin();
94
95 temp[1] = sub++->second.get_value<float>();
96 temp[2] = sub->second.get_value<float>();
97 }
98 catch (std::exception const& e)
99 {
100 Warn("Parsing of JSON failed: "+string(e.what()));
101
102 fStatus = Temperature::State::kConnected;
103
104 PostClose(false);
105 return;
106 }
107
108 fRdfData = "";
109
110 Update(temp);
111
112 ostringstream msg;
113 msg << "T=" << temp[0] << "\u00b0C"
114 << " Tmin=" << temp[1] << "\u00b0C"
115 << " Tmax=" << temp[2] << "\u00b0C";
116 Message(msg);
117
118 fStatus = Temperature::State::kValid;
119
120 fLastReport = Time();
121 PostClose(false);
122 }
123
124 void HandleRead(const boost::system::error_code& err, size_t bytes_received)
125 {
126 // Do not schedule a new read if the connection failed.
127 if (bytes_received==0 || err)
128 {
129 if (err==ba::error::eof)
130 {
131 if (!fRdfData.empty())
132 ProcessAnswer();
133 return;
134 }
135
136 // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
137 // 125: Operation canceled
138 if (err && err!=ba::error::eof && // Connection closed by remote host
139 err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
140 err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
141 {
142 ostringstream str;
143 str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
144 Error(str);
145 }
146 PostClose(err!=ba::error::basic_errors::operation_aborted);
147
148 fRdfData = "";
149 return;
150 }
151
152 fRdfData += string(fArray.data(), bytes_received);
153
154 // Does the message contain a header?
155 const size_t p1 = fRdfData.find("\r\n\r\n");
156 if (p1!=string::npos)
157 {
158 // Does the answer also contain the body?
159 const size_t p2 = fRdfData.find("\r\n\r\n", p1+4);
160 if (p2!=string::npos)
161 ProcessAnswer();
162 }
163
164 // Go on reading until the web-server closes the connection
165 StartReadReport();
166 }
167
168 boost::asio::streambuf fBuffer;
169
170 void StartReadReport()
171 {
172 async_read_some(ba::buffer(fArray),
173 boost::bind(&ConnectionPowerSwitch::HandleRead, this,
174 dummy::error, dummy::bytes_transferred));
175 }
176
177 boost::asio::deadline_timer fKeepAlive;
178
179 void HandleRequest(const bs::error_code &error)
180 {
181 // 125: Operation canceled (bs::error_code(125, bs::system_category))
182 if (error && error!=ba::error::basic_errors::operation_aborted)
183 {
184 ostringstream str;
185 str << "Write timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
186 Error(str);
187
188 PostClose(false);
189 return;
190 }
191
192 if (!is_open())
193 {
194 // For example: Here we could schedule a new accept if we
195 // would not want to allow two connections at the same time.
196 PostClose(true);
197 return;
198 }
199
200 // Check whether the deadline has passed. We compare the deadline
201 // against the current time since a new asynchronous operation
202 // may have moved the deadline before this actor had a chance
203 // to run.
204 if (fKeepAlive.expires_at() > ba::deadline_timer::traits_type::now())
205 return;
206
207 Request();
208 }
209
210
211private:
212 // This is called when a connection was established
213 void ConnectionEstablished()
214 {
215 Request();
216 StartReadReport();
217 }
218
219public:
220 ConnectionPowerSwitch(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
221 fIsValid(false), fIsVerbose(true), fDebugRx(false), fLastReport(Time::none),
222 fStatus(Temperature::State::kDisconnected), fKeepAlive(ioservice)
223 {
224 SetLogStream(&imp);
225 }
226
227 void SetVerbose(bool b)
228 {
229 fIsVerbose = b;
230 }
231
232 void SetDebugRx(bool b)
233 {
234 fDebugRx = b;
235 Connection::SetVerbose(b);
236 }
237
238 void SetInterval(uint16_t i)
239 {
240 fInterval = i;
241 }
242
243 void SetSite(const string &site)
244 {
245 fSite = site;
246 }
247
248 void Post(const string &post)
249 {
250 fNextCommand = post;
251 }
252
253 void Request()
254 {
255 string cmd = "GET " + fSite;
256
257 if (!fNextCommand.empty())
258 cmd += "?" + fNextCommand;
259
260 cmd += " HTTP/1.1\r\n";
261 cmd += "\r\n";
262
263 PostMessage(cmd);
264
265 fNextCommand = "";
266
267 fKeepAlive.expires_from_now(boost::posix_time::seconds(fInterval));
268 fKeepAlive.async_wait(boost::bind(&ConnectionPowerSwitch::HandleRequest,
269 this, dummy::error));
270 }
271
272 int GetInterval() const
273 {
274 return fInterval;
275 }
276
277 int GetState() const
278 {
279 // Timeout
280 if (!fLastReport.IsValid() || Time()>fLastReport+boost::posix_time::seconds(fInterval*3))
281 return Temperature::State::kDisconnected;
282
283 return fStatus;
284 }
285};
286
287// ------------------------------------------------------------------------
288
289#include "DimDescriptionService.h"
290
291class ConnectionDimPowerSwitch : public ConnectionPowerSwitch
292{
293private:
294 DimDescribedService fDim;
295
296public:
297 ConnectionDimPowerSwitch(ba::io_service& ioservice, MessageImp &imp) :
298 ConnectionPowerSwitch(ioservice, imp),
299 fDim("TEMPERATURE/DATA", "F:1;F:1;F:1",
300 "Temperature readout from power switch"
301 "|T[degC]:Current temperature"
302 "|Tmin[degC]:24h minimum"
303 "|Tmax[degC]:24h maximum")
304 {
305 }
306
307 void Update(const vector<float> &temp)
308 {
309 fDim.Update(temp);
310 }
311};
312
313// ------------------------------------------------------------------------
314
315template <class T, class S>
316class StateMachinePowerControl : public StateMachineAsio<T>
317{
318private:
319 S fPower;
320 Time fLastCommand;
321
322 bool CheckEventSize(size_t has, const char *name, size_t size)
323 {
324 if (has==size)
325 return true;
326
327 ostringstream msg;
328 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
329 T::Fatal(msg);
330 return false;
331 }
332
333 int SetVerbosity(const EventImp &evt)
334 {
335 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
336 return T::kSM_FatalError;
337
338 fPower.SetVerbose(evt.GetBool());
339
340 return T::GetCurrentState();
341 }
342
343 int SetDebugRx(const EventImp &evt)
344 {
345 if (!CheckEventSize(evt.GetSize(), "SetDebugRx", 1))
346 return T::kSM_FatalError;
347
348 fPower.SetDebugRx(evt.GetBool());
349
350 return T::GetCurrentState();
351 }
352
353 int Execute()
354 {
355 return fPower.GetState();
356 }
357
358
359public:
360 StateMachinePowerControl(ostream &out=cout) :
361 StateMachineAsio<T>(out, "TEMPERATURE"), fPower(*this, *this)
362 {
363 // State names
364 T::AddStateName(Temperature::State::kDisconnected, "NoConnection",
365 "No connection to web-server could be established recently");
366
367 T::AddStateName(Temperature::State::kConnected, "Connected",
368 "Connection established, but no valid data received");
369
370 T::AddStateName(Temperature::State::kValid, "Valid",
371 "Connection established, received data valid");
372
373 // Verbosity commands
374 T::AddEvent("SET_VERBOSE", "B:1")
375 (bind(&StateMachinePowerControl::SetVerbosity, this, placeholders::_1))
376 ("Set verbosity state"
377 "|verbosity[bool]:disable or enable verbosity for interpreted data (yes/no)");
378
379 T::AddEvent("SET_DEBUG_RX", "B:1")
380 (bind(&StateMachinePowerControl::SetDebugRx, this, placeholders::_1))
381 ("Set debux-rx state"
382 "|debug[bool]:dump received text and parsed text to console (yes/no)");
383
384 }
385
386 int EvalOptions(Configuration &conf)
387 {
388 fPower.SetVerbose(!conf.Get<bool>("quiet"));
389 fPower.SetInterval(conf.Get<uint16_t>("interval"));
390 fPower.SetDebugTx(conf.Get<bool>("debug-tx"));
391 fPower.SetDebugRx(conf.Get<bool>("debug-rx"));
392 fPower.SetSite(conf.Get<string>("url"));
393 fPower.SetEndpoint(conf.Get<string>("addr"));
394 fPower.StartConnect();
395
396 return -1;
397 }
398};
399
400// ------------------------------------------------------------------------
401
402#include "Main.h"
403
404
405template<class T, class S, class R>
406int RunShell(Configuration &conf)
407{
408 return Main::execute<T, StateMachinePowerControl<S, R>>(conf);
409}
410
411void SetupConfiguration(Configuration &conf)
412{
413 po::options_description control("Lid control");
414 control.add_options()
415 ("no-dim,d", po_switch(), "Disable dim services")
416 ("addr,a", var<string>("10.0.100.234:80"), "Network address of the lid controling Arduino including port")
417 ("url,u", var<string>("/statusjsn.js?components=18179&_=1365876572736"), "File name and path to load")
418 ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
419 ("interval,i", var<uint16_t>(60), "Interval between two updates on the server in seconds")
420 ("debug-tx", po_bool(), "Enable debugging of ethernet transmission.")
421 ("debug-rx", po_bool(), "Enable debugging for received data.")
422 ;
423
424 conf.AddOptions(control);
425}
426
427/*
428 Extract usage clause(s) [if any] for SYNOPSIS.
429 Translators: "Usage" and "or" here are patterns (regular expressions) which
430 are used to match the usage synopsis in program output. An example from cp
431 (GNU coreutils) which contains both strings:
432 Usage: cp [OPTION]... [-T] SOURCE DEST
433 or: cp [OPTION]... SOURCE... DIRECTORY
434 or: cp [OPTION]... -t DIRECTORY SOURCE...
435 */
436void PrintUsage()
437{
438 cout <<
439 "The temperature is an interface to readout the temperature from the power switch.\n"
440 "\n"
441 "The default is that the program is started without user intercation. "
442 "All actions are supposed to arrive as DimCommands. Using the -c "
443 "option, a local shell can be initialized. With h or help a short "
444 "help message about the usuage can be brought to the screen.\n"
445 "\n"
446 "Usage: temperature [-c type] [OPTIONS]\n"
447 " or: temperature [OPTIONS]\n";
448 cout << endl;
449}
450
451void PrintHelp()
452{
453// Main::PrintHelp<StateMachineFTM<StateMachine, ConnectionFTM>>();
454
455 /* Additional help text which is printed after the configuration
456 options goes here */
457
458 /*
459 cout << "bla bla bla" << endl << endl;
460 cout << endl;
461 cout << "Environment:" << endl;
462 cout << "environment" << endl;
463 cout << endl;
464 cout << "Examples:" << endl;
465 cout << "test exam" << endl;
466 cout << endl;
467 cout << "Files:" << endl;
468 cout << "files" << endl;
469 cout << endl;
470 */
471}
472
473int main(int argc, const char* argv[])
474{
475 Configuration conf(argv[0]);
476 conf.SetPrintUsage(PrintUsage);
477 Main::SetupConfiguration(conf);
478 SetupConfiguration(conf);
479
480 if (!conf.DoParse(argc, argv, PrintHelp))
481 return 127;
482
483 // No console access at all
484 if (!conf.Has("console"))
485 {
486 if (conf.Get<bool>("no-dim"))
487 return RunShell<LocalStream, StateMachine, ConnectionPowerSwitch>(conf);
488 else
489 return RunShell<LocalStream, StateMachineDim, ConnectionDimPowerSwitch>(conf);
490 }
491 // Cosole access w/ and w/o Dim
492 if (conf.Get<bool>("no-dim"))
493 {
494 if (conf.Get<int>("console")==0)
495 return RunShell<LocalShell, StateMachine, ConnectionPowerSwitch>(conf);
496 else
497 return RunShell<LocalConsole, StateMachine, ConnectionPowerSwitch>(conf);
498 }
499 else
500 {
501 if (conf.Get<int>("console")==0)
502 return RunShell<LocalShell, StateMachineDim, ConnectionDimPowerSwitch>(conf);
503 else
504 return RunShell<LocalConsole, StateMachineDim, ConnectionDimPowerSwitch>(conf);
505 }
506
507 return 0;
508}
Note: See TracBrowser for help on using the repository browser.