1 | #include <boost/array.hpp>
|
---|
2 | #include <boost/property_tree/ptree.hpp>
|
---|
3 | #include <boost/property_tree/json_parser.hpp>
|
---|
4 |
|
---|
5 | #include <string> // std::string
|
---|
6 | #include <algorithm> // std::transform
|
---|
7 | #include <cctype> // std::tolower
|
---|
8 |
|
---|
9 | #include "FACT.h"
|
---|
10 | #include "Dim.h"
|
---|
11 | #include "Event.h"
|
---|
12 | #include "Shell.h"
|
---|
13 | #include "StateMachineDim.h"
|
---|
14 | #include "StateMachineAsio.h"
|
---|
15 | #include "Connection.h"
|
---|
16 | #include "LocalControl.h"
|
---|
17 | #include "Configuration.h"
|
---|
18 | #include "Console.h"
|
---|
19 |
|
---|
20 | #include "tools.h"
|
---|
21 |
|
---|
22 | #include "HeadersBiasTemp.h"
|
---|
23 |
|
---|
24 | namespace ba = boost::asio;
|
---|
25 | namespace bs = boost::system;
|
---|
26 | namespace pt = boost::property_tree;
|
---|
27 | namespace dummy = ba::placeholders;
|
---|
28 |
|
---|
29 | using namespace std;
|
---|
30 | using namespace BiasTemp;
|
---|
31 |
|
---|
32 | // ------------------------------------------------------------------------
|
---|
33 |
|
---|
34 | class ConnectionBiasTemp : public Connection
|
---|
35 | {
|
---|
36 | uint16_t fInterval;
|
---|
37 |
|
---|
38 | bool fIsVerbose;
|
---|
39 |
|
---|
40 | string fSite;
|
---|
41 |
|
---|
42 | protected:
|
---|
43 |
|
---|
44 | Time fLastReport;
|
---|
45 | Time fLastReception;
|
---|
46 |
|
---|
47 | boost::asio::streambuf fBuffer;
|
---|
48 | string fData;
|
---|
49 |
|
---|
50 | struct DimData
|
---|
51 | {
|
---|
52 | uint64_t time;
|
---|
53 | float temp[10];
|
---|
54 | double avg;
|
---|
55 | double rms;
|
---|
56 | } __attribute__((__packed__));
|
---|
57 |
|
---|
58 | virtual void UpdateBiasTemp(const DimData &)
|
---|
59 | {
|
---|
60 | }
|
---|
61 |
|
---|
62 | void ProcessAnswer(string s)
|
---|
63 | {
|
---|
64 | try
|
---|
65 | {
|
---|
66 | std::stringstream ss;
|
---|
67 | ss << s;
|
---|
68 |
|
---|
69 | pt::ptree tree;
|
---|
70 | pt::read_json(ss, tree);
|
---|
71 |
|
---|
72 | DimData data;
|
---|
73 | data.time = tree.get_child("timestamp").get_value<uint64_t>();
|
---|
74 |
|
---|
75 | const auto &branch = tree.get_child("temperatures_deg_C");
|
---|
76 |
|
---|
77 | // FIXME: Move to config file?
|
---|
78 | static const string id[10] =
|
---|
79 | {
|
---|
80 | "10 e5 54 2d 03 08 00 cc", // between master and BIAS_0
|
---|
81 | "10 ca 24 2e 03 08 00 bb", // between BIAS_0 and BIAS_1
|
---|
82 | "10 9f 51 2d 03 08 00 49", // between BIAS_1 and BIAS_2
|
---|
83 | "10 b7 6d 2d 03 08 00 fb", // between BIAS_3 and BIAS_4
|
---|
84 | "10 a5 f0 2d 03 08 00 95", // between BIAS_4 and BIAS_5
|
---|
85 | "10 16 75 2d 03 08 00 d2", // between BIAS_5 and BIAS_6
|
---|
86 | "10 50 77 2d 03 08 00 96", // between BIAS_7 and "SPARE"
|
---|
87 | "10 9f 02 2e 03 08 00 1a", // between "SPARE" and BIAS_9
|
---|
88 | "10 1d ce 2d 03 08 00 15", // right of BIAS_9
|
---|
89 | "10 cc f3 2d 03 08 00 8e", // far to the right, where no heat should be generated
|
---|
90 | };
|
---|
91 |
|
---|
92 | data.avg = 0;
|
---|
93 | data.rms = 0;
|
---|
94 |
|
---|
95 | for (int i=0; i<10; i++)
|
---|
96 | {
|
---|
97 | data.temp[i] = branch.get_child(id[i]).get_value<float>();
|
---|
98 | data.avg += data.temp[i];
|
---|
99 | data.rms += data.temp[i]*data.temp[i];
|
---|
100 | }
|
---|
101 |
|
---|
102 | data.avg /= 10;
|
---|
103 | data.rms /= 10;
|
---|
104 |
|
---|
105 | data.rms = sqrt(data.rms - data.avg*data.avg);
|
---|
106 |
|
---|
107 | ostringstream out;
|
---|
108 | out << Tools::Form("T=%09d:", data.time);
|
---|
109 | for (int i=0; i<10; i++)
|
---|
110 | out << Tools::Form("%5.1f", data.temp[i]);
|
---|
111 |
|
---|
112 | out << Tools::Form(" |%5.1f +-%4.1f", data.avg, data.rms);
|
---|
113 |
|
---|
114 | Info(out);
|
---|
115 |
|
---|
116 | UpdateBiasTemp(data);
|
---|
117 |
|
---|
118 | fLastReport = Time();
|
---|
119 | }
|
---|
120 | catch (std::exception const& e)
|
---|
121 | {
|
---|
122 | Error(string("Parsing JSON failed: ")+e.what());
|
---|
123 | }
|
---|
124 | }
|
---|
125 |
|
---|
126 | void HandleRead(const boost::system::error_code& err, size_t bytes_received)
|
---|
127 | {
|
---|
128 | // Do not schedule a new read if the connection failed.
|
---|
129 | if (bytes_received==0 || err)
|
---|
130 | {
|
---|
131 | if (err==ba::error::eof)
|
---|
132 | {
|
---|
133 | // Does the message contain a header?
|
---|
134 | const size_t p1 = fData.find("\r\n\r\n");
|
---|
135 | if (p1!=string::npos)
|
---|
136 | ProcessAnswer(fData.substr(p1));
|
---|
137 | else
|
---|
138 | Warn("Receives message lacks a header!");
|
---|
139 | fData = "";
|
---|
140 |
|
---|
141 | PostClose(false);
|
---|
142 |
|
---|
143 | return;
|
---|
144 | }
|
---|
145 |
|
---|
146 | // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
|
---|
147 | // 125: Operation canceled
|
---|
148 | if (err && err!=ba::error::eof && // Connection closed by remote host
|
---|
149 | err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
|
---|
150 | err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
|
---|
151 | {
|
---|
152 | ostringstream str;
|
---|
153 | str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
|
---|
154 | Error(str);
|
---|
155 | }
|
---|
156 | PostClose(err!=ba::error::basic_errors::operation_aborted);
|
---|
157 | return;
|
---|
158 | }
|
---|
159 |
|
---|
160 | fLastReception = Time();
|
---|
161 |
|
---|
162 | istream is(&fBuffer);
|
---|
163 |
|
---|
164 | string buffer;
|
---|
165 | if (!getline(is, buffer, '\n'))
|
---|
166 | {
|
---|
167 | Fatal("Received message does not contain \\n... closing connection.");
|
---|
168 | PostClose(false);
|
---|
169 | return;
|
---|
170 | }
|
---|
171 |
|
---|
172 | if (fIsVerbose)
|
---|
173 | Out() << buffer << endl;
|
---|
174 |
|
---|
175 | fData += buffer;
|
---|
176 | fData += '\n';
|
---|
177 |
|
---|
178 | StartReadLine();
|
---|
179 | }
|
---|
180 |
|
---|
181 | void StartReadLine()
|
---|
182 | {
|
---|
183 | async_read_until(*this, fBuffer, '\n',
|
---|
184 | boost::bind(&ConnectionBiasTemp::HandleRead, this,
|
---|
185 | dummy::error, dummy::bytes_transferred));
|
---|
186 | }
|
---|
187 |
|
---|
188 | ba::deadline_timer fKeepAlive;
|
---|
189 |
|
---|
190 | void PostRequest()
|
---|
191 | {
|
---|
192 | const string cmd =
|
---|
193 | "GET "+fSite+" HTTP/1.1\r\n"
|
---|
194 | "\r\n";
|
---|
195 |
|
---|
196 | PostMessage(cmd);
|
---|
197 | }
|
---|
198 |
|
---|
199 | void Request()
|
---|
200 | {
|
---|
201 | PostRequest();
|
---|
202 |
|
---|
203 | fKeepAlive.expires_from_now(boost::posix_time::seconds(fInterval/2));
|
---|
204 | fKeepAlive.async_wait(boost::bind(&ConnectionBiasTemp::HandleRequest,
|
---|
205 | this, dummy::error));
|
---|
206 | }
|
---|
207 |
|
---|
208 | void HandleRequest(const bs::error_code &error)
|
---|
209 | {
|
---|
210 | // 125: Operation canceled (bs::error_code(125, bs::system_category))
|
---|
211 | if (error && error!=ba::error::basic_errors::operation_aborted)
|
---|
212 | {
|
---|
213 | ostringstream str;
|
---|
214 | str << "Write timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
|
---|
215 | Error(str);
|
---|
216 |
|
---|
217 | PostClose(false);
|
---|
218 | return;
|
---|
219 | }
|
---|
220 |
|
---|
221 | if (!is_open())
|
---|
222 | {
|
---|
223 | // For example: Here we could schedule a new accept if we
|
---|
224 | // would not want to allow two connections at the same time.
|
---|
225 | PostClose(true);
|
---|
226 | return;
|
---|
227 | }
|
---|
228 |
|
---|
229 | // Check whether the deadline has passed. We compare the deadline
|
---|
230 | // against the current time since a new asynchronous operation
|
---|
231 | // may have moved the deadline before this actor had a chance
|
---|
232 | // to run.
|
---|
233 | if (fKeepAlive.expires_at() > ba::deadline_timer::traits_type::now())
|
---|
234 | return;
|
---|
235 |
|
---|
236 | Request();
|
---|
237 | }
|
---|
238 |
|
---|
239 |
|
---|
240 | private:
|
---|
241 | // This is called when a connection was established
|
---|
242 | void ConnectionEstablished()
|
---|
243 | {
|
---|
244 | Request();
|
---|
245 | StartReadLine();
|
---|
246 | }
|
---|
247 |
|
---|
248 | public:
|
---|
249 |
|
---|
250 | static const uint16_t kMaxAddr;
|
---|
251 |
|
---|
252 | public:
|
---|
253 | ConnectionBiasTemp(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
|
---|
254 | fIsVerbose(true), fLastReport(Time::none), fLastReception(Time::none), fKeepAlive(ioservice)
|
---|
255 | {
|
---|
256 | SetLogStream(&imp);
|
---|
257 | }
|
---|
258 |
|
---|
259 | void SetVerbose(bool b)
|
---|
260 | {
|
---|
261 | fIsVerbose = b;
|
---|
262 | Connection::SetVerbose(b);
|
---|
263 | }
|
---|
264 |
|
---|
265 | void SetInterval(uint16_t i)
|
---|
266 | {
|
---|
267 | fInterval = i;
|
---|
268 | }
|
---|
269 |
|
---|
270 | void SetSite(const string &site)
|
---|
271 | {
|
---|
272 | fSite = site;
|
---|
273 | }
|
---|
274 |
|
---|
275 | int GetState() const
|
---|
276 | {
|
---|
277 | if (fLastReport.IsValid() && fLastReport+boost::posix_time::seconds(fInterval*2)>Time())
|
---|
278 | return 3;
|
---|
279 |
|
---|
280 | if (fLastReception.IsValid() && fLastReception+boost::posix_time::seconds(fInterval*2)>Time())
|
---|
281 | return 2;
|
---|
282 |
|
---|
283 | return 1;
|
---|
284 |
|
---|
285 | }
|
---|
286 | };
|
---|
287 |
|
---|
288 | const uint16_t ConnectionBiasTemp::kMaxAddr = 0xfff;
|
---|
289 |
|
---|
290 | // ------------------------------------------------------------------------
|
---|
291 |
|
---|
292 | #include "DimDescriptionService.h"
|
---|
293 |
|
---|
294 | class ConnectionDimBiasTemp : public ConnectionBiasTemp
|
---|
295 | {
|
---|
296 | private:
|
---|
297 |
|
---|
298 | DimDescribedService fDimBiasTemp;
|
---|
299 |
|
---|
300 | virtual void UpdateBiasTemp(const DimData &data)
|
---|
301 | {
|
---|
302 | fDimBiasTemp.setData(&data, sizeof(DimData));
|
---|
303 | fDimBiasTemp.Update();
|
---|
304 | }
|
---|
305 |
|
---|
306 | public:
|
---|
307 | ConnectionDimBiasTemp(ba::io_service& ioservice, MessageImp &imp) :
|
---|
308 | ConnectionBiasTemp(ioservice, imp),
|
---|
309 | fDimBiasTemp("BIAS_TEMP/DATA", "X:1;F:10;D:1;D:1",
|
---|
310 | "|time[s]:Seconds since device start"
|
---|
311 | "|T[degC]:Temperature"
|
---|
312 | "|Tavg[degC]:Average temperature"
|
---|
313 | "|Trms[degC]:RMS of temperatures")
|
---|
314 | {
|
---|
315 | }
|
---|
316 | };
|
---|
317 |
|
---|
318 | // ------------------------------------------------------------------------
|
---|
319 |
|
---|
320 | template <class T, class S>
|
---|
321 | class StateMachineBiasTemp : public StateMachineAsio<T>
|
---|
322 | {
|
---|
323 | private:
|
---|
324 | S fBiasTemp;
|
---|
325 |
|
---|
326 | bool CheckEventSize(size_t has, const char *name, size_t size)
|
---|
327 | {
|
---|
328 | if (has==size)
|
---|
329 | return true;
|
---|
330 |
|
---|
331 | ostringstream msg;
|
---|
332 | msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
|
---|
333 | T::Fatal(msg);
|
---|
334 | return false;
|
---|
335 | }
|
---|
336 |
|
---|
337 | int SetVerbosity(const EventImp &evt)
|
---|
338 | {
|
---|
339 | if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
|
---|
340 | return T::kSM_FatalError;
|
---|
341 |
|
---|
342 | fBiasTemp.SetVerbose(evt.GetBool());
|
---|
343 |
|
---|
344 | return T::GetCurrentState();
|
---|
345 | }
|
---|
346 | /*
|
---|
347 | int Disconnect()
|
---|
348 | {
|
---|
349 | // Close all connections
|
---|
350 | fBiasTemp.PostClose(false);
|
---|
351 |
|
---|
352 | return T::GetCurrentState();
|
---|
353 | }
|
---|
354 |
|
---|
355 | int Reconnect(const EventImp &evt)
|
---|
356 | {
|
---|
357 | // Close all connections to supress the warning in SetEndpoint
|
---|
358 | fBiasTemp.PostClose(false);
|
---|
359 |
|
---|
360 | // Now wait until all connection have been closed and
|
---|
361 | // all pending handlers have been processed
|
---|
362 | ba::io_service::poll();
|
---|
363 |
|
---|
364 | if (evt.GetBool())
|
---|
365 | fBiasTemp.SetEndpoint(evt.GetString());
|
---|
366 |
|
---|
367 | // Now we can reopen the connection
|
---|
368 | fBiasTemp.PostClose(true);
|
---|
369 |
|
---|
370 | return T::GetCurrentState();
|
---|
371 | }
|
---|
372 | */
|
---|
373 | int Execute()
|
---|
374 | {
|
---|
375 | return fBiasTemp.GetState();
|
---|
376 | }
|
---|
377 |
|
---|
378 | public:
|
---|
379 | StateMachineBiasTemp(ostream &out=cout) :
|
---|
380 | StateMachineAsio<T>(out, "BIAS_TEMP"), fBiasTemp(*this, *this)
|
---|
381 | {
|
---|
382 | // State names
|
---|
383 | T::AddStateName(State::kDisconnected, "NoConnection",
|
---|
384 | "No connection to web-server could be established recently");
|
---|
385 |
|
---|
386 | T::AddStateName(State::kConnected, "Invalid",
|
---|
387 | "Connection to webserver can be established, but received data is not recent or invalid");
|
---|
388 |
|
---|
389 | T::AddStateName(State::kReceiving, "Valid",
|
---|
390 | "Connection to webserver can be established, receint data received");
|
---|
391 |
|
---|
392 | // Verbosity commands
|
---|
393 | T::AddEvent("SET_VERBOSE", "B")
|
---|
394 | (bind(&StateMachineBiasTemp::SetVerbosity, this, placeholders::_1))
|
---|
395 | ("set verbosity state"
|
---|
396 | "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
|
---|
397 | /*
|
---|
398 | // Conenction commands
|
---|
399 | AddEvent("DISCONNECT")
|
---|
400 | (bind(&StateMachineBiasTemp::Disconnect, this))
|
---|
401 | ("disconnect from ethernet");
|
---|
402 |
|
---|
403 | AddEvent("RECONNECT", "O")
|
---|
404 | (bind(&StateMachineBiasTemp::Reconnect, this, placeholders::_1))
|
---|
405 | ("(Re)connect ethernet connection to FTM, a new address can be given"
|
---|
406 | "|[host][string]:new ethernet address in the form <host:port>");
|
---|
407 | */
|
---|
408 | }
|
---|
409 |
|
---|
410 | int EvalOptions(Configuration &conf)
|
---|
411 | {
|
---|
412 | fBiasTemp.SetVerbose(!conf.Get<bool>("quiet"));
|
---|
413 | fBiasTemp.SetInterval(conf.Get<uint16_t>("interval"));
|
---|
414 | fBiasTemp.SetDebugTx(conf.Get<bool>("debug-tx"));
|
---|
415 | fBiasTemp.SetSite(conf.Get<string>("url"));
|
---|
416 | fBiasTemp.SetEndpoint(conf.Get<string>("addr"));
|
---|
417 | fBiasTemp.StartConnect();
|
---|
418 |
|
---|
419 | return -1;
|
---|
420 | }
|
---|
421 | };
|
---|
422 |
|
---|
423 |
|
---|
424 |
|
---|
425 | // ------------------------------------------------------------------------
|
---|
426 |
|
---|
427 | #include "Main.h"
|
---|
428 |
|
---|
429 |
|
---|
430 | template<class T, class S, class R>
|
---|
431 | int RunShell(Configuration &conf)
|
---|
432 | {
|
---|
433 | return Main::execute<T, StateMachineBiasTemp<S, R>>(conf);
|
---|
434 | }
|
---|
435 |
|
---|
436 | void SetupConfiguration(Configuration &conf)
|
---|
437 | {
|
---|
438 | po::options_description control("Bias Crate temperature readout");
|
---|
439 | control.add_options()
|
---|
440 | ("no-dim,d", po_switch(), "Disable dim services")
|
---|
441 | ("addr,a", var<string>("10.0.100.101:80"), "Network address of the hardware")
|
---|
442 | ("url,u", var<string>("/index.html"), "File name and path to load")
|
---|
443 | ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
|
---|
444 | ("interval,i", var<uint16_t>(15), "Interval between two updates on the server in seconds")
|
---|
445 | ("debug-tx", po_bool(), "Enable debugging of ethernet transmission.")
|
---|
446 | ;
|
---|
447 |
|
---|
448 | conf.AddOptions(control);
|
---|
449 | }
|
---|
450 |
|
---|
451 | /*
|
---|
452 | Extract usage clause(s) [if any] for SYNOPSIS.
|
---|
453 | Translators: "Usage" and "or" here are patterns (regular expressions) which
|
---|
454 | are used to match the usage synopsis in program output. An example from cp
|
---|
455 | (GNU coreutils) which contains both strings:
|
---|
456 | Usage: cp [OPTION]... [-T] SOURCE DEST
|
---|
457 | or: cp [OPTION]... SOURCE... DIRECTORY
|
---|
458 | or: cp [OPTION]... -t DIRECTORY SOURCE...
|
---|
459 | */
|
---|
460 | void PrintUsage()
|
---|
461 | {
|
---|
462 | cout <<
|
---|
463 | "The biastemp is an interface to the temperature sensors in the bias crate.\n"
|
---|
464 | "\n"
|
---|
465 | "The default is that the program is started without user intercation. "
|
---|
466 | "All actions are supposed to arrive as DimCommands. Using the -c "
|
---|
467 | "option, a local shell can be initialized. With h or help a short "
|
---|
468 | "help message about the usuage can be brought to the screen.\n"
|
---|
469 | "\n"
|
---|
470 | "Usage: biastemp [-c type] [OPTIONS]\n"
|
---|
471 | " or: biastemp [OPTIONS]\n";
|
---|
472 | cout << endl;
|
---|
473 | }
|
---|
474 |
|
---|
475 | void PrintHelp()
|
---|
476 | {
|
---|
477 | // Main::PrintHelp<StateMachineFTM<StateMachine, ConnectionFTM>>();
|
---|
478 |
|
---|
479 | /* Additional help text which is printed after the configuration
|
---|
480 | options goes here */
|
---|
481 |
|
---|
482 | /*
|
---|
483 | cout << "bla bla bla" << endl << endl;
|
---|
484 | cout << endl;
|
---|
485 | cout << "Environment:" << endl;
|
---|
486 | cout << "environment" << endl;
|
---|
487 | cout << endl;
|
---|
488 | cout << "Examples:" << endl;
|
---|
489 | cout << "test exam" << endl;
|
---|
490 | cout << endl;
|
---|
491 | cout << "Files:" << endl;
|
---|
492 | cout << "files" << endl;
|
---|
493 | cout << endl;
|
---|
494 | */
|
---|
495 | }
|
---|
496 |
|
---|
497 | int main(int argc, const char* argv[])
|
---|
498 | {
|
---|
499 | Configuration conf(argv[0]);
|
---|
500 | conf.SetPrintUsage(PrintUsage);
|
---|
501 | Main::SetupConfiguration(conf);
|
---|
502 | SetupConfiguration(conf);
|
---|
503 |
|
---|
504 | if (!conf.DoParse(argc, argv, PrintHelp))
|
---|
505 | return 127;
|
---|
506 |
|
---|
507 | //try
|
---|
508 | {
|
---|
509 | // No console access at all
|
---|
510 | if (!conf.Has("console"))
|
---|
511 | {
|
---|
512 | if (conf.Get<bool>("no-dim"))
|
---|
513 | return RunShell<LocalStream, StateMachine, ConnectionBiasTemp>(conf);
|
---|
514 | else
|
---|
515 | return RunShell<LocalStream, StateMachineDim, ConnectionDimBiasTemp>(conf);
|
---|
516 | }
|
---|
517 | // Cosole access w/ and w/o Dim
|
---|
518 | if (conf.Get<bool>("no-dim"))
|
---|
519 | {
|
---|
520 | if (conf.Get<int>("console")==0)
|
---|
521 | return RunShell<LocalShell, StateMachine, ConnectionBiasTemp>(conf);
|
---|
522 | else
|
---|
523 | return RunShell<LocalConsole, StateMachine, ConnectionBiasTemp>(conf);
|
---|
524 | }
|
---|
525 | else
|
---|
526 | {
|
---|
527 | if (conf.Get<int>("console")==0)
|
---|
528 | return RunShell<LocalShell, StateMachineDim, ConnectionDimBiasTemp>(conf);
|
---|
529 | else
|
---|
530 | return RunShell<LocalConsole, StateMachineDim, ConnectionDimBiasTemp>(conf);
|
---|
531 | }
|
---|
532 | }
|
---|
533 | /*catch (std::exception& e)
|
---|
534 | {
|
---|
535 | cerr << "Exception: " << e.what() << endl;
|
---|
536 | return -1;
|
---|
537 | }*/
|
---|
538 |
|
---|
539 | return 0;
|
---|
540 | }
|
---|