source: trunk/FACT++/src/pwrctrl.cc@ 14868

Last change on this file since 14868 was 14525, checked in by tbretz, 12 years ago
Made thformat of the service dim compliant.
File size: 17.2 KB
Line 
1#include <boost/bind.hpp>
2
3#include <string>
4
5#include <QtXml/QDomDocument>
6
7#include "FACT.h"
8#include "Dim.h"
9#include "Event.h"
10#include "StateMachineDim.h"
11#include "Connection.h"
12#include "LocalControl.h"
13#include "Configuration.h"
14#include "Console.h"
15
16#include "tools.h"
17
18#include "HeadersPower.h"
19
20namespace ba = boost::asio;
21namespace bs = boost::system;
22namespace dummy = ba::placeholders;
23
24using namespace std;
25
26class ConnectionInterlock : public Connection
27{
28protected:
29 bool fIsValid;
30
31private:
32 uint16_t fInterval;
33
34 bool fIsVerbose;
35 bool fDebugRx;
36
37 string fSite;
38 string fRdfData;
39
40 boost::array<char, 4096> fArray;
41
42 string fNextCommand;
43
44 Time fLastReport;
45
46 Power::Status fStatus;
47
48 virtual void Update(const Power::Status &)
49 {
50 }
51
52
53 void ProcessAnswer()
54 {
55 if (fDebugRx)
56 {
57 Out() << "------------------------------------------------------" << endl;
58 Out() << fRdfData << endl;
59 Out() << "------------------------------------------------------" << endl;
60 }
61
62 const size_t p1 = fRdfData.find("\r\n\r\n");
63 if (p1==string::npos)
64 {
65 Warn("HTTP header not found.");
66 PostClose(false);
67 return;
68 }
69
70 fRdfData.erase(0, p1+4);
71 fRdfData.insert(0, "<?xml version=\"1.0\"?>\n");
72
73 QDomDocument doc;
74 if (!doc.setContent(QString(fRdfData.c_str()), false))
75 {
76 Warn("Parsing of html failed.");
77 PostClose(false);
78 return;
79 }
80
81 if (fDebugRx)
82 Out() << "Parsed:\n-------\n" << doc.toString().toStdString() << endl;
83
84 const QDomNodeList imageElems = doc.elementsByTagName("span");
85
86 for (unsigned int i=0; i<imageElems.length(); i++)
87 {
88 const QDomElement e = imageElems.item(i).toElement();
89
90 const QDomNamedNodeMap att = e.attributes();
91
92 if (fStatus.Set(att))
93 fIsValid = true;
94 }
95
96 if (fIsVerbose)
97 fStatus.Print(Out());
98
99 Update(fStatus);
100
101 fRdfData = "";
102
103 fLastReport = Time();
104 PostClose(false);
105 }
106
107 void HandleRead(const boost::system::error_code& err, size_t bytes_received)
108 {
109 // Do not schedule a new read if the connection failed.
110 if (bytes_received==0 || err)
111 {
112 if (err==ba::error::eof)
113 {
114 if (!fRdfData.empty())
115 ProcessAnswer();
116 return;
117 }
118
119 // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
120 // 125: Operation canceled
121 if (err && err!=ba::error::eof && // Connection closed by remote host
122 err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
123 err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
124 {
125 ostringstream str;
126 str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
127 Error(str);
128 }
129 PostClose(err!=ba::error::basic_errors::operation_aborted);
130
131 fRdfData = "";
132 return;
133 }
134
135 fRdfData += string(fArray.data(), bytes_received);
136
137 // Does the message contain a header?
138 const size_t p1 = fRdfData.find("\r\n\r\n");
139 if (p1!=string::npos)
140 {
141 // Does the answer also contain the body?
142 const size_t p2 = fRdfData.find("\r\n\r\n", p1+4);
143 if (p2!=string::npos)
144 ProcessAnswer();
145 }
146
147 // Go on reading until the web-server closes the connection
148 StartReadReport();
149 }
150
151 boost::asio::streambuf fBuffer;
152
153 void StartReadReport()
154 {
155 async_read_some(ba::buffer(fArray),
156 boost::bind(&ConnectionInterlock::HandleRead, this,
157 dummy::error, dummy::bytes_transferred));
158 }
159
160 boost::asio::deadline_timer fKeepAlive;
161
162 void HandleRequest(const bs::error_code &error)
163 {
164 // 125: Operation canceled (bs::error_code(125, bs::system_category))
165 if (error && error!=ba::error::basic_errors::operation_aborted)
166 {
167 ostringstream str;
168 str << "Write timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
169 Error(str);
170
171 PostClose(false);
172 return;
173 }
174
175 if (!is_open())
176 {
177 // For example: Here we could schedule a new accept if we
178 // would not want to allow two connections at the same time.
179 PostClose(true);
180 return;
181 }
182
183 // Check whether the deadline has passed. We compare the deadline
184 // against the current time since a new asynchronous operation
185 // may have moved the deadline before this actor had a chance
186 // to run.
187 if (fKeepAlive.expires_at() > ba::deadline_timer::traits_type::now())
188 return;
189
190 Request();
191 }
192
193
194private:
195 // This is called when a connection was established
196 void ConnectionEstablished()
197 {
198 Request();
199 StartReadReport();
200 }
201
202public:
203 static const uint16_t kMaxAddr;
204
205public:
206 ConnectionInterlock(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
207 fIsValid(false), fIsVerbose(true), fDebugRx(false), fLastReport(Time::none), fKeepAlive(ioservice)
208 {
209 SetLogStream(&imp);
210 }
211
212 void SetVerbose(bool b)
213 {
214 fIsVerbose = b;
215 }
216
217 void SetDebugRx(bool b)
218 {
219 fDebugRx = b;
220 Connection::SetVerbose(b);
221 }
222
223 void SetInterval(uint16_t i)
224 {
225 fInterval = i;
226 }
227
228 void SetSite(const string &site)
229 {
230 fSite = site;
231 }
232
233 void Post(const string &post)
234 {
235 fNextCommand = post;
236 }
237
238 void Request()
239 {
240 string cmd = "GET " + fSite;
241
242 if (!fNextCommand.empty())
243 cmd += "?" + fNextCommand;
244
245 cmd += " HTTP/1.1\r\n";
246 cmd += "\r\n";
247
248 PostMessage(cmd);
249
250 fNextCommand = "";
251
252 fKeepAlive.expires_from_now(boost::posix_time::seconds(fInterval));
253 fKeepAlive.async_wait(boost::bind(&ConnectionInterlock::HandleRequest,
254 this, dummy::error));
255 }
256
257 int GetInterval() const
258 {
259 return fInterval;
260 }
261
262 int GetState() const
263 {
264 using namespace Power::State;
265
266 // Timeout
267 if (fLastReport.IsValid() && fLastReport+boost::posix_time::seconds(fInterval*2)<Time())
268 return Power::State::kDisconnected;
269
270 // No dat areceived yet
271 if (!fIsValid)
272 return Power::State::kConnected;
273
274 /*
275 bool fWaterFlowOk;
276 bool fWaterLevelOk;
277 bool fPwrBiasOn;
278 bool fPwr24VOn;
279 bool fPwrPumpOn;
280 bool fPwrDriveOn;
281 bool fDriveMainSwitchOn;
282 bool fDriveFeedbackOn;
283 */
284
285 if (!fStatus.fWaterLevelOk || (fStatus.fPwrPumpOn && !fStatus.fWaterFlowOk))
286 return kCoolingFailure;
287
288 const int rc =
289 (fStatus.fPwrBiasOn ? kBiasOn : 0) |
290 (fStatus.fPwrPumpOn ? kCameraOn : 0) |
291 (fStatus.fDriveFeedbackOn ? kDriveOn : 0);
292
293 return rc==0 ? kSystemOff : rc;
294 }
295};
296
297const uint16_t ConnectionInterlock::kMaxAddr = 0xfff;
298
299// ------------------------------------------------------------------------
300
301#include "DimDescriptionService.h"
302
303class ConnectionDimWeather : public ConnectionInterlock
304{
305private:
306 DimDescribedService fDim;
307
308public:
309 ConnectionDimWeather(ba::io_service& ioservice, MessageImp &imp) :
310 ConnectionInterlock(ioservice, imp),
311 fDim("PWR_CONTROL/DATA", "C:1;C:1;C:1;C:1;C:1;C:1;C:1;C:1",
312 "|water_lvl[bool]:Water level ok"
313 "|water_flow[bool]:Water flowing"
314 "|pwr_24V[bool]:24V power enabled"
315 "|pwr_pump[bool]:Pump power enabled"
316 "|pwr_bias[bool]:Bias power enabled"
317 "|pwr_drive[bool]:Drive power enabled (command value)"
318 "|main_drive[bool]:Drive manual main switch on"
319 "|feedback_drive[bool]:Drive power on (feedback value)")
320 {
321 }
322
323 void Update(const Power::Status &status)
324 {
325 fDim.setQuality(status.GetVal());
326 fDim.Update(status);
327 }
328};
329
330// ------------------------------------------------------------------------
331
332template <class T, class S>
333class StateMachinePowerControl : public T, public ba::io_service, public ba::io_service::work
334{
335private:
336 S fPower;
337 Time fLastCommand;
338
339 bool CheckEventSize(size_t has, const char *name, size_t size)
340 {
341 if (has==size)
342 return true;
343
344 ostringstream msg;
345 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
346 T::Fatal(msg);
347 return false;
348 }
349
350 int SetVerbosity(const EventImp &evt)
351 {
352 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
353 return T::kSM_FatalError;
354
355 fPower.SetVerbose(evt.GetBool());
356
357 return T::GetCurrentState();
358 }
359
360 int SetDebugRx(const EventImp &evt)
361 {
362 if (!CheckEventSize(evt.GetSize(), "SetDebugRx", 1))
363 return T::kSM_FatalError;
364
365 fPower.SetDebugRx(evt.GetBool());
366
367 return T::GetCurrentState();
368 }
369
370 int Post(const EventImp &evt)
371 {
372 fPower.Post(evt.GetText());
373 return T::GetCurrentState();
374 }
375
376 int SetCameraPower(const EventImp &evt)
377 {
378 if (!CheckEventSize(evt.GetSize(), "SetCameraPower", 1))
379 return T::kSM_FatalError;
380
381 fLastCommand = Time();
382 fPower.Post(evt.GetBool() ? "cam_on=Camera+ON" : "cam_off=Camera+OFF");
383 return T::GetCurrentState();
384 }
385
386 int ToggleDrive()
387 {
388 fLastCommand = Time();
389 fPower.Post("dt=Drive+ON%2FOFF");
390 return T::GetCurrentState();
391
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 fPower.GetState();
404 }
405
406
407public:
408 StateMachinePowerControl(ostream &out=cout) :
409 T(out, "PWR_CONTROL"), ba::io_service::work(static_cast<ba::io_service&>(*this)),
410 fPower(*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(Power::State::kDisconnected, "NoConnection",
421 "No connection to web-server could be established recently");
422
423 T::AddStateName(Power::State::kConnected, "Connected",
424 "Connection established, but status still not known");
425
426 T::AddStateName(Power::State::kSystemOff, "PowerOff",
427 "Camera, Bias and Drive power off");
428
429 T::AddStateName(Power::State::kBiasOn, "BiasOn",
430 "Camera and Drive power off, Bias on");
431
432 T::AddStateName(Power::State::kDriveOn, "DriveOn",
433 "Camera and Bias power off, Drive on");
434
435 T::AddStateName(Power::State::kCameraOn, "CameraOn",
436 "Drive and Bias power off, Camera on");
437
438 T::AddStateName(Power::State::kBiasOff, "BiasOff",
439 "Camera and Drive power on, Bias off");
440
441 T::AddStateName(Power::State::kDriveOff, "DriveOff",
442 "Camera and Bias power on, Drive off");
443
444 T::AddStateName(Power::State::kCameraOff, "CameraOff",
445 "Drive and Bias power on, Camera off");
446
447 T::AddStateName(Power::State::kSystemOn, "SystemOn",
448 "Camera, Bias and drive power on");
449
450
451 // Verbosity commands
452 T::AddEvent("SET_VERBOSE", "B:1")
453 (bind(&StateMachinePowerControl::SetVerbosity, this, placeholders::_1))
454 ("Set verbosity state"
455 "|verbosity[bool]:disable or enable verbosity for interpreted data (yes/no)");
456
457 T::AddEvent("SET_DEBUG_RX", "B:1")
458 (bind(&StateMachinePowerControl::SetDebugRx, this, placeholders::_1))
459 ("Set debux-rx state"
460 "|debug[bool]:dump received text and parsed text to console (yes/no)");
461
462 T::AddEvent("CAMERA_POWER", "B:1")
463 (bind(&StateMachinePowerControl::SetCameraPower, this, placeholders::_1))
464 ("Switch camera power"
465 "|power[bool]:Switch camera power 'on' or 'off'");
466
467 T::AddEvent("TOGGLE_DRIVE")
468 (bind(&StateMachinePowerControl::ToggleDrive, this))
469 ("Toggle drive power");
470
471 T::AddEvent("POST", "C")
472 (bind(&StateMachinePowerControl::Post, this, placeholders::_1))
473 ("set verbosity state"
474 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
475 }
476
477 int EvalOptions(Configuration &conf)
478 {
479 fPower.SetVerbose(!conf.Get<bool>("quiet"));
480 fPower.SetInterval(conf.Get<uint16_t>("interval"));
481 fPower.SetDebugTx(conf.Get<bool>("debug-tx"));
482 fPower.SetDebugRx(conf.Get<bool>("debug-rx"));
483 fPower.SetSite(conf.Get<string>("url"));
484 fPower.SetEndpoint(conf.Get<string>("addr"));
485 fPower.StartConnect();
486
487 return -1;
488 }
489};
490
491// ------------------------------------------------------------------------
492
493#include "Main.h"
494
495
496template<class T, class S, class R>
497int RunShell(Configuration &conf)
498{
499 return Main::execute<T, StateMachinePowerControl<S, R>>(conf);
500}
501
502void SetupConfiguration(Configuration &conf)
503{
504 po::options_description control("Lid control");
505 control.add_options()
506 ("no-dim,d", po_switch(), "Disable dim services")
507 ("addr,a", var<string>(""), "Network address of the lid controling Arduino including port")
508 ("url,u", var<string>(""), "File name and path to load")
509 ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
510 ("interval,i", var<uint16_t>(5), "Interval between two updates on the server in seconds")
511 ("debug-tx", po_bool(), "Enable debugging of ethernet transmission.")
512 ("debug-rx", po_bool(), "Enable debugging for received data.")
513 ;
514
515 conf.AddOptions(control);
516}
517
518/*
519 Extract usage clause(s) [if any] for SYNOPSIS.
520 Translators: "Usage" and "or" here are patterns (regular expressions) which
521 are used to match the usage synopsis in program output. An example from cp
522 (GNU coreutils) which contains both strings:
523 Usage: cp [OPTION]... [-T] SOURCE DEST
524 or: cp [OPTION]... SOURCE... DIRECTORY
525 or: cp [OPTION]... -t DIRECTORY SOURCE...
526 */
527void PrintUsage()
528{
529 cout <<
530 "The lidctrl is an interface to the LID control hardware.\n"
531 "\n"
532 "The default is that the program is started without user intercation. "
533 "All actions are supposed to arrive as DimCommands. Using the -c "
534 "option, a local shell can be initialized. With h or help a short "
535 "help message about the usuage can be brought to the screen.\n"
536 "\n"
537 "Usage: lidctrl [-c type] [OPTIONS]\n"
538 " or: lidctrl [OPTIONS]\n";
539 cout << endl;
540}
541
542void PrintHelp()
543{
544// Main::PrintHelp<StateMachineFTM<StateMachine, ConnectionFTM>>();
545
546 /* Additional help text which is printed after the configuration
547 options goes here */
548
549 /*
550 cout << "bla bla bla" << endl << endl;
551 cout << endl;
552 cout << "Environment:" << endl;
553 cout << "environment" << endl;
554 cout << endl;
555 cout << "Examples:" << endl;
556 cout << "test exam" << endl;
557 cout << endl;
558 cout << "Files:" << endl;
559 cout << "files" << endl;
560 cout << endl;
561 */
562}
563
564int main(int argc, const char* argv[])
565{
566 Configuration conf(argv[0]);
567 conf.SetPrintUsage(PrintUsage);
568 Main::SetupConfiguration(conf);
569 SetupConfiguration(conf);
570
571 if (!conf.DoParse(argc, argv, PrintHelp))
572 return 127;
573
574 // No console access at all
575 if (!conf.Has("console"))
576 {
577 if (conf.Get<bool>("no-dim"))
578 return RunShell<LocalStream, StateMachine, ConnectionInterlock>(conf);
579 else
580 return RunShell<LocalStream, StateMachineDim, ConnectionDimWeather>(conf);
581 }
582 // Cosole access w/ and w/o Dim
583 if (conf.Get<bool>("no-dim"))
584 {
585 if (conf.Get<int>("console")==0)
586 return RunShell<LocalShell, StateMachine, ConnectionInterlock>(conf);
587 else
588 return RunShell<LocalConsole, StateMachine, ConnectionInterlock>(conf);
589 }
590 else
591 {
592 if (conf.Get<int>("console")==0)
593 return RunShell<LocalShell, StateMachineDim, ConnectionDimWeather>(conf);
594 else
595 return RunShell<LocalConsole, StateMachineDim, ConnectionDimWeather>(conf);
596 }
597
598 return 0;
599}
Note: See TracBrowser for help on using the repository browser.