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

Last change on this file since 12009 was 11837, checked in by tbretz, 13 years ago
Changed Dim services to ensure they send the time.
File size: 28.1 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 return;
310 }
311
312 if (line.substr(0, 13)=="DRIVE-REPORT ")
313 {
314 // DRIVE-REPORT M1
315 // 01 2011 05 14 11 31 19 038
316 // 02 1858 11 17 00 00 00 000
317 // + 000 00 000 + 000 00 000
318 // + 000 00 000
319 // 55695.480081
320 // + 000 00 000 + 000 00 000
321 // + 000 00 000 + 000 00 000
322 // 0000.000 0000.000
323 // 0 2
324
325 // status
326 // year month day hour minute seconds millisec
327 // year month day hour minute seconds millisec
328 // ra(+ h m s) dec(+ d m s) ha(+ h m s)
329 // mjd
330 // zd(+ d m s) az(+ d m s)
331 // zd(+ d m s) az(+ d m s)
332 // zd_err az_err
333 // armed(0=unlocked, 1=locked)
334 // stgmd(0=none, 1=starguider, 2=starguider off)
335 istringstream stream(line.substr(16));
336
337 uint16_t status1;
338 stream >> status1;
339 const Time t1 = ReadTime(stream);
340
341 uint16_t status2;
342 stream >> status2;
343 const Time t2 = ReadTime(stream);
344
345 const double ra = ReadAngle(stream);
346 const double dec = ReadAngle(stream);
347 const double ha = ReadAngle(stream);
348
349 double mjd;
350 stream >> mjd;
351
352 const double zd1 = ReadAngle(stream);
353 const double az1 = ReadAngle(stream);
354 const double zd2 = ReadAngle(stream);
355 const double az2 = ReadAngle(stream);
356
357 double zd_err, az_err;
358 stream >> zd_err;
359 stream >> az_err;
360
361 uint16_t armed, stgmd;
362 stream >> armed;
363 stream >> stgmd;
364
365 if (stream.fail())
366 return;
367
368 // Status 0: Error
369 // Status 1: Stopped
370 // Status 3: Stopping || Moving
371 // Status 4: Tracking
372 if (status1==0)
373 status1 = 99;
374 fState = status1==1 ? armed+1 : status1;
375
376 const array<double, 2> point = {{ zd2, az2 }};
377 UpdatePointing(t1, point);
378
379 const array<double, 7> track =
380 {{
381 ra, dec, ha,
382 zd1, az1,
383 zd_err, az_err
384 }};
385 UpdateTracking(Time(mjd), track);
386
387 // ---- DIM ----> t1 as event time
388 // status1
389 // mjd
390 // ra/dec/ha
391 // zd/az (nominal)
392 // zd/az (current)
393 // err(zd/az)
394 // [armed] [stgmd]
395
396 // Maybe:
397 // POINTING_POSITION --> t1, zd/az (current), [armed, stgmd, status1]
398 //
399 // if (mjd>0)
400 // TRACKING_POSITION --> mjd, zd/az (nominal), err(zd/az)
401 // ra/dec, ha(not well defined),
402 // [Nominal + Error == Current]
403
404 // MJD is the time which corresponds to the nominal position
405 // t1 is the time which corresponds to the current position/HA
406
407 return;
408 }
409 }
410
411 void StartReadReport()
412 {
413 boost::asio::async_read_until(*this, fBuffer, '\n',
414 boost::bind(&ConnectionDrive::HandleReceivedReport, this,
415 dummy::error, dummy::bytes_transferred));
416 }
417
418 boost::asio::deadline_timer fKeepAlive;
419
420 void KeepAlive()
421 {
422 PostMessage(string("KEEP_ALIVE"));
423
424 fKeepAlive.expires_from_now(boost::posix_time::seconds(10));
425 fKeepAlive.async_wait(boost::bind(&ConnectionDrive::HandleKeepAlive,
426 this, dummy::error));
427 }
428
429 void HandleKeepAlive(const bs::error_code &error)
430 {
431 // 125: Operation canceled (bs::error_code(125, bs::system_category))
432 if (error && error!=ba::error::basic_errors::operation_aborted)
433 {
434 ostringstream str;
435 str << "Write timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
436 Error(str);
437
438 PostClose(false);
439 return;
440 }
441
442 if (!is_open())
443 {
444 // For example: Here we could schedule a new accept if we
445 // would not want to allow two connections at the same time.
446 return;
447 }
448
449 // Check whether the deadline has passed. We compare the deadline
450 // against the current time since a new asynchronous operation
451 // may have moved the deadline before this actor had a chance
452 // to run.
453 if (fKeepAlive.expires_at() > ba::deadline_timer::traits_type::now())
454 return;
455
456 KeepAlive();
457 }
458
459
460private:
461 // This is called when a connection was established
462 void ConnectionEstablished()
463 {
464 StartReadReport();
465 KeepAlive();
466 }
467
468 /*
469 void HandleReadTimeout(const bs::error_code &error)
470 {
471 if (error && error!=ba::error::basic_errors::operation_aborted)
472 {
473 stringstream str;
474 str << "Read timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
475 Error(str);
476
477 PostClose();
478 return;
479
480 }
481
482 if (!is_open())
483 {
484 // For example: Here we could schedule a new accept if we
485 // would not want to allow two connections at the same time.
486 return;
487 }
488
489 // Check whether the deadline has passed. We compare the deadline
490 // against the current time since a new asynchronous operation
491 // may have moved the deadline before this actor had a chance
492 // to run.
493 if (fInTimeout.expires_at() > ba::deadline_timer::traits_type::now())
494 return;
495
496 Error("Timeout reading data from "+URL());
497
498 PostClose();
499 }*/
500
501
502public:
503
504 static const uint16_t kMaxAddr;
505
506public:
507 ConnectionDrive(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
508 fState(0), fIsVerbose(true), fKeepAlive(ioservice)
509 {
510 SetLogStream(&imp);
511 }
512
513 void SetVerbose(bool b)
514 {
515 fIsVerbose = b;
516 }
517
518 int GetState() const { return IsConnected() ? fState+1 : 1; }
519};
520
521const uint16_t ConnectionDrive::kMaxAddr = 0xfff;
522
523// ------------------------------------------------------------------------
524
525#include "DimDescriptionService.h"
526
527class ConnectionDimDrive : public ConnectionDrive
528{
529private:
530
531 DimDescribedService fDimPointing;
532 DimDescribedService fDimTracking;
533
534 template<size_t N>
535 void Update(DimDescribedService &svc, const Time &t, const array<double, N> &arr) const
536 {
537 svc.setData(arr);
538 svc.Update(t);
539 }
540
541 virtual void UpdatePointing(const Time &t,
542 const array<double, 2> &arr)
543 {
544 Update(fDimPointing, t, arr);
545 }
546
547 virtual void UpdateTracking(const Time &t,
548 const array<double, 7> &arr)
549 {
550 Update(fDimTracking, t, arr);
551 }
552
553public:
554 ConnectionDimDrive(ba::io_service& ioservice, MessageImp &imp) :
555 ConnectionDrive(ioservice, imp),
556 fDimPointing("FTM_CONTROL/POINTING_POSITION", "D:2", ""),
557 fDimTracking("FTM_CONTROL/TRACKING_POSITION", "D:7", "")
558 {
559 }
560
561 // 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
562};
563
564// ------------------------------------------------------------------------
565
566template <class T, class S>
567class StateMachineDrive : public T, public ba::io_service, public ba::io_service::work
568{
569 int Wrap(boost::function<void()> f)
570 {
571 f();
572 return T::GetCurrentState();
573 }
574
575 boost::function<int(const EventImp &)> Wrapper(boost::function<void()> func)
576 {
577 return bind(&StateMachineDrive::Wrap, this, func);
578 }
579
580private:
581 S fDrive;
582
583 enum states_t
584 {
585 kStateDisconnected = 1,
586 kStateConnected,
587 kStateArmed,
588 kStateMoving,
589 kStateTracking,
590 };
591
592 // Status 0: Error
593 // Status 1: Unlocked
594 // Status 2: Locked
595 // Status 3: Stopping || Moving
596 // Status 4: Tracking
597
598 bool CheckEventSize(size_t has, const char *name, size_t size)
599 {
600 if (has==size)
601 return true;
602
603 ostringstream msg;
604 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
605 T::Fatal(msg);
606 return false;
607 }
608
609 enum Coordinates
610 {
611 kPoint,
612 kTrackSlow,
613 kTrackFast
614 };
615
616 string AngleToStr(double angle)
617 {
618 /* Handle sign */
619 const char sgn = angle<0?'-':'+';
620
621 /* Round interval and express in smallest units required */
622 double a = round(3600. * fabs(angle)); // deg to seconds
623
624 /* Separate into fields */
625 const double ad = trunc(a/3600.);
626 a -= ad * 3600.;
627 const double am = trunc(a/60.);
628 a -= am * 60.;
629 const double as = trunc(a);
630
631 /* Return results */
632 ostringstream str;
633 str << sgn << " " << uint16_t(ad) << " " << uint16_t(am) << " " << as;
634 return str.str();
635 }
636
637 int SendCommand(const string &str)
638 {
639 fDrive.PostMessage(str);
640 return T::GetCurrentState();
641 }
642
643 int SendCoordinates(const EventImp &evt, const Coordinates type)
644 {
645 if (!CheckEventSize(evt.GetSize(), "SendCoordinates", 16))
646 return T::kSM_FatalError;
647
648 const double *dat = evt.Ptr<double>();
649
650 string command;
651
652 switch (type)
653 {
654 case kPoint: command += "ZDAZ "; break;
655 case kTrackSlow: command += "RADEC "; break;
656 case kTrackFast: command += "GRB "; break;
657 }
658
659 command += AngleToStr(dat[0]) + ' ' + AngleToStr(dat[1]);
660
661 return SendCommand(command);
662 }
663
664 int SetVerbosity(const EventImp &evt)
665 {
666 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
667 return T::kSM_FatalError;
668
669 fDrive.SetVerbose(evt.GetBool());
670
671 return T::GetCurrentState();
672 }
673
674 int Disconnect()
675 {
676 // Close all connections
677 fDrive.PostClose(false);
678
679 /*
680 // Now wait until all connection have been closed and
681 // all pending handlers have been processed
682 poll();
683 */
684
685 return T::GetCurrentState();
686 }
687
688 int Reconnect(const EventImp &evt)
689 {
690 // Close all connections to supress the warning in SetEndpoint
691 fDrive.PostClose(false);
692
693 // Now wait until all connection have been closed and
694 // all pending handlers have been processed
695 poll();
696
697 if (evt.GetBool())
698 fDrive.SetEndpoint(evt.GetString());
699
700 // Now we can reopen the connection
701 fDrive.PostClose(true);
702
703 return T::GetCurrentState();
704 }
705
706 int Execute()
707 {
708 // Dispatch (execute) at most one handler from the queue. In contrary
709 // to run_one(), it doesn't wait until a handler is available
710 // which can be dispatched, so poll_one() might return with 0
711 // handlers dispatched. The handlers are always dispatched/executed
712 // synchronously, i.e. within the call to poll_one()
713 poll_one();
714
715 return fDrive.GetState();
716 }
717
718
719public:
720 StateMachineDrive(ostream &out=cout) :
721 T(out, "DRIVE_CONTROL"), ba::io_service::work(static_cast<ba::io_service&>(*this)),
722 fDrive(*this, *this)
723 {
724 // ba::io_service::work is a kind of keep_alive for the loop.
725 // It prevents the io_service to go to stopped state, which
726 // would prevent any consecutive calls to run()
727 // or poll() to do nothing. reset() could also revoke to the
728 // previous state but this might introduce some overhead of
729 // deletion and creation of threads and more.
730
731 // State names
732 AddStateName(kStateDisconnected, "Disconnected",
733 "");
734
735 AddStateName(kStateConnected, "Connected",
736 "");
737
738 AddStateName(kStateArmed, "Armed",
739 "");
740
741 AddStateName(kStateMoving, "Moving",
742 "");
743
744 AddStateName(kStateTracking, "Tracking",
745 "");
746
747 // kStateIdle
748 // kStateArmed
749 // kStateMoving
750 // kStateTracking
751
752 // Init
753 // -----------
754 // "ARM lock"
755 // "STGMD off"
756
757 /*
758 [ ] WAIT -> WM_WAIT
759 [x] STOP! -> WM_STOP
760 [x] RADEC ra(+ d m s.f) dec(+ d m s.f)
761 [x] GRB ra(+ d m s.f) dec(+ d m s.f)
762 [x] ZDAZ zd(+ d m s.f) az (+ d m s.f)
763 [ ] CELEST id offset angle
764 [ ] MOON wobble offset
765 [ ] PREPS string
766 [ ] TPOIN star mag
767 [ ] ARM lock/unlock
768 [ ] STGMD on/off
769 */
770
771 // Drive Commands
772 T::AddEvent("MOVE_TO", "D:2", kStateArmed) // ->ZDAZ
773 (bind(&StateMachineDrive::SendCoordinates, this, placeholders::_1, kPoint))
774 (""
775 "|zd[deg]:"
776 "|az[deg]:");
777
778 T::AddEvent("TRACK", "D:2", kStateArmed) // ->RADEC/GRB
779 (bind(&StateMachineDrive::SendCoordinates, this, placeholders::_1, kTrackSlow))
780 (""
781 "|ra[h]:"
782 "|dec[deg]:");
783
784 T::AddEvent("MOON", kStateArmed)
785 (bind(&StateMachineDrive::SendCommand, this, "MOON 0 0"))
786 ("");
787 T::AddEvent("VENUS", kStateArmed)
788 (bind(&StateMachineDrive::SendCommand, this, "CELEST 2 0 0"))
789 ("");
790 T::AddEvent("MARS", kStateArmed)
791 (bind(&StateMachineDrive::SendCommand, this, "CELEST 4 0 0"))
792 ("");
793 T::AddEvent("JUPITER", kStateArmed)
794 (bind(&StateMachineDrive::SendCommand, this, "CELEST 5 0 0"))
795 ("");
796 T::AddEvent("SATURN", kStateArmed)
797 (bind(&StateMachineDrive::SendCommand, this, "CELEST 6 0 0"))
798 ("");
799
800 T::AddEvent("TPOINT")
801 (bind(&StateMachineDrive::SendCommand, this, "TPOIN FACT 0"))
802 ("");
803
804 T::AddEvent("STOP")
805 (bind(&StateMachineDrive::SendCommand, this, "STOP!"))
806 ("");
807
808 T::AddEvent("ARM", kStateConnected)
809 (bind(&StateMachineDrive::SendCommand, this, "ARM lock"))
810 ("");
811
812
813 // Verbosity commands
814 T::AddEvent("SET_VERBOSE", "B")
815 (bind(&StateMachineDrive::SetVerbosity, this, placeholders::_1))
816 ("set verbosity state"
817 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
818
819 // Conenction commands
820 AddEvent("DISCONNECT", kStateConnected, kStateArmed)
821 (bind(&StateMachineDrive::Disconnect, this))
822 ("disconnect from ethernet");
823
824 AddEvent("RECONNECT", "O", kStateDisconnected, kStateConnected, kStateArmed)
825 (bind(&StateMachineDrive::Reconnect, this, placeholders::_1))
826 ("(Re)connect ethernet connection to FTM, a new address can be given"
827 "|[host][string]:new ethernet address in the form <host:port>");
828
829 fDrive.StartConnect();
830 }
831
832 void SetEndpoint(const string &url)
833 {
834 fDrive.SetEndpoint(url);
835 }
836
837 int EvalOptions(Configuration &conf)
838 {
839 SetEndpoint(conf.Get<string>("addr"));
840
841 fDrive.SetVerbose(!conf.Get<bool>("quiet"));
842
843 return -1;
844 }
845};
846
847// ------------------------------------------------------------------------
848
849#include "Main.h"
850
851/*
852void RunThread(StateMachineImp *io_service)
853{
854 // This is necessary so that the StateMachien Thread can signal the
855 // Readline to exit
856 io_service->Run();
857 Readline::Stop();
858}
859*/
860/*
861template<class S, class T>
862int RunDim(Configuration &conf)
863{
864 WindowLog wout;
865
866 ReadlineColor::PrintBootMsg(wout, conf.GetName(), false);
867
868 if (conf.Has("log"))
869 if (!wout.OpenLogFile(conf.Get<string>("log")))
870 wout << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
871
872 // Start io_service.Run to use the StateMachineImp::Run() loop
873 // Start io_service.run to only use the commandHandler command detaching
874 StateMachineDrive<S, T> io_service(wout);
875 if (!io_service.EvalConfiguration(conf))
876 return -1;
877
878 io_service.Run();
879
880 return 0;
881}
882*/
883
884template<class T, class S, class R>
885int RunShell(Configuration &conf)
886{
887 return Main<T, StateMachineDrive<S, R>>(conf);
888/*
889 static T shell(conf.GetName().c_str(), conf.Get<int>("console")!=1);
890
891 WindowLog &win = shell.GetStreamIn();
892 WindowLog &wout = shell.GetStreamOut();
893
894 if (conf.Has("log"))
895 if (!wout.OpenLogFile(conf.Get<string>("log")))
896 win << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
897
898 StateMachineDrive<S, R> io_service(wout);
899 if (!io_service.EvalConfiguration(conf))
900 return -1;
901
902 shell.SetReceiver(io_service);
903
904 boost::thread t(bind(RunThread, &io_service));
905 // boost::thread t(bind(&StateMachineDrive<S>::Run, &io_service));
906
907 if (conf.Has("cmd"))
908 {
909 const vector<string> v = conf.Get<vector<string>>("cmd");
910 for (vector<string>::const_iterator it=v.begin(); it!=v.end(); it++)
911 shell.ProcessLine(*it);
912 }
913
914 if (conf.Has("exec"))
915 {
916 const vector<string> v = conf.Get<vector<string>>("exec");
917 for (vector<string>::const_iterator it=v.begin(); it!=v.end(); it++)
918 shell.Execute(*it);
919 }
920
921 if (conf.Get<bool>("quit"))
922 shell.Stop();
923
924 shell.Run(); // Run the shell
925 io_service.Stop(); // Signal Loop-thread to stop
926 // io_service.Close(); // Obsolete, done by the destructor
927
928 // Wait until the StateMachine has finished its thread
929 // before returning and destroying the dim objects which might
930 // still be in use.
931 t.join();
932
933 return 0;
934 */
935}
936
937void SetupConfiguration(Configuration &conf)
938{
939 po::options_description control("FTM control options");
940 control.add_options()
941 ("no-dim,d", po_switch(), "Disable dim services")
942 ("addr,a", var<string>("localhost:7404"), "Network address of FTM")
943 ("quiet,q", po_bool(), "Disable printing contents of all received messages (except dynamic data) in clear text.")
944 ;
945
946 conf.AddOptions(control);
947}
948
949/*
950 Extract usage clause(s) [if any] for SYNOPSIS.
951 Translators: "Usage" and "or" here are patterns (regular expressions) which
952 are used to match the usage synopsis in program output. An example from cp
953 (GNU coreutils) which contains both strings:
954 Usage: cp [OPTION]... [-T] SOURCE DEST
955 or: cp [OPTION]... SOURCE... DIRECTORY
956 or: cp [OPTION]... -t DIRECTORY SOURCE...
957 */
958void PrintUsage()
959{
960 cout <<
961 "The drivectrl is an interface to cosy.\n"
962 "\n"
963 "The default is that the program is started without user intercation. "
964 "All actions are supposed to arrive as DimCommands. Using the -c "
965 "option, a local shell can be initialized. With h or help a short "
966 "help message about the usuage can be brought to the screen.\n"
967 "\n"
968 "Usage: drivectrl [-c type] [OPTIONS]\n"
969 " or: drivectrl [OPTIONS]\n";
970 cout << endl;
971}
972
973void PrintHelp()
974{
975 /* Additional help text which is printed after the configuration
976 options goes here */
977
978 /*
979 cout << "bla bla bla" << endl << endl;
980 cout << endl;
981 cout << "Environment:" << endl;
982 cout << "environment" << endl;
983 cout << endl;
984 cout << "Examples:" << endl;
985 cout << "test exam" << endl;
986 cout << endl;
987 cout << "Files:" << endl;
988 cout << "files" << endl;
989 cout << endl;
990 */
991}
992
993int main(int argc, const char* argv[])
994{
995 Configuration conf(argv[0]);
996 conf.SetPrintUsage(PrintUsage);
997 Main::SetupConfiguration(conf);
998 SetupConfiguration(conf);
999
1000 if (!conf.DoParse(argc, argv, PrintHelp))
1001 return -1;
1002
1003 //try
1004 {
1005 // No console access at all
1006 if (!conf.Has("console"))
1007 {
1008 if (conf.Get<bool>("no-dim"))
1009 return RunShell<LocalStream, StateMachine, ConnectionDrive>(conf);
1010 else
1011 return RunShell<LocalStream, StateMachineDim, ConnectionDimDrive>(conf);
1012 }
1013 // Cosole access w/ and w/o Dim
1014 if (conf.Get<bool>("no-dim"))
1015 {
1016 if (conf.Get<int>("console")==0)
1017 return RunShell<LocalShell, StateMachine, ConnectionDrive>(conf);
1018 else
1019 return RunShell<LocalConsole, StateMachine, ConnectionDrive>(conf);
1020 }
1021 else
1022 {
1023 if (conf.Get<int>("console")==0)
1024 return RunShell<LocalShell, StateMachineDim, ConnectionDimDrive>(conf);
1025 else
1026 return RunShell<LocalConsole, StateMachineDim, ConnectionDimDrive>(conf);
1027 }
1028 }
1029 /*catch (std::exception& e)
1030 {
1031 cerr << "Exception: " << e.what() << endl;
1032 return -1;
1033 }*/
1034
1035 return 0;
1036}
Note: See TracBrowser for help on using the repository browser.