source: trunk/FACT++/src/drivectrl.cc@ 12301

Last change on this file since 12301 was 12252, checked in by tbretz, 14 years ago
Added commands to set LED brightness.
File size: 28.8 KB
Line 
1#include <boost/bind.hpp>
2
3#include "FACT.h"
4#include "Dim.h"
5#include "Event.h"
6#include "Shell.h"
7#include "StateMachineDim.h"
8#include "Connection.h"
9#include "Configuration.h"
10#include "Timers.h"
11#include "Console.h"
12#include "Converter.h"
13
14#include "tools.h"
15
16
17namespace ba = boost::asio;
18namespace bs = boost::system;
19namespace dummy = ba::placeholders;
20
21using namespace std;
22
23// ------------------------------------------------------------------------
24
25namespace Drive
26{
27 struct DimPointing
28 {
29 } __attribute__((__packed__));
30
31 struct DimTracking
32 {
33 } __attribute__((__packed__));
34
35 struct DimStarguider
36 {
37 double fMissZd;
38 double fMissAz;
39
40 double fNominalZd;
41 double fNominalAz;
42
43 double fCenterX;
44 double fCenterY;
45
46 double fBrightness;
47
48 uint16_t fNumCorrelated;
49 uint16_t fNumLeds;
50 uint16_t fNumRings;
51 uint16_t fNumStars;
52
53 } __attribute__((__packed__));
54
55 struct DimTPoint
56 {
57 double fNominalAlt;
58 double fNominalAz;
59
60 double fCurrentAlt;
61 double fCurrentAz;
62
63 double fDevZd;
64 double fDevAz;
65
66 double fRa;
67 double fDec;
68
69 double fCenterX;
70 double fCenterY;
71 double fCenterMag;
72
73 double fStarX;
74 double fStarY;
75 double fStarMag;
76
77 double fBrightness;
78 double fRealMag;
79
80 uint16_t fNumLeds;
81 uint16_t fNumRings;
82 uint16_t fNumStars;
83 uint16_t fNumCorrelated;
84
85 } __attribute__((__packed__));
86};
87
88
89
90// ------------------------------------------------------------------------
91
92class ConnectionDrive : public Connection
93{
94 int fState;
95
96 bool fIsVerbose;
97
98 // --verbose
99 // --hex-out
100 // --dynamic-out
101 // --load-file
102 // --leds
103 // --trigger-interval
104 // --physcis-coincidence
105 // --calib-coincidence
106 // --physcis-window
107 // --physcis-window
108 // --trigger-delay
109 // --time-marker-delay
110 // --dead-time
111 // --clock-conditioner-r0
112 // --clock-conditioner-r1
113 // --clock-conditioner-r8
114 // --clock-conditioner-r9
115 // --clock-conditioner-r11
116 // --clock-conditioner-r13
117 // --clock-conditioner-r14
118 // --clock-conditioner-r15
119 // ...
120
121 virtual void UpdatePointing(const Time &, const array<double, 2> &)
122 {
123 }
124
125 virtual void UpdateTracking(const Time &, const array<double, 7> &)
126 {
127 }
128
129 virtual void UpdateStarguider(const Time &, const Drive::DimStarguider &)
130 {
131 }
132
133 virtual void UpdateTPoint(const Time &, const Drive::DimTPoint &)
134 {
135 }
136
137protected:
138 map<uint16_t, int> fCounter;
139
140 ba::streambuf fBuffer;
141
142 Time ReadTime(istream &in)
143 {
144 uint16_t y, m, d, hh, mm, ss, ms;
145 in >> y >> m >> d >> hh >> mm >> ss >> ms;
146
147 return Time(y, m, d, hh, mm, ss, ms*1000);
148 }
149
150 double ReadAngle(istream &in)
151 {
152 char sgn;
153 uint16_t d, m;
154 float s;
155
156 in >> sgn >> d >> m >> s;
157
158 const double ret = ((60.0 * (60.0 * (double)d + (double)m) + s))/3600.;
159 return sgn=='-' ? -ret : ret;
160 }
161
162 void HandleReceivedReport(const boost::system::error_code& err, size_t bytes_received)
163 {
164 // Do not schedule a new read if the connection failed.
165 if (bytes_received==0 || err)
166 {
167 if (err==ba::error::eof)
168 Warn("Connection closed by remote host (FTM).");
169
170 // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
171 // 125: Operation canceled
172 if (err && err!=ba::error::eof && // Connection closed by remote host
173 err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
174 err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
175 {
176 ostringstream str;
177 str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
178 Error(str);
179 }
180 PostClose(err!=ba::error::basic_errors::operation_aborted);
181 return;
182 }
183
184 istream is(&fBuffer);
185
186 string line;
187 getline(is, line);
188
189 if (fIsVerbose)
190 Out() << line << endl;
191
192 StartReadReport();
193
194 if (line.substr(0, 13)=="STARG-REPORT ")
195 {
196 istringstream stream(line.substr(16));
197
198 // 0: Error
199 // 1: Standby
200 // 2: Monitoring
201 uint16_t status1;
202 stream >> status1;
203 const Time t1 = ReadTime(stream);
204
205 uint16_t status2;
206 stream >> status2;
207 const Time t2 = ReadTime(stream);
208
209 double misszd, missaz;
210 stream >> misszd >> missaz;
211
212 const double zd = ReadAngle(stream);
213 const double az = ReadAngle(stream);
214
215 double cx, cy;
216 stream >> cx >> cy;
217
218 int ncor;
219 stream >> ncor;
220
221 double bright, mjd;
222 stream >> bright >> mjd;
223
224 int nled, nring, nstars;
225 stream >> nled >> nring >> nstars;
226
227 if (stream.fail())
228 return;
229
230 Drive::DimStarguider data;
231
232 data.fMissZd = misszd;
233 data.fMissAz = missaz;
234 data.fNominalZd = zd;
235 data.fNominalAz = az;
236 data.fCenterX = cx;
237 data.fCenterY = cy;
238 data.fNumCorrelated = ncor;
239 data.fBrightness = bright;
240 data.fNumLeds = nled;
241 data.fNumRings = nring;
242 data.fNumStars = nstars;
243
244 UpdateStarguider(Time(mjd), data);
245
246 return;
247
248 }
249
250 if (line.substr(0, 14)=="TPOINT-REPORT ")
251 {
252 istringstream stream(line.substr(17));
253
254 uint16_t status1;
255 stream >> status1;
256 const Time t1 = ReadTime(stream);
257
258 uint16_t status2;
259 stream >> status2;
260 const Time t2 = ReadTime(stream);
261
262 double az1, alt1, az2, alt2, ra, dec, dzd, daz;
263 stream >> az1 >> alt1 >> az2 >> alt2 >> ra >> dec >> dzd >> daz;
264
265 // c: center, s:start
266 double mjd, cmag, smag, cx, cy, sx, sy;
267 stream >> mjd >> cmag >> smag >> cx >> cy >> sx >> sy;
268
269 int nled, nring, nstar, ncor;
270 stream >> nled >> nring >> nstar >> ncor;
271
272 double bright, mag;
273 stream >> bright >> mag;
274
275 string name;
276 stream >> name;
277
278 if (stream.fail())
279 return;
280
281 Drive::DimTPoint tpoint;
282
283 tpoint.fNominalAz = az1;
284 tpoint.fNominalAlt = alt1;
285 tpoint.fCurrentAz = az2;
286 tpoint.fCurrentAlt = alt2;
287 tpoint.fDevAz = daz;
288 tpoint.fDevZd = dzd;
289 tpoint.fRa = ra;
290 tpoint.fDec = dec;
291
292 tpoint.fCenterX = cx;
293 tpoint.fCenterY = cy;
294 tpoint.fCenterMag = cmag;
295
296 tpoint.fStarX = sx;
297 tpoint.fStarY = sy;
298 tpoint.fStarMag = smag;
299
300 tpoint.fBrightness = bright;
301
302 tpoint.fNumCorrelated = ncor;
303 tpoint.fNumLeds = nled;
304 tpoint.fNumRings = nring;
305 tpoint.fNumStars = nstar;
306
307 tpoint.fRealMag = mag;
308
309 UpdteTPoint(t1, tpoint);
310
311 return;
312 }
313
314 if (line.substr(0, 13)=="DRIVE-REPORT ")
315 {
316 // DRIVE-REPORT M1
317 // 01 2011 05 14 11 31 19 038
318 // 02 1858 11 17 00 00 00 000
319 // + 000 00 000 + 000 00 000
320 // + 000 00 000
321 // 55695.480081
322 // + 000 00 000 + 000 00 000
323 // + 000 00 000 + 000 00 000
324 // 0000.000 0000.000
325 // 0 2
326
327 // status
328 // year month day hour minute seconds millisec
329 // year month day hour minute seconds millisec
330 // ra(+ h m s) dec(+ d m s) ha(+ h m s)
331 // mjd
332 // zd(+ d m s) az(+ d m s)
333 // zd(+ d m s) az(+ d m s)
334 // zd_err az_err
335 // armed(0=unlocked, 1=locked)
336 // stgmd(0=none, 1=starguider, 2=starguider off)
337 istringstream stream(line.substr(16));
338
339 uint16_t status1;
340 stream >> status1;
341 const Time t1 = ReadTime(stream);
342
343 uint16_t status2;
344 stream >> status2;
345 const Time t2 = ReadTime(stream);
346
347 const double ra = ReadAngle(stream);
348 const double dec = ReadAngle(stream);
349 const double ha = ReadAngle(stream);
350
351 double mjd;
352 stream >> mjd;
353
354 const double zd1 = ReadAngle(stream);
355 const double az1 = ReadAngle(stream);
356 const double zd2 = ReadAngle(stream);
357 const double az2 = ReadAngle(stream);
358
359 double zd_err, az_err;
360 stream >> zd_err;
361 stream >> az_err;
362
363 uint16_t armed, stgmd;
364 stream >> armed;
365 stream >> stgmd;
366
367 if (stream.fail())
368 return;
369
370 // Status 0: Error
371 // Status 1: Stopped
372 // Status 3: Stopping || Moving
373 // Status 4: Tracking
374 if (status1==0)
375 status1 = 99;
376 fState = status1==1 ? armed+1 : status1;
377
378 const array<double, 2> point = {{ zd2, az2 }};
379 UpdatePointing(t1, point);
380
381 const array<double, 7> track =
382 {{
383 ra, dec, ha,
384 zd1, az1,
385 zd_err, az_err
386 }};
387 UpdateTracking(Time(mjd), track);
388
389 // ---- DIM ----> t1 as event time
390 // status1
391 // mjd
392 // ra/dec/ha
393 // zd/az (nominal)
394 // zd/az (current)
395 // err(zd/az)
396 // [armed] [stgmd]
397
398 // Maybe:
399 // POINTING_POSITION --> t1, zd/az (current), [armed, stgmd, status1]
400 //
401 // if (mjd>0)
402 // TRACKING_POSITION --> mjd, zd/az (nominal), err(zd/az)
403 // ra/dec, ha(not well defined),
404 // [Nominal + Error == Current]
405
406 // MJD is the time which corresponds to the nominal position
407 // t1 is the time which corresponds to the current position/HA
408
409 return;
410 }
411 }
412
413 void StartReadReport()
414 {
415 boost::asio::async_read_until(*this, fBuffer, '\n',
416 boost::bind(&ConnectionDrive::HandleReceivedReport, this,
417 dummy::error, dummy::bytes_transferred));
418 }
419
420 boost::asio::deadline_timer fKeepAlive;
421
422 void KeepAlive()
423 {
424 PostMessage(string("KEEP_ALIVE"));
425
426 fKeepAlive.expires_from_now(boost::posix_time::seconds(10));
427 fKeepAlive.async_wait(boost::bind(&ConnectionDrive::HandleKeepAlive,
428 this, dummy::error));
429 }
430
431 void HandleKeepAlive(const bs::error_code &error)
432 {
433 // 125: Operation canceled (bs::error_code(125, bs::system_category))
434 if (error && error!=ba::error::basic_errors::operation_aborted)
435 {
436 ostringstream str;
437 str << "Write timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
438 Error(str);
439
440 PostClose(false);
441 return;
442 }
443
444 if (!is_open())
445 {
446 // For example: Here we could schedule a new accept if we
447 // would not want to allow two connections at the same time.
448 return;
449 }
450
451 // Check whether the deadline has passed. We compare the deadline
452 // against the current time since a new asynchronous operation
453 // may have moved the deadline before this actor had a chance
454 // to run.
455 if (fKeepAlive.expires_at() > ba::deadline_timer::traits_type::now())
456 return;
457
458 KeepAlive();
459 }
460
461
462private:
463 // This is called when a connection was established
464 void ConnectionEstablished()
465 {
466 StartReadReport();
467 KeepAlive();
468 }
469
470 /*
471 void HandleReadTimeout(const bs::error_code &error)
472 {
473 if (error && error!=ba::error::basic_errors::operation_aborted)
474 {
475 stringstream str;
476 str << "Read timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
477 Error(str);
478
479 PostClose();
480 return;
481
482 }
483
484 if (!is_open())
485 {
486 // For example: Here we could schedule a new accept if we
487 // would not want to allow two connections at the same time.
488 return;
489 }
490
491 // Check whether the deadline has passed. We compare the deadline
492 // against the current time since a new asynchronous operation
493 // may have moved the deadline before this actor had a chance
494 // to run.
495 if (fInTimeout.expires_at() > ba::deadline_timer::traits_type::now())
496 return;
497
498 Error("Timeout reading data from "+URL());
499
500 PostClose();
501 }*/
502
503
504public:
505
506 static const uint16_t kMaxAddr;
507
508public:
509 ConnectionDrive(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
510 fState(0), fIsVerbose(true), fKeepAlive(ioservice)
511 {
512 SetLogStream(&imp);
513 }
514
515 void SetVerbose(bool b)
516 {
517 fIsVerbose = b;
518 }
519
520 int GetState() const { return IsConnected() ? fState+1 : 1; }
521};
522
523const uint16_t ConnectionDrive::kMaxAddr = 0xfff;
524
525// ------------------------------------------------------------------------
526
527#include "DimDescriptionService.h"
528
529class ConnectionDimDrive : public ConnectionDrive
530{
531private:
532
533 DimDescribedService fDimPointing;
534 DimDescribedService fDimTracking;
535
536 template<size_t N>
537 void Update(DimDescribedService &svc, const Time &t, const array<double, N> &arr) const
538 {
539 svc.setData(arr);
540 svc.Update(t);
541 }
542
543 virtual void UpdatePointing(const Time &t,
544 const array<double, 2> &arr)
545 {
546 Update(fDimPointing, t, arr);
547 }
548
549 virtual void UpdateTracking(const Time &t,
550 const array<double, 7> &arr)
551 {
552 Update(fDimTracking, t, arr);
553 }
554
555public:
556 ConnectionDimDrive(ba::io_service& ioservice, MessageImp &imp) :
557 ConnectionDrive(ioservice, imp),
558 fDimPointing("FTM_CONTROL/POINTING_POSITION", "D:2", ""),
559 fDimTracking("FTM_CONTROL/TRACKING_POSITION", "D:7", "")
560 {
561 }
562
563 // A B [C] [D] E [F] G H [I] J K [L] M N O P Q R [S] T U V W [X] Y Z
564};
565
566// ------------------------------------------------------------------------
567
568template <class T, class S>
569class StateMachineDrive : public T, public ba::io_service, public ba::io_service::work
570{
571 int Wrap(boost::function<void()> f)
572 {
573 f();
574 return T::GetCurrentState();
575 }
576
577 boost::function<int(const EventImp &)> Wrapper(boost::function<void()> func)
578 {
579 return bind(&StateMachineDrive::Wrap, this, func);
580 }
581
582private:
583 S fDrive;
584
585 enum states_t
586 {
587 kStateDisconnected = 1,
588 kStateConnected,
589 kStateArmed,
590 kStateMoving,
591 kStateTracking,
592 };
593
594 // Status 0: Error
595 // Status 1: Unlocked
596 // Status 2: Locked
597 // Status 3: Stopping || Moving
598 // Status 4: Tracking
599
600 bool CheckEventSize(size_t has, const char *name, size_t size)
601 {
602 if (has==size)
603 return true;
604
605 ostringstream msg;
606 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
607 T::Fatal(msg);
608 return false;
609 }
610
611 enum Coordinates
612 {
613 kPoint,
614 kTrackSlow,
615 kTrackFast
616 };
617
618 string AngleToStr(double angle)
619 {
620 /* Handle sign */
621 const char sgn = angle<0?'-':'+';
622
623 /* Round interval and express in smallest units required */
624 double a = round(3600. * fabs(angle)); // deg to seconds
625
626 /* Separate into fields */
627 const double ad = trunc(a/3600.);
628 a -= ad * 3600.;
629 const double am = trunc(a/60.);
630 a -= am * 60.;
631 const double as = trunc(a);
632
633 /* Return results */
634 ostringstream str;
635 str << sgn << " " << uint16_t(ad) << " " << uint16_t(am) << " " << as;
636 return str.str();
637 }
638
639 int SendCommand(const string &str)
640 {
641 fDrive.PostMessage(str);
642 return T::GetCurrentState();
643 }
644
645 int SendCoordinates(const EventImp &evt, const Coordinates type)
646 {
647 if (!CheckEventSize(evt.GetSize(), "SendCoordinates", 16))
648 return T::kSM_FatalError;
649
650 const double *dat = evt.Ptr<double>();
651
652 string command;
653
654 switch (type)
655 {
656 case kPoint: command += "ZDAZ "; break;
657 case kTrackSlow: command += "RADEC "; break;
658 case kTrackFast: command += "GRB "; break;
659 }
660
661 command += AngleToStr(dat[0]) + ' ' + AngleToStr(dat[1]);
662
663 return SendCommand(command);
664 }
665
666 int SetLedBrightness(const EventImp &evt)
667 {
668 if (!CheckEventSize(evt.GetSize(), "SetLedBrightness", 8))
669 return T::kSM_FatalError;
670
671 const uint32_t *led = evt.Ptr<uint32_t>();
672
673 ostringstream cmd;
674 cmd << "LEDS " << led[0] << " " << led[1];
675 return SendCommand(cmd.str());
676 }
677
678
679 int SetVerbosity(const EventImp &evt)
680 {
681 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
682 return T::kSM_FatalError;
683
684 fDrive.SetVerbose(evt.GetBool());
685
686 return T::GetCurrentState();
687 }
688
689 int Disconnect()
690 {
691 // Close all connections
692 fDrive.PostClose(false);
693
694 /*
695 // Now wait until all connection have been closed and
696 // all pending handlers have been processed
697 poll();
698 */
699
700 return T::GetCurrentState();
701 }
702
703 int Reconnect(const EventImp &evt)
704 {
705 // Close all connections to supress the warning in SetEndpoint
706 fDrive.PostClose(false);
707
708 // Now wait until all connection have been closed and
709 // all pending handlers have been processed
710 poll();
711
712 if (evt.GetBool())
713 fDrive.SetEndpoint(evt.GetString());
714
715 // Now we can reopen the connection
716 fDrive.PostClose(true);
717
718 return T::GetCurrentState();
719 }
720
721 int Execute()
722 {
723 // Dispatch (execute) at most one handler from the queue. In contrary
724 // to run_one(), it doesn't wait until a handler is available
725 // which can be dispatched, so poll_one() might return with 0
726 // handlers dispatched. The handlers are always dispatched/executed
727 // synchronously, i.e. within the call to poll_one()
728 poll_one();
729
730 return fDrive.GetState();
731 }
732
733
734public:
735 StateMachineDrive(ostream &out=cout) :
736 T(out, "DRIVE_CONTROL"), ba::io_service::work(static_cast<ba::io_service&>(*this)),
737 fDrive(*this, *this)
738 {
739 // ba::io_service::work is a kind of keep_alive for the loop.
740 // It prevents the io_service to go to stopped state, which
741 // would prevent any consecutive calls to run()
742 // or poll() to do nothing. reset() could also revoke to the
743 // previous state but this might introduce some overhead of
744 // deletion and creation of threads and more.
745
746 // State names
747 AddStateName(kStateDisconnected, "Disconnected",
748 "");
749
750 AddStateName(kStateConnected, "Connected",
751 "");
752
753 AddStateName(kStateArmed, "Armed",
754 "");
755
756 AddStateName(kStateMoving, "Moving",
757 "");
758
759 AddStateName(kStateTracking, "Tracking",
760 "");
761
762 // kStateIdle
763 // kStateArmed
764 // kStateMoving
765 // kStateTracking
766
767 // Init
768 // -----------
769 // "ARM lock"
770 // "STGMD off"
771
772 /*
773 [ ] WAIT -> WM_WAIT
774 [x] STOP! -> WM_STOP
775 [x] RADEC ra(+ d m s.f) dec(+ d m s.f)
776 [x] GRB ra(+ d m s.f) dec(+ d m s.f)
777 [x] ZDAZ zd(+ d m s.f) az (+ d m s.f)
778 [ ] CELEST id offset angle
779 [ ] MOON wobble offset
780 [ ] PREPS string
781 [ ] TPOIN star mag
782 [ ] ARM lock/unlock
783 [ ] STGMD on/off
784 */
785
786 // Drive Commands
787 T::AddEvent("MOVE_TO", "D:2", kStateArmed) // ->ZDAZ
788 (bind(&StateMachineDrive::SendCoordinates, this, placeholders::_1, kPoint))
789 (""
790 "|zd[deg]:"
791 "|az[deg]:");
792
793 T::AddEvent("TRACK", "D:2", kStateArmed) // ->RADEC/GRB
794 (bind(&StateMachineDrive::SendCoordinates, this, placeholders::_1, kTrackSlow))
795 (""
796 "|ra[h]:"
797 "|dec[deg]:");
798
799 T::AddEvent("MOON", kStateArmed)
800 (bind(&StateMachineDrive::SendCommand, this, "MOON 0 0"))
801 ("");
802 T::AddEvent("VENUS", kStateArmed)
803 (bind(&StateMachineDrive::SendCommand, this, "CELEST 2 0 0"))
804 ("");
805 T::AddEvent("MARS", kStateArmed)
806 (bind(&StateMachineDrive::SendCommand, this, "CELEST 4 0 0"))
807 ("");
808 T::AddEvent("JUPITER", kStateArmed)
809 (bind(&StateMachineDrive::SendCommand, this, "CELEST 5 0 0"))
810 ("");
811 T::AddEvent("SATURN", kStateArmed)
812 (bind(&StateMachineDrive::SendCommand, this, "CELEST 6 0 0"))
813 ("");
814
815 T::AddEvent("TPOINT")
816 (bind(&StateMachineDrive::SendCommand, this, "TPOIN FACT 0"))
817 ("");
818
819 T::AddEvent("SET_LED_BRIGHTNESS", "I:2")
820 (bind(&StateMachineDrive::SetLedBrightness, this, placeholders::_1))
821 ("");
822
823 T::AddEvent("LEDS_OFF")
824 (bind(&StateMachineDrive::SendCommand, this, "LEDS 0 0"))
825 ("");
826
827 T::AddEvent("STOP")
828 (bind(&StateMachineDrive::SendCommand, this, "STOP!"))
829 ("");
830
831 T::AddEvent("ARM", kStateConnected)
832 (bind(&StateMachineDrive::SendCommand, this, "ARM lock"))
833 ("");
834
835
836 // Verbosity commands
837 T::AddEvent("SET_VERBOSE", "B")
838 (bind(&StateMachineDrive::SetVerbosity, this, placeholders::_1))
839 ("set verbosity state"
840 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
841
842 // Conenction commands
843 AddEvent("DISCONNECT", kStateConnected, kStateArmed)
844 (bind(&StateMachineDrive::Disconnect, this))
845 ("disconnect from ethernet");
846
847 AddEvent("RECONNECT", "O", kStateDisconnected, kStateConnected, kStateArmed)
848 (bind(&StateMachineDrive::Reconnect, this, placeholders::_1))
849 ("(Re)connect ethernet connection to FTM, a new address can be given"
850 "|[host][string]:new ethernet address in the form <host:port>");
851
852 fDrive.StartConnect();
853 }
854
855 void SetEndpoint(const string &url)
856 {
857 fDrive.SetEndpoint(url);
858 }
859
860 int EvalOptions(Configuration &conf)
861 {
862 SetEndpoint(conf.Get<string>("addr"));
863
864 fDrive.SetVerbose(!conf.Get<bool>("quiet"));
865
866 return -1;
867 }
868};
869
870// ------------------------------------------------------------------------
871
872#include "Main.h"
873
874/*
875void RunThread(StateMachineImp *io_service)
876{
877 // This is necessary so that the StateMachien Thread can signal the
878 // Readline to exit
879 io_service->Run();
880 Readline::Stop();
881}
882*/
883/*
884template<class S, class T>
885int RunDim(Configuration &conf)
886{
887 WindowLog wout;
888
889 ReadlineColor::PrintBootMsg(wout, conf.GetName(), false);
890
891 if (conf.Has("log"))
892 if (!wout.OpenLogFile(conf.Get<string>("log")))
893 wout << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
894
895 // Start io_service.Run to use the StateMachineImp::Run() loop
896 // Start io_service.run to only use the commandHandler command detaching
897 StateMachineDrive<S, T> io_service(wout);
898 if (!io_service.EvalConfiguration(conf))
899 return -1;
900
901 io_service.Run();
902
903 return 0;
904}
905*/
906
907template<class T, class S, class R>
908int RunShell(Configuration &conf)
909{
910 return Main<T, StateMachineDrive<S, R>>(conf);
911/*
912 static T shell(conf.GetName().c_str(), conf.Get<int>("console")!=1);
913
914 WindowLog &win = shell.GetStreamIn();
915 WindowLog &wout = shell.GetStreamOut();
916
917 if (conf.Has("log"))
918 if (!wout.OpenLogFile(conf.Get<string>("log")))
919 win << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
920
921 StateMachineDrive<S, R> io_service(wout);
922 if (!io_service.EvalConfiguration(conf))
923 return -1;
924
925 shell.SetReceiver(io_service);
926
927 boost::thread t(bind(RunThread, &io_service));
928 // boost::thread t(bind(&StateMachineDrive<S>::Run, &io_service));
929
930 if (conf.Has("cmd"))
931 {
932 const vector<string> v = conf.Get<vector<string>>("cmd");
933 for (vector<string>::const_iterator it=v.begin(); it!=v.end(); it++)
934 shell.ProcessLine(*it);
935 }
936
937 if (conf.Has("exec"))
938 {
939 const vector<string> v = conf.Get<vector<string>>("exec");
940 for (vector<string>::const_iterator it=v.begin(); it!=v.end(); it++)
941 shell.Execute(*it);
942 }
943
944 if (conf.Get<bool>("quit"))
945 shell.Stop();
946
947 shell.Run(); // Run the shell
948 io_service.Stop(); // Signal Loop-thread to stop
949 // io_service.Close(); // Obsolete, done by the destructor
950
951 // Wait until the StateMachine has finished its thread
952 // before returning and destroying the dim objects which might
953 // still be in use.
954 t.join();
955
956 return 0;
957 */
958}
959
960void SetupConfiguration(Configuration &conf)
961{
962 po::options_description control("FTM control options");
963 control.add_options()
964 ("no-dim,d", po_switch(), "Disable dim services")
965 ("addr,a", var<string>("localhost:7404"), "Network address of FTM")
966 ("quiet,q", po_bool(), "Disable printing contents of all received messages (except dynamic data) in clear text.")
967 ;
968
969 conf.AddOptions(control);
970}
971
972/*
973 Extract usage clause(s) [if any] for SYNOPSIS.
974 Translators: "Usage" and "or" here are patterns (regular expressions) which
975 are used to match the usage synopsis in program output. An example from cp
976 (GNU coreutils) which contains both strings:
977 Usage: cp [OPTION]... [-T] SOURCE DEST
978 or: cp [OPTION]... SOURCE... DIRECTORY
979 or: cp [OPTION]... -t DIRECTORY SOURCE...
980 */
981void PrintUsage()
982{
983 cout <<
984 "The drivectrl is an interface to cosy.\n"
985 "\n"
986 "The default is that the program is started without user intercation. "
987 "All actions are supposed to arrive as DimCommands. Using the -c "
988 "option, a local shell can be initialized. With h or help a short "
989 "help message about the usuage can be brought to the screen.\n"
990 "\n"
991 "Usage: drivectrl [-c type] [OPTIONS]\n"
992 " or: drivectrl [OPTIONS]\n";
993 cout << endl;
994}
995
996void PrintHelp()
997{
998 /* Additional help text which is printed after the configuration
999 options goes here */
1000
1001 /*
1002 cout << "bla bla bla" << endl << endl;
1003 cout << endl;
1004 cout << "Environment:" << endl;
1005 cout << "environment" << endl;
1006 cout << endl;
1007 cout << "Examples:" << endl;
1008 cout << "test exam" << endl;
1009 cout << endl;
1010 cout << "Files:" << endl;
1011 cout << "files" << endl;
1012 cout << endl;
1013 */
1014}
1015
1016int main(int argc, const char* argv[])
1017{
1018 Configuration conf(argv[0]);
1019 conf.SetPrintUsage(PrintUsage);
1020 Main::SetupConfiguration(conf);
1021 SetupConfiguration(conf);
1022
1023 if (!conf.DoParse(argc, argv, PrintHelp))
1024 return -1;
1025
1026 //try
1027 {
1028 // No console access at all
1029 if (!conf.Has("console"))
1030 {
1031 if (conf.Get<bool>("no-dim"))
1032 return RunShell<LocalStream, StateMachine, ConnectionDrive>(conf);
1033 else
1034 return RunShell<LocalStream, StateMachineDim, ConnectionDimDrive>(conf);
1035 }
1036 // Cosole access w/ and w/o Dim
1037 if (conf.Get<bool>("no-dim"))
1038 {
1039 if (conf.Get<int>("console")==0)
1040 return RunShell<LocalShell, StateMachine, ConnectionDrive>(conf);
1041 else
1042 return RunShell<LocalConsole, StateMachine, ConnectionDrive>(conf);
1043 }
1044 else
1045 {
1046 if (conf.Get<int>("console")==0)
1047 return RunShell<LocalShell, StateMachineDim, ConnectionDimDrive>(conf);
1048 else
1049 return RunShell<LocalConsole, StateMachineDim, ConnectionDimDrive>(conf);
1050 }
1051 }
1052 /*catch (std::exception& e)
1053 {
1054 cerr << "Exception: " << e.what() << endl;
1055 return -1;
1056 }*/
1057
1058 return 0;
1059}
Note: See TracBrowser for help on using the repository browser.