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

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