source: trunk/FACT++/src/biastemp.cc@ 19926

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