source: trunk/FACT++/src/lidctrl.cc@ 15900

Last change on this file since 15900 was 15122, checked in by tbretz, 12 years ago
Fixed a problem which occured when the status of both lids was empty before the first report after starting a move arrived.
File size: 21.2 KB
Line 
1#include <boost/bind.hpp>
2#include <boost/array.hpp>
3
4#include <string> // std::string
5#include <algorithm> // std::transform
6#include <cctype> // std::tolower
7
8#include <QtXml/QDomDocument>
9
10#include "FACT.h"
11#include "Dim.h"
12#include "Event.h"
13#include "StateMachineDim.h"
14#include "Connection.h"
15#include "LocalControl.h"
16#include "Configuration.h"
17#include "Console.h"
18
19#include "tools.h"
20
21#include "HeadersLid.h"
22
23namespace ba = boost::asio;
24namespace bs = boost::system;
25namespace dummy = ba::placeholders;
26
27using namespace std;
28
29class ConnectionLid : public Connection
30{
31protected:
32
33 struct Lid
34 {
35 int id;
36
37 float position;
38 float current;
39 string status;
40
41 Lid(int i) : id(i) { }
42
43 bool Set(const QDomNamedNodeMap &map)
44 {
45 if (!map.contains("id") || !map.contains("value"))
46 return false;
47
48 QString item = map.namedItem("id").nodeValue();
49 QString value = map.namedItem("value").nodeValue();
50
51 const char c = '0'+id;
52
53 if (item==(QString("cur")+c))
54 {
55 current = value.toFloat();
56 return true;
57 }
58
59 if (item==(QString("pos")+c))
60 {
61 position = value.toFloat();
62 return true;
63 }
64
65 if (item==(QString("lid")+c))
66 {
67 status = value.toStdString();
68 return true;
69 }
70
71 return false;
72 }
73
74 void Print(ostream &out)
75 {
76 out << "Lid" << id << " @ " << position << " / " << current << "A [" << status << "]" << endl;
77 }
78
79 };
80
81private:
82 uint16_t fInterval;
83
84 bool fIsVerbose;
85
86 string fSite;
87 string fRdfData;
88
89 boost::array<char, 4096> fArray;
90
91 string fNextCommand;
92
93 Time fLastReport;
94
95 Lid fLid1;
96 Lid fLid2;
97
98 virtual void Update(const Lid &, const Lid &)
99 {
100 }
101
102
103 void ProcessAnswer()
104 {
105 if (fIsVerbose)
106 {
107 Out() << "------------------------------------------------------" << endl;
108 Out() << fRdfData << endl;
109 Out() << "------------------------------------------------------" << endl;
110 }
111
112 fRdfData.insert(0, "<?xml version=\"1.0\"?>\n");
113
114 QDomDocument doc;
115 if (!doc.setContent(QString(fRdfData.c_str()), false))
116 {
117 Warn("Parsing of html failed.");
118 PostClose(false);
119 return;
120 }
121
122 if (fIsVerbose)
123 {
124 Out() << "Parsed:\n-------\n" << doc.toString().toStdString() << endl;
125 Out() << "------------------------------------------------------" << endl;
126 }
127
128 const QDomNodeList imageElems = doc.elementsByTagName("span"); // "input"
129
130 /*
131 // elementById
132 for (unsigned int i=0; i<imageElems.length(); i++)
133 {
134 QDomElement e = imageElems.item(i).toElement();
135 Out() << "<" << e.tagName().toStdString() << " ";
136
137 QDomNamedNodeMap att = e.attributes();
138
139 for (int j=0; j<att.size(); j++)
140 {
141 Out() << att.item(j).nodeName().toStdString() << "=";
142 Out() << att.item(j).nodeValue().toStdString() << " ";
143 }
144 Out() << "> " << e.text().toStdString() << endl;
145 }*/
146
147 for (unsigned int i=0; i<imageElems.length(); i++)
148 {
149 const QDomElement e = imageElems.item(i).toElement();
150
151 const QDomNamedNodeMap att = e.attributes();
152
153 fLid1.Set(att);
154 fLid2.Set(att);
155 }
156
157 if (fIsVerbose)
158 {
159 fLid1.Print(Out());
160 fLid2.Print(Out());
161 Out() << "------------------------------------------------------" << endl;
162 }
163
164 Update(fLid1, fLid2);
165
166 fRdfData = "";
167
168 if ((fLid1.status!="Open" && fLid1.status!="Closed" && fLid1.status!="Power Problem" && fLid1.status!="Unknown") ||
169 (fLid2.status!="Open" && fLid2.status!="Closed" && fLid2.status!="Power Problem" && fLid2.status!="Unknown"))
170 Warn("Lid reported status unknown by lidctrl ("+fLid1.status+"/"+fLid2.status+")");
171
172 fLastReport = Time();
173 PostClose(false);
174 }
175
176 void HandleRead(const boost::system::error_code& err, size_t bytes_received)
177 {
178 // Do not schedule a new read if the connection failed.
179 if (bytes_received==0 || err)
180 {
181 if (err==ba::error::eof)
182 {
183 //Warn("Connection closed by remote host.");
184 ProcessAnswer();
185 return;
186 }
187
188 // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
189 // 125: Operation canceled
190 if (err && err!=ba::error::eof && // Connection closed by remote host
191 err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
192 err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
193 {
194 ostringstream str;
195 str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
196 Error(str);
197 }
198 PostClose(err!=ba::error::basic_errors::operation_aborted);
199
200 fRdfData = "";
201 return;
202 }
203
204 fRdfData += string(fArray.data(), bytes_received);
205
206 //cout << "." << flush;
207
208 // Does the message contain a header?
209 const size_t p1 = fRdfData.find("\r\n\r\n");
210 if (p1!=string::npos)
211 {
212 // Does the answer also contain the body?
213 const size_t p2 = fRdfData.find("\r\n\r\n", p1+4);
214 if (p2!=string::npos)
215 {
216 ProcessAnswer();
217 }
218 }
219
220 // Go on reading until the web-server closes the connection
221 StartReadReport();
222 }
223
224 boost::asio::streambuf fBuffer;
225
226 void StartReadReport()
227 {
228 async_read_some(ba::buffer(fArray),
229 boost::bind(&ConnectionLid::HandleRead, this,
230 dummy::error, dummy::bytes_transferred));
231 }
232
233 boost::asio::deadline_timer fKeepAlive;
234
235 void PostRequest(string cmd, const string &args="")
236 {
237 cmd += " "+fSite+" HTTP/1.1\r\n"
238 //"Connection: Keep-Alive\r\n"
239 ;
240
241 ostringstream msg;
242 msg << args.length();
243
244 cmd += "Content-Length: ";
245 cmd += msg.str();
246 cmd +="\r\n";
247
248 if (args.length()>0)
249 cmd += "\r\n"+args + "\r\n";
250
251 cmd += "\r\n";
252
253 //cout << "Post: " << cmd << endl;
254 PostMessage(cmd);
255 }
256
257 void HandleRequest(const bs::error_code &error)
258 {
259 // 125: Operation canceled (bs::error_code(125, bs::system_category))
260 if (error && error!=ba::error::basic_errors::operation_aborted)
261 {
262 ostringstream str;
263 str << "Write timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
264 Error(str);
265
266 PostClose(false);
267 return;
268 }
269
270 if (!is_open())
271 {
272 // For example: Here we could schedule a new accept if we
273 // would not want to allow two connections at the same time.
274 PostClose(true);
275 return;
276 }
277
278 // Check whether the deadline has passed. We compare the deadline
279 // against the current time since a new asynchronous operation
280 // may have moved the deadline before this actor had a chance
281 // to run.
282 if (fKeepAlive.expires_at() > ba::deadline_timer::traits_type::now())
283 return;
284
285 Request();
286 }
287
288
289private:
290 // This is called when a connection was established
291 void ConnectionEstablished()
292 {
293 Request();
294 StartReadReport();
295 }
296
297public:
298 static const uint16_t kMaxAddr;
299
300public:
301 ConnectionLid(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
302 fIsVerbose(true), fLastReport(Time::none),
303 fLid1(1), fLid2(2), fKeepAlive(ioservice)
304 {
305 SetLogStream(&imp);
306 }
307
308 void SetVerbose(bool b)
309 {
310 fIsVerbose = b;
311 Connection::SetVerbose(b);
312 }
313
314 void SetInterval(uint16_t i)
315 {
316 fInterval = i;
317 }
318
319 void SetSite(const string &site)
320 {
321 fSite = site;
322 }
323
324 void Post(const string &post)
325 {
326 fNextCommand = post;
327
328 fLid1.status = "";
329 fLid2.status = "";
330 //PostRequest("POST", post);
331 }
332
333 void Request()
334 {
335 PostRequest("POST", fNextCommand);
336 fNextCommand = "";
337
338 fKeepAlive.expires_from_now(boost::posix_time::seconds(fInterval));
339 fKeepAlive.async_wait(boost::bind(&ConnectionLid::HandleRequest,
340 this, dummy::error));
341 }
342
343 int GetInterval() const
344 {
345 return fInterval;
346 }
347
348 int GetState() const
349 {
350 using namespace Lid;
351
352 // Timeout
353 if (fLastReport.IsValid() && fLastReport+boost::posix_time::seconds(fInterval*2)<Time())
354 return State::kDisconnected;
355
356 // Unidentified state detected
357 if ((!fLid1.status.empty() && fLid1.status!="Open" && fLid1.status!="Closed" && fLid1.status!="Power Problem" && fLid1.status!="Unknown") ||
358 (!fLid2.status.empty() && fLid2.status!="Open" && fLid2.status!="Closed" && fLid2.status!="Power Problem" && fLid2.status!="Unknown"))
359 return State::kUnidentified;
360
361 // This is an assumption, but the best we have...
362 if (fLid1.status=="Closed" && fLid2.status=="Power Problem")
363 return State::kClosed;
364 if (fLid2.status=="Closed" && fLid1.status=="Power Problem")
365 return State::kClosed;
366 if (fLid1.status=="Open" && fLid2.status=="Power Problem")
367 return State::kOpen;
368 if (fLid2.status=="Open" && fLid1.status=="Power Problem")
369 return State::kOpen;
370
371 // Inconsistency
372 if (fLid1.status!=fLid2.status)
373 return State::kInconsistent;
374
375 // Unknown
376 if (fLid1.status=="Unknown")
377 return State::kUnknown;
378
379 // Power Problem
380 if (fLid1.status=="Power Problem")
381 return State::kPowerProblem;
382
383 // Closed
384 if (fLid1.status=="Closed")
385 return State::kClosed;
386
387 // Open
388 if (fLid1.status=="Open")
389 return State::kOpen;
390
391 return State::kConnected;
392 }
393};
394
395const uint16_t ConnectionLid::kMaxAddr = 0xfff;
396
397// ------------------------------------------------------------------------
398
399#include "DimDescriptionService.h"
400
401class ConnectionDimWeather : public ConnectionLid
402{
403private:
404 DimDescribedService fDim;
405
406public:
407 ConnectionDimWeather(ba::io_service& ioservice, MessageImp &imp) :
408 ConnectionLid(ioservice, imp),
409 fDim("LID_CONTROL/DATA", "S:2;F:2;F:2",
410 "|status[bool]:Lid1/2 open or closed"
411 "|I[A]:Lid1/2 current"
412 "|P[dac]:Lid1/2 hall sensor position in averaged dac counts")
413 {
414 }
415
416 void Update(const Lid &l1, const Lid &l2)
417 {
418 struct DimData
419 {
420 int16_t status[2];
421 float current[2];
422 float position[2];
423
424 DimData() { status[0] = status[1] = -1; }
425
426 } __attribute__((__packed__));
427
428 DimData data;
429
430 if (l1.status=="Unknown")
431 data.status[0] = 3;
432 if (l1.status=="Power Problem")
433 data.status[0] = 2;
434 if (l1.status=="Open")
435 data.status[0] = 1;
436 if (l1.status=="Closed")
437 data.status[0] = 0;
438
439 if (l2.status=="Unknown")
440 data.status[1] = 3;
441 if (l2.status=="Power Problem")
442 data.status[1] = 2;
443 if (l2.status=="Open")
444 data.status[1] = 1;
445 if (l2.status=="Closed")
446 data.status[1] = 0;
447
448 data.current[0] = l1.current;
449 data.current[1] = l2.current;
450
451 data.position[0] = l1.position;
452 data.position[1] = l2.position;
453
454 fDim.setQuality(GetState());
455 fDim.Update(data);
456 }
457};
458
459// ------------------------------------------------------------------------
460
461template <class T, class S>
462class StateMachineLidControl : public T, public ba::io_service, public ba::io_service::work
463{
464private:
465 S fLid;
466 Time fLastCommand;
467
468 uint16_t fTimeToMove;
469
470 bool CheckEventSize(size_t has, const char *name, size_t size)
471 {
472 if (has==size)
473 return true;
474
475 ostringstream msg;
476 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
477 T::Fatal(msg);
478 return false;
479 }
480
481 int SetVerbosity(const EventImp &evt)
482 {
483 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
484 return T::kSM_FatalError;
485
486 fLid.SetVerbose(evt.GetBool());
487
488 return T::GetCurrentState();
489 }
490
491 int Post(const EventImp &evt)
492 {
493 fLid.Post(evt.GetText());
494 return T::GetCurrentState();
495 }
496
497 int Open()
498 {
499 fLastCommand = Time();
500 fLid.Post("Button5=");
501 return Lid::State::kMoving;
502 }
503 int Close()
504 {
505 fLastCommand = Time();
506 fLid.Post("Button6=");
507 return Lid::State::kMoving;
508
509 }
510 /*
511 int MoveMotor(const EventImp &evt, int mid)
512 {
513 if (!CheckEventSize(evt.GetSize(), "MoveMotor", 2))
514 return T::kSM_FatalError;
515
516 if (evt.GetUShort()>0xfff)
517 {
518 ostringstream msg;
519 msg << "Position " << evt.GetUShort() << " for motor " << mid+1 << " out of range [0,1023].";
520 T::Error(msg);
521 return T::GetCurrentState();
522 }
523
524 fLid.MoveMotor(mid, evt.GetUShort());
525
526 return T::GetCurrentState();
527 }*/
528
529 int Execute()
530 {
531 // Dispatch (execute) at most one handler from the queue. In contrary
532 // to run_one(), it doesn't wait until a handler is available
533 // which can be dispatched, so poll_one() might return with 0
534 // handlers dispatched. The handlers are always dispatched/executed
535 // synchronously, i.e. within the call to poll_one()
536 poll_one();
537
538 const int rc = fLid.GetState();
539
540 if (T::GetCurrentState()==Lid::State::kMoving &&
541 (rc==Lid::State::kConnected || rc==Lid::State::kDisconnected) &&
542 fLastCommand+boost::posix_time::seconds(fTimeToMove+fLid.GetInterval()) > Time())
543 {
544 return Lid::State::kMoving;
545 }
546
547 return rc==Lid::State::kConnected ? T::GetCurrentState() : rc;
548 }
549
550
551public:
552 StateMachineLidControl(ostream &out=cout) :
553 T(out, "LID_CONTROL"), ba::io_service::work(static_cast<ba::io_service&>(*this)),
554 fLid(*this, *this)
555 {
556 // ba::io_service::work is a kind of keep_alive for the loop.
557 // It prevents the io_service to go to stopped state, which
558 // would prevent any consecutive calls to run()
559 // or poll() to do nothing. reset() could also revoke to the
560 // previous state but this might introduce some overhead of
561 // deletion and creation of threads and more.
562
563 // State names
564 T::AddStateName(Lid::State::kDisconnected, "NoConnection",
565 "No connection to web-server could be established recently");
566
567 T::AddStateName(Lid::State::kConnected, "Connected",
568 "Connection established, but status still not known");
569
570 T::AddStateName(Lid::State::kUnidentified, "Unidentified",
571 "At least one lid reported a state which could not be identified by lidctrl");
572
573 T::AddStateName(Lid::State::kInconsistent, "Inconsistent",
574 "Both lids show different states");
575
576 T::AddStateName(Lid::State::kUnknown, "Unknown",
577 "Arduino reports at least one lids in an unknown status");
578
579 T::AddStateName(Lid::State::kPowerProblem, "PowerProblem",
580 "Arduino reports both lids to have a power problem (might also be that both are at the end switches)");
581
582 T::AddStateName(Lid::State::kClosed, "Closed",
583 "Both lids are closed");
584
585 T::AddStateName(Lid::State::kOpen, "Open",
586 "Both lids are open");
587
588 T::AddStateName(Lid::State::kMoving, "Moving",
589 "Lids are supposed to move, waiting for next status");
590
591
592 // Verbosity commands
593 T::AddEvent("SET_VERBOSE", "B")
594 (bind(&StateMachineLidControl::SetVerbosity, this, placeholders::_1))
595 ("set verbosity state"
596 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
597
598 T::AddEvent("OPEN", Lid::State::kUnidentified, Lid::State::kInconsistent, Lid::State::kUnknown, Lid::State::kPowerProblem, Lid::State::kClosed)
599 (bind(&StateMachineLidControl::Open, this))
600 ("Open the lids");
601
602 T::AddEvent("CLOSE", Lid::State::kUnidentified, Lid::State::kInconsistent, Lid::State::kUnknown, Lid::State::kPowerProblem, Lid::State::kOpen)
603 (bind(&StateMachineLidControl::Close, this))
604 ("Close the lids");
605
606 T::AddEvent("POST", "C")
607 (bind(&StateMachineLidControl::Post, this, placeholders::_1))
608 ("set verbosity state"
609 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
610 }
611
612 int EvalOptions(Configuration &conf)
613 {
614 fLid.SetVerbose(!conf.Get<bool>("quiet"));
615 fLid.SetInterval(conf.Get<uint16_t>("interval"));
616 fLid.SetDebugTx(conf.Get<bool>("debug-tx"));
617 fLid.SetSite(conf.Get<string>("url"));
618 fLid.SetEndpoint(conf.Get<string>("addr"));
619 fLid.StartConnect();
620
621 fTimeToMove = conf.Get<uint16_t>("time-to-move");
622
623 return -1;
624 }
625};
626
627// ------------------------------------------------------------------------
628
629#include "Main.h"
630
631
632template<class T, class S, class R>
633int RunShell(Configuration &conf)
634{
635 return Main::execute<T, StateMachineLidControl<S, R>>(conf);
636}
637
638void SetupConfiguration(Configuration &conf)
639{
640 po::options_description control("Lid control");
641 control.add_options()
642 ("no-dim,d", po_switch(), "Disable dim services")
643 ("addr,a", var<string>(""), "Network address of the lid controling Arduino including port")
644 ("url,u", var<string>(""), "File name and path to load")
645 ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
646 ("interval,i", var<uint16_t>(5), "Interval between two updates on the server in seconds")
647 ("time-to-move", var<uint16_t>(20), "Expected minimum time the lid taks to open/close")
648 ("debug-tx", po_bool(), "Enable debugging of ethernet transmission.")
649 ;
650
651 conf.AddOptions(control);
652}
653
654/*
655 Extract usage clause(s) [if any] for SYNOPSIS.
656 Translators: "Usage" and "or" here are patterns (regular expressions) which
657 are used to match the usage synopsis in program output. An example from cp
658 (GNU coreutils) which contains both strings:
659 Usage: cp [OPTION]... [-T] SOURCE DEST
660 or: cp [OPTION]... SOURCE... DIRECTORY
661 or: cp [OPTION]... -t DIRECTORY SOURCE...
662 */
663void PrintUsage()
664{
665 cout <<
666 "The lidctrl is an interface to the LID control hardware.\n"
667 "\n"
668 "The default is that the program is started without user intercation. "
669 "All actions are supposed to arrive as DimCommands. Using the -c "
670 "option, a local shell can be initialized. With h or help a short "
671 "help message about the usuage can be brought to the screen.\n"
672 "\n"
673 "Usage: lidctrl [-c type] [OPTIONS]\n"
674 " or: lidctrl [OPTIONS]\n";
675 cout << endl;
676}
677
678void PrintHelp()
679{
680// Main::PrintHelp<StateMachineFTM<StateMachine, ConnectionFTM>>();
681
682 /* Additional help text which is printed after the configuration
683 options goes here */
684
685 /*
686 cout << "bla bla bla" << endl << endl;
687 cout << endl;
688 cout << "Environment:" << endl;
689 cout << "environment" << endl;
690 cout << endl;
691 cout << "Examples:" << endl;
692 cout << "test exam" << endl;
693 cout << endl;
694 cout << "Files:" << endl;
695 cout << "files" << endl;
696 cout << endl;
697 */
698}
699
700int main(int argc, const char* argv[])
701{
702 Configuration conf(argv[0]);
703 conf.SetPrintUsage(PrintUsage);
704 Main::SetupConfiguration(conf);
705 SetupConfiguration(conf);
706
707 if (!conf.DoParse(argc, argv, PrintHelp))
708 return 127;
709
710 // No console access at all
711 if (!conf.Has("console"))
712 {
713 if (conf.Get<bool>("no-dim"))
714 return RunShell<LocalStream, StateMachine, ConnectionLid>(conf);
715 else
716 return RunShell<LocalStream, StateMachineDim, ConnectionDimWeather>(conf);
717 }
718 // Cosole access w/ and w/o Dim
719 if (conf.Get<bool>("no-dim"))
720 {
721 if (conf.Get<int>("console")==0)
722 return RunShell<LocalShell, StateMachine, ConnectionLid>(conf);
723 else
724 return RunShell<LocalConsole, StateMachine, ConnectionLid>(conf);
725 }
726 else
727 {
728 if (conf.Get<int>("console")==0)
729 return RunShell<LocalShell, StateMachineDim, ConnectionDimWeather>(conf);
730 else
731 return RunShell<LocalConsole, StateMachineDim, ConnectionDimWeather>(conf);
732 }
733
734 return 0;
735}
Note: See TracBrowser for help on using the repository browser.