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

Last change on this file since 17676 was 17320, checked in by tbretz, 11 years ago
Implemented missing Overcurrent state.
File size: 20.8 KB
Line 
1#include <boost/array.hpp>
2
3#include <string> // std::string
4#include <algorithm> // std::transform
5#include <cctype> // std::tolower
6
7#include <QtXml/QDomDocument>
8
9#include "FACT.h"
10#include "Dim.h"
11#include "Event.h"
12#include "StateMachineDim.h"
13#include "StateMachineAsio.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" && fLid1.status!="Overcurrent") ||
169 (fLid2.status!="Open" && fLid2.status!="Closed" && fLid2.status!="Power Problem" && fLid2.status!="Unknown" && fLid1.status!="Overcurrent"))
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" && fLid1.status!="Overcurrent") ||
358 (!fLid2.status.empty() && fLid2.status!="Open" && fLid2.status!="Closed" && fLid2.status!="Power Problem" && fLid2.status!="Unknown" && fLid2.status!="Overcurrent"))
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 // Overcurrent
384 if (fLid1.status=="Overcurrent")
385 return State::kOvercurrent;
386
387 // Closed
388 if (fLid1.status=="Closed")
389 return State::kClosed;
390
391 // Open
392 if (fLid1.status=="Open")
393 return State::kOpen;
394
395 return State::kConnected;
396 }
397};
398
399const uint16_t ConnectionLid::kMaxAddr = 0xfff;
400
401// ------------------------------------------------------------------------
402
403#include "DimDescriptionService.h"
404
405class ConnectionDimWeather : public ConnectionLid
406{
407private:
408 DimDescribedService fDim;
409
410public:
411 ConnectionDimWeather(ba::io_service& ioservice, MessageImp &imp) :
412 ConnectionLid(ioservice, imp),
413 fDim("LID_CONTROL/DATA", "S:2;F:2;F:2",
414 "|status[bool]:Lid1/2 open or closed"
415 "|I[A]:Lid1/2 current"
416 "|P[dac]:Lid1/2 hall sensor position in averaged dac counts")
417 {
418 }
419
420 void Update(const Lid &l1, const Lid &l2)
421 {
422 struct DimData
423 {
424 int16_t status[2];
425 float current[2];
426 float position[2];
427
428 DimData() { status[0] = status[1] = -1; }
429
430 } __attribute__((__packed__));
431
432 DimData data;
433
434 if (l1.status=="Unknown")
435 data.status[0] = 3;
436 if (l1.status=="Power Problem")
437 data.status[0] = 2;
438 if (l1.status=="Open")
439 data.status[0] = 1;
440 if (l1.status=="Closed")
441 data.status[0] = 0;
442
443 if (l2.status=="Unknown")
444 data.status[1] = 3;
445 if (l2.status=="Power Problem")
446 data.status[1] = 2;
447 if (l2.status=="Open")
448 data.status[1] = 1;
449 if (l2.status=="Closed")
450 data.status[1] = 0;
451
452 data.current[0] = l1.current;
453 data.current[1] = l2.current;
454
455 data.position[0] = l1.position;
456 data.position[1] = l2.position;
457
458 fDim.setQuality(GetState());
459 fDim.Update(data);
460 }
461};
462
463// ------------------------------------------------------------------------
464
465template <class T, class S>
466class StateMachineLidControl : public StateMachineAsio<T>
467{
468private:
469 S fLid;
470 Time fLastCommand;
471
472 uint16_t fTimeToMove;
473
474 bool CheckEventSize(size_t has, const char *name, size_t size)
475 {
476 if (has==size)
477 return true;
478
479 ostringstream msg;
480 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
481 T::Fatal(msg);
482 return false;
483 }
484
485 int SetVerbosity(const EventImp &evt)
486 {
487 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
488 return T::kSM_FatalError;
489
490 fLid.SetVerbose(evt.GetBool());
491
492 return T::GetCurrentState();
493 }
494
495 int Post(const EventImp &evt)
496 {
497 fLid.Post(evt.GetText());
498 return T::GetCurrentState();
499 }
500
501 int Open()
502 {
503 fLastCommand = Time();
504 fLid.Post("Button5=");
505 return Lid::State::kMoving;
506 }
507 int Close()
508 {
509 fLastCommand = Time();
510 fLid.Post("Button6=");
511 return Lid::State::kMoving;
512
513 }
514 /*
515 int MoveMotor(const EventImp &evt, int mid)
516 {
517 if (!CheckEventSize(evt.GetSize(), "MoveMotor", 2))
518 return T::kSM_FatalError;
519
520 if (evt.GetUShort()>0xfff)
521 {
522 ostringstream msg;
523 msg << "Position " << evt.GetUShort() << " for motor " << mid+1 << " out of range [0,1023].";
524 T::Error(msg);
525 return T::GetCurrentState();
526 }
527
528 fLid.MoveMotor(mid, evt.GetUShort());
529
530 return T::GetCurrentState();
531 }*/
532
533 int Execute()
534 {
535 const int rc = fLid.GetState();
536
537 if (T::GetCurrentState()==Lid::State::kMoving &&
538 (rc==Lid::State::kConnected || rc==Lid::State::kDisconnected) &&
539 fLastCommand+boost::posix_time::seconds(fTimeToMove+fLid.GetInterval()) > Time())
540 {
541 return Lid::State::kMoving;
542 }
543
544 return rc==Lid::State::kConnected ? T::GetCurrentState() : rc;
545 }
546
547
548public:
549 StateMachineLidControl(ostream &out=cout) :
550 StateMachineAsio<T>(out, "LID_CONTROL"), fLid(*this, *this)
551 {
552 // State names
553 T::AddStateName(Lid::State::kDisconnected, "NoConnection",
554 "No connection to web-server could be established recently");
555
556 T::AddStateName(Lid::State::kConnected, "Connected",
557 "Connection established, but status still not known");
558
559 T::AddStateName(Lid::State::kUnidentified, "Unidentified",
560 "At least one lid reported a state which could not be identified by lidctrl");
561
562 T::AddStateName(Lid::State::kInconsistent, "Inconsistent",
563 "Both lids show different states");
564
565 T::AddStateName(Lid::State::kUnknown, "Unknown",
566 "Arduino reports at least one lids in an unknown status");
567
568 T::AddStateName(Lid::State::kPowerProblem, "PowerProblem",
569 "Arduino reports both lids to have a power problem (might also be that both are at the end switches)");
570
571 T::AddStateName(Lid::State::kOvercurrent, "Overcurrent",
572 "Arduino reports both lids to have a overcurrent (might also be that both are at the end switches)");
573
574 T::AddStateName(Lid::State::kClosed, "Closed",
575 "Both lids are closed");
576
577 T::AddStateName(Lid::State::kOpen, "Open",
578 "Both lids are open");
579
580 T::AddStateName(Lid::State::kMoving, "Moving",
581 "Lids are supposed to move, waiting for next status");
582
583
584 // Verbosity commands
585 T::AddEvent("SET_VERBOSE", "B")
586 (bind(&StateMachineLidControl::SetVerbosity, this, placeholders::_1))
587 ("set verbosity state"
588 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
589
590 T::AddEvent("OPEN", Lid::State::kUnidentified, Lid::State::kInconsistent, Lid::State::kUnknown, Lid::State::kPowerProblem, Lid::State::kClosed)
591 (bind(&StateMachineLidControl::Open, this))
592 ("Open the lids");
593
594 T::AddEvent("CLOSE")(Lid::State::kUnidentified)(Lid::State::kInconsistent)(Lid::State::kUnknown)(Lid::State::kOvercurrent)(Lid::State::kPowerProblem)(Lid::State::kOpen)
595 (bind(&StateMachineLidControl::Close, this))
596 ("Close the lids");
597
598 T::AddEvent("POST", "C")
599 (bind(&StateMachineLidControl::Post, this, placeholders::_1))
600 ("set verbosity state"
601 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
602 }
603
604 int EvalOptions(Configuration &conf)
605 {
606 fLid.SetVerbose(!conf.Get<bool>("quiet"));
607 fLid.SetInterval(conf.Get<uint16_t>("interval"));
608 fLid.SetDebugTx(conf.Get<bool>("debug-tx"));
609 fLid.SetSite(conf.Get<string>("url"));
610 fLid.SetEndpoint(conf.Get<string>("addr"));
611 fLid.StartConnect();
612
613 fTimeToMove = conf.Get<uint16_t>("time-to-move");
614
615 return -1;
616 }
617};
618
619// ------------------------------------------------------------------------
620
621#include "Main.h"
622
623
624template<class T, class S, class R>
625int RunShell(Configuration &conf)
626{
627 return Main::execute<T, StateMachineLidControl<S, R>>(conf);
628}
629
630void SetupConfiguration(Configuration &conf)
631{
632 po::options_description control("Lid control");
633 control.add_options()
634 ("no-dim,d", po_switch(), "Disable dim services")
635 ("addr,a", var<string>(""), "Network address of the lid controling Arduino including port")
636 ("url,u", var<string>(""), "File name and path to load")
637 ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
638 ("interval,i", var<uint16_t>(5), "Interval between two updates on the server in seconds")
639 ("time-to-move", var<uint16_t>(20), "Expected minimum time the lid taks to open/close")
640 ("debug-tx", po_bool(), "Enable debugging of ethernet transmission.")
641 ;
642
643 conf.AddOptions(control);
644}
645
646/*
647 Extract usage clause(s) [if any] for SYNOPSIS.
648 Translators: "Usage" and "or" here are patterns (regular expressions) which
649 are used to match the usage synopsis in program output. An example from cp
650 (GNU coreutils) which contains both strings:
651 Usage: cp [OPTION]... [-T] SOURCE DEST
652 or: cp [OPTION]... SOURCE... DIRECTORY
653 or: cp [OPTION]... -t DIRECTORY SOURCE...
654 */
655void PrintUsage()
656{
657 cout <<
658 "The lidctrl is an interface to the LID control hardware.\n"
659 "\n"
660 "The default is that the program is started without user intercation. "
661 "All actions are supposed to arrive as DimCommands. Using the -c "
662 "option, a local shell can be initialized. With h or help a short "
663 "help message about the usuage can be brought to the screen.\n"
664 "\n"
665 "Usage: lidctrl [-c type] [OPTIONS]\n"
666 " or: lidctrl [OPTIONS]\n";
667 cout << endl;
668}
669
670void PrintHelp()
671{
672// Main::PrintHelp<StateMachineFTM<StateMachine, ConnectionFTM>>();
673
674 /* Additional help text which is printed after the configuration
675 options goes here */
676
677 /*
678 cout << "bla bla bla" << endl << endl;
679 cout << endl;
680 cout << "Environment:" << endl;
681 cout << "environment" << endl;
682 cout << endl;
683 cout << "Examples:" << endl;
684 cout << "test exam" << endl;
685 cout << endl;
686 cout << "Files:" << endl;
687 cout << "files" << endl;
688 cout << endl;
689 */
690}
691
692int main(int argc, const char* argv[])
693{
694 Configuration conf(argv[0]);
695 conf.SetPrintUsage(PrintUsage);
696 Main::SetupConfiguration(conf);
697 SetupConfiguration(conf);
698
699 if (!conf.DoParse(argc, argv, PrintHelp))
700 return 127;
701
702 // No console access at all
703 if (!conf.Has("console"))
704 {
705 if (conf.Get<bool>("no-dim"))
706 return RunShell<LocalStream, StateMachine, ConnectionLid>(conf);
707 else
708 return RunShell<LocalStream, StateMachineDim, ConnectionDimWeather>(conf);
709 }
710 // Cosole access w/ and w/o Dim
711 if (conf.Get<bool>("no-dim"))
712 {
713 if (conf.Get<int>("console")==0)
714 return RunShell<LocalShell, StateMachine, ConnectionLid>(conf);
715 else
716 return RunShell<LocalConsole, StateMachine, ConnectionLid>(conf);
717 }
718 else
719 {
720 if (conf.Get<int>("console")==0)
721 return RunShell<LocalShell, StateMachineDim, ConnectionDimWeather>(conf);
722 else
723 return RunShell<LocalConsole, StateMachineDim, ConnectionDimWeather>(conf);
724 }
725
726 return 0;
727}
Note: See TracBrowser for help on using the repository browser.