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

Last change on this file since 14640 was 14617, checked in by tbretz, 12 years ago
Fixed two compilation issues.
File size: 49.4 KB
Line 
1#include <boost/bind.hpp>
2#include <boost/regex.hpp>
3
4#ifdef HAVE_LIBNOVA
5#include <libnova/solar.h>
6#include <libnova/rise_set.h>
7#endif
8
9#ifdef HAVE_SQL
10#include "Database.h"
11#endif
12
13#include "FACT.h"
14#include "Dim.h"
15#include "Event.h"
16#include "Shell.h"
17#include "StateMachineDim.h"
18#include "Connection.h"
19#include "LocalControl.h"
20#include "Configuration.h"
21#include "Timers.h"
22#include "Console.h"
23
24#include "tools.h"
25
26#include "HeadersDrive.h"
27
28namespace ba = boost::asio;
29namespace bs = boost::system;
30namespace dummy = ba::placeholders;
31
32using namespace std;
33using namespace Drive;
34
35// ------------------------------------------------------------------------
36
37class ConnectionDrive : public Connection
38{
39 int fState;
40
41 bool fIsVerbose;
42
43 // --verbose
44 // --hex-out
45 // --dynamic-out
46 // --load-file
47 // --leds
48 // --trigger-interval
49 // --physcis-coincidence
50 // --calib-coincidence
51 // --physcis-window
52 // --physcis-window
53 // --trigger-delay
54 // --time-marker-delay
55 // --dead-time
56 // --clock-conditioner-r0
57 // --clock-conditioner-r1
58 // --clock-conditioner-r8
59 // --clock-conditioner-r9
60 // --clock-conditioner-r11
61 // --clock-conditioner-r13
62 // --clock-conditioner-r14
63 // --clock-conditioner-r15
64 // ...
65
66 virtual void UpdatePointing(const Time &, const array<double, 2> &)
67 {
68 }
69
70 virtual void UpdateTracking(const Time &, const array<double, 8> &)
71 {
72 }
73
74 virtual void UpdateStatus(const Time &, const array<uint8_t, 3> &)
75 {
76 }
77
78 virtual void UpdateStarguider(const Time &, const DimStarguider &)
79 {
80 }
81
82 virtual void UpdateTPoint(const Time &, const DimTPoint &, const string &)
83 {
84 }
85
86public:
87 virtual void UpdateSource()
88 {
89 }
90 virtual void UpdateSource(const array<double, 6> &, const string& = "")
91 {
92 }
93
94protected:
95 map<uint16_t, int> fCounter;
96
97 ba::streambuf fBuffer;
98
99public:
100 static Time ReadTime(istream &in)
101 {
102 uint16_t y, m, d, hh, mm, ss, ms;
103 in >> y >> m >> d >> hh >> mm >> ss >> ms;
104
105 return Time(y, m, d, hh, mm, ss, ms*1000);
106 }
107
108 static double ReadAngle(istream &in)
109 {
110 char sgn;
111 uint16_t d, m;
112 float s;
113
114 in >> sgn >> d >> m >> s;
115
116 const double ret = ((60.0 * (60.0 * (double)d + (double)m) + s))/3600.;
117 return sgn=='-' ? -ret : ret;
118 }
119
120 double GetDevAbs(double nomzd, double meszd, double devaz)
121 {
122 nomzd *= M_PI/180;
123 meszd *= M_PI/180;
124 devaz *= M_PI/180;
125
126 const double x = sin(meszd) * sin(nomzd) * cos(devaz);
127 const double y = cos(meszd) * cos(nomzd);
128
129 return acos(x + y) * 180/M_PI;
130 }
131
132 uint16_t fDeviationLimit;
133 uint16_t fDeviationCounter;
134 uint16_t fDeviationMax;
135
136 uint64_t fTrackingCounter;
137
138protected:
139 void HandleReceivedReport(const boost::system::error_code& err, size_t bytes_received)
140 {
141 // Do not schedule a new read if the connection failed.
142 if (bytes_received==0 || err)
143 {
144 if (err==ba::error::eof)
145 Warn("Connection closed by remote host (FTM).");
146
147 // 107: Transport endpoint is not connected (bs::error_code(107, bs::system_category))
148 // 125: Operation canceled
149 if (err && err!=ba::error::eof && // Connection closed by remote host
150 err!=ba::error::basic_errors::not_connected && // Connection closed by remote host
151 err!=ba::error::basic_errors::operation_aborted) // Connection closed by us
152 {
153 ostringstream str;
154 str << "Reading from " << URL() << ": " << err.message() << " (" << err << ")";// << endl;
155 Error(str);
156 }
157 PostClose(err!=ba::error::basic_errors::operation_aborted);
158 return;
159 }
160
161 istream is(&fBuffer);
162
163 string line;
164 getline(is, line);
165
166 if (fIsVerbose)
167 Out() << line << endl;
168
169 StartReadReport();
170
171 if (line.substr(0, 13)=="DRIVE-STATUS ")
172 {
173 Message(line.substr(70));
174 return;
175 }
176
177 if (line.substr(0, 13)=="STARG-REPORT ")
178 {
179 istringstream stream(line.substr(16));
180
181 // 0: Error
182 // 1: Standby
183 // 2: Monitoring
184 uint16_t status1;
185 stream >> status1;
186 /*const Time t1 = */ReadTime(stream);
187
188 uint16_t status2;
189 stream >> status2;
190 /*const Time t2 = */ReadTime(stream);
191
192 double misszd, missaz;
193 stream >> misszd >> missaz;
194
195 const double zd = ReadAngle(stream);
196 const double az = ReadAngle(stream);
197
198 double cx, cy;
199 stream >> cx >> cy;
200
201 int ncor;
202 stream >> ncor;
203
204 double bright, mjd;
205 stream >> bright >> mjd;
206
207 int nled, nring, nstars;
208 stream >> nled >> nring >> nstars;
209
210 if (stream.fail())
211 return;
212
213 DimStarguider data;
214
215 data.fMissZd = misszd;
216 data.fMissAz = missaz;
217 data.fNominalZd = zd;
218 data.fNominalAz = az;
219 data.fCenterX = cx;
220 data.fCenterY = cy;
221 data.fNumCorrelated = ncor;
222 data.fBrightness = bright;
223 data.fNumLeds = nled;
224 data.fNumRings = nring;
225 data.fNumStars = nstars;
226
227 UpdateStarguider(Time(mjd), data);
228
229 return;
230
231 }
232
233 if (line.substr(0, 14)=="TPOINT-REPORT ")
234 {
235 istringstream stream(line.substr(17));
236
237 uint16_t status1;
238 stream >> status1;
239 const Time t1 = ReadTime(stream);
240
241 uint16_t status2;
242 stream >> status2;
243 /*const Time t2 =*/ ReadTime(stream);
244
245 char type;
246 stream >> type;
247 if (type != 'T')
248 return;
249
250 double az1, alt1, az2, alt2, ra, dec, dzd, daz;
251 stream >> az1 >> alt1 >> az2 >> alt2 >> ra >> dec >> dzd >> daz;
252
253 // c: center, s:start
254 double mjd, cmag, smag, cx, cy, sx, sy;
255 stream >> mjd >> cmag >> smag >> cx >> cy >> sx >> sy;
256
257 int nled, nring, nstar, ncor;
258 stream >> nled >> nring >> nstar >> ncor;
259
260 double bright, mag;
261 stream >> bright >> mag;
262
263 string name;
264 stream >> name;
265
266 if (stream.fail())
267 return;
268
269 DimTPoint tpoint;
270
271 tpoint.fRa = ra;
272 tpoint.fDec = dec;
273
274 tpoint.fNominalZd = 90-alt1-dzd;
275 tpoint.fNominalAz = 90-az1 +daz;
276
277 tpoint.fPointingZd = 90-alt1;
278 tpoint.fPointingAz = az1;
279
280 tpoint.fFeedbackZd = 90-alt2;
281 tpoint.fFeedbackAz = az2;
282
283 tpoint.fNumLeds = nled;
284 tpoint.fNumRings = nring;
285
286 tpoint.fCenterX = cx;
287 tpoint.fCenterY = cy;
288 tpoint.fCenterMag = cmag;
289
290 tpoint.fStarX = sx;
291 tpoint.fStarY = sy;
292 tpoint.fStarMag = smag;
293
294 tpoint.fRealMag = mag;
295
296 UpdateTPoint(t1, tpoint, name);
297
298 return;
299 }
300
301 if (line.substr(0, 13)=="DRIVE-REPORT ")
302 {
303 // DRIVE-REPORT M1
304 // 01 2011 05 14 11 31 19 038
305 // 02 1858 11 17 00 00 00 000
306 // + 000 00 000 + 000 00 000
307 // + 000 00 000
308 // 55695.480081
309 // + 000 00 000 + 000 00 000
310 // + 000 00 000 + 000 00 000
311 // 0000.000 0000.000
312 // 0 2
313
314 // status
315 // year month day hour minute seconds millisec
316 // year month day hour minute seconds millisec
317 // ra(+ h m s) dec(+ d m s) ha(+ h m s)
318 // mjd
319 // zd(+ d m s) az(+ d m s)
320 // zd(+ d m s) az(+ d m s)
321 // zd_err az_err
322 // armed(0=unlocked, 1=locked)
323 // stgmd(0=none, 1=starguider, 2=starguider off)
324 istringstream stream(line.substr(16));
325
326 uint16_t status1;
327 stream >> status1;
328 const Time t1 = ReadTime(stream);
329
330 uint16_t status2;
331 stream >> status2;
332 /*const Time t2 =*/ ReadTime(stream);
333
334 const double ra = ReadAngle(stream);
335 const double dec = ReadAngle(stream);
336 const double ha = ReadAngle(stream);
337
338 double mjd;
339 stream >> mjd;
340
341 const double zd1 = ReadAngle(stream); // Nominal (zd/az asynchronous, dev synchronous, mjd synchronous with zd)
342 const double az1 = ReadAngle(stream); // Nominal (zd/az asynchronous, dev synchronous, mjd synchronous with z)
343 const double zd2 = ReadAngle(stream); // Masured (zd/az synchronous, dev asynchronous, mjd asynchronous)
344 const double az2 = ReadAngle(stream); // Measurd (zd/az synchronous, dev asynchronous, mjd asynchronous)
345
346 double zd_err, az_err;
347 stream >> zd_err; // Deviation = Nominal - Measured
348 stream >> az_err; // Deviation = Nominal - Measured
349
350 uint16_t armed, stgmd;
351 stream >> armed;
352 stream >> stgmd;
353
354 uint32_t pdo3;
355 stream >> hex >> pdo3;
356
357 if (stream.fail())
358 return;
359
360 // Status 0: Error
361 // Status 1: Stopped
362 // Status 3: Stopping || Moving
363 // Status 4: Tracking
364 if (status1==0)
365 status1 = StateMachineImp::kSM_Error - Drive::State::kNotReady;
366
367 const bool ready = (pdo3&0xef00ef)==0xef00ef;
368 if (!ready)
369 fState = Drive::State::kNotReady;
370 else
371 fState = status1==1 ?
372 Drive::State::kReady+armed :
373 Drive::State::kNotReady+status1;
374
375 // kDisconnected = 1,
376 // kConnected,
377 // kNotReady,
378 // kReady,
379 // kArmed,
380 // kMoving,
381 // kTracking,
382 // kOnTrack,
383
384 // pdo3:
385 // 1 Ab
386 // 2 1
387 // 4 Emergency
388 // 8 OverVolt
389 // 10 Move (Drehen-soll)
390 // 20 Af
391 // 40 1
392 // 80 Power on Az
393 // ------------------
394 // 100 NOT UPS Alarm
395 // 200 UPS on Battery
396 // 400 UPS charging
397
398 // Power cut: 2ef02ef
399 // charging: 4ef04ef
400
401 // Convert to deg
402 zd_err /= 3600;
403 az_err /= 3600;
404
405 // Calculate absolut deviation on the sky
406 const double dev = GetDevAbs(zd1, zd1-zd_err, az_err)*3600;
407
408 // If any other state than tracking or a deviation
409 // larger than 60, reset the counter
410 if (fState!=State::kTracking || dev>fDeviationLimit)
411 fTrackingCounter = 0;
412 else
413 fTrackingCounter++;
414
415 // If in tracking, at least five consecutive reports (5s)
416 // must be below 60arcsec deviation, this is considered OnTrack
417 if (fState==State::kTracking && fTrackingCounter>=fDeviationCounter)
418 fState = State::kOnTrack;
419
420 // Having th state as Tracking will reset the counter
421 if (fState==State::kOnTrack && dev>fDeviationMax)
422 fState = State::kTracking;
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, 8> track =
431 {{
432 ra, dec, ha,
433 zd1, az1,
434 zd_err, az_err,
435 dev
436 }};
437 if (mjd>0)
438 UpdateTracking(Time(mjd), track);
439
440 // ---- DIM ----> t1 as event time
441 // status1
442 // mjd
443 // ra/dec/ha
444 // zd/az (nominal)
445 // zd/az (current)
446 // err(zd/az)
447 // [armed] [stgmd]
448
449 // Maybe:
450 // POINTING_POSITION --> t1, zd/az (current), [armed, stgmd, status1]
451 //
452 // if (mjd>0)
453 // TRACKING_POSITION --> mjd, zd/az (nominal), err(zd/az)
454 // ra/dec, ha(not well defined),
455 // [Nominal + Error == Current]
456
457 // MJD is the time which corresponds to the nominal position
458 // t1 is the time which corresponds to the current position/HA
459
460 return;
461 }
462 }
463
464 void StartReadReport()
465 {
466 boost::asio::async_read_until(*this, fBuffer, '\n',
467 boost::bind(&ConnectionDrive::HandleReceivedReport, this,
468 dummy::error, dummy::bytes_transferred));
469 }
470
471 boost::asio::deadline_timer fKeepAlive;
472
473 void KeepAlive()
474 {
475 PostMessage(string("KEEP_ALIVE"));
476
477 fKeepAlive.expires_from_now(boost::posix_time::seconds(10));
478 fKeepAlive.async_wait(boost::bind(&ConnectionDrive::HandleKeepAlive,
479 this, dummy::error));
480 }
481
482 void HandleKeepAlive(const bs::error_code &error)
483 {
484 // 125: Operation canceled (bs::error_code(125, bs::system_category))
485 if (error && error!=ba::error::basic_errors::operation_aborted)
486 {
487 ostringstream str;
488 str << "Write timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
489 Error(str);
490
491 PostClose(false);
492 return;
493 }
494
495 if (!is_open())
496 {
497 // For example: Here we could schedule a new accept if we
498 // would not want to allow two connections at the same time.
499 return;
500 }
501
502 // Check whether the deadline has passed. We compare the deadline
503 // against the current time since a new asynchronous operation
504 // may have moved the deadline before this actor had a chance
505 // to run.
506 if (fKeepAlive.expires_at() > ba::deadline_timer::traits_type::now())
507 return;
508
509 KeepAlive();
510 }
511
512
513private:
514 // This is called when a connection was established
515 void ConnectionEstablished()
516 {
517 StartReadReport();
518 KeepAlive();
519 }
520
521 /*
522 void HandleReadTimeout(const bs::error_code &error)
523 {
524 if (error && error!=ba::error::basic_errors::operation_aborted)
525 {
526 stringstream str;
527 str << "Read timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
528 Error(str);
529
530 PostClose();
531 return;
532
533 }
534
535 if (!is_open())
536 {
537 // For example: Here we could schedule a new accept if we
538 // would not want to allow two connections at the same time.
539 return;
540 }
541
542 // Check whether the deadline has passed. We compare the deadline
543 // against the current time since a new asynchronous operation
544 // may have moved the deadline before this actor had a chance
545 // to run.
546 if (fInTimeout.expires_at() > ba::deadline_timer::traits_type::now())
547 return;
548
549 Error("Timeout reading data from "+URL());
550
551 PostClose();
552 }*/
553
554
555public:
556
557 static const uint16_t kMaxAddr;
558
559public:
560 ConnectionDrive(ba::io_service& ioservice, MessageImp &imp) : Connection(ioservice, imp()),
561 fState(-1), fIsVerbose(true), fDeviationLimit(120), fDeviationCounter(5), fDeviationMax(240), fTrackingCounter(0), fKeepAlive(ioservice)
562 {
563 SetLogStream(&imp);
564 }
565
566 void SetVerbose(bool b)
567 {
568 fIsVerbose = b;
569 }
570
571 void SetDeviationCondition(uint16_t limit, uint16_t counter, uint16_t max)
572 {
573 fDeviationLimit = limit;
574 fDeviationCounter = counter;
575 fDeviationMax = max;
576 }
577 int GetState() const
578 {
579 if (!IsConnected())
580 return 1;
581 if (IsConnected() && fState<0)
582 return 2;
583 return fState;
584 }
585};
586
587const uint16_t ConnectionkMaxAddr = 0xfff;
588
589// ------------------------------------------------------------------------
590
591#include "DimDescriptionService.h"
592
593class ConnectionDimDrive : public ConnectionDrive
594{
595private:
596 DimDescribedService fDimPointing;
597 DimDescribedService fDimTracking;
598 DimDescribedService fDimSource;
599 DimDescribedService fDimTPoint;
600 DimDescribedService fDimStatus;
601
602 void UpdatePointing(const Time &t, const array<double, 2> &arr)
603 {
604 fDimPointing.setData(arr);
605 fDimPointing.Update(t);
606 }
607
608 void UpdateTracking(const Time &t,const array<double, 8> &arr)
609 {
610 fDimTracking.setData(arr);
611 fDimTracking.Update(t);
612 }
613
614 void UpdateStatus(const Time &t, const array<uint8_t, 3> &arr)
615 {
616 fDimStatus.setData(arr);
617 fDimStatus.Update(t);
618 }
619
620 void UpdateTPoint(const Time &t, const DimTPoint &data,
621 const string &name)
622 {
623 vector<char> dim(sizeof(data)+name.length()+1);
624 memcpy(dim.data(), &data, sizeof(data));
625 memcpy(dim.data()+sizeof(data), name.c_str(), name.length()+1);
626
627 fDimTPoint.setData(dim);
628 fDimTPoint.Update(t);
629 }
630
631public:
632 ConnectionDimDrive(ba::io_service& ioservice, MessageImp &imp) :
633 ConnectionDrive(ioservice, imp),
634 fDimPointing("DRIVE_CONTROL/POINTING_POSITION", "D:1;D:1",
635 "|Zd[deg]:Zenith distance (encoder readout)"
636 "|Az[deg]:Azimuth angle (encoder readout)"),
637 fDimTracking("DRIVE_CONTROL/TRACKING_POSITION", "D:1;D:1;D:1;D:1;D:1;D:1;D:1;D:1",
638 "|Ra[h]:Command right ascension"
639 "|Dec[deg]:Command declination"
640 "|Ha[h]:Corresponding hour angle"
641 "|Zd[deg]:Nominal zenith distance"
642 "|Az[deg]:Nominal azimuth angle"
643 "|dZd[deg]:Control deviation Zd"
644 "|dAz[deg]:Control deviation Az"
645 "|dev[arcsec]:Absolute control deviation"),
646 fDimSource("DRIVE_CONTROL/SOURCE_POSITION", "D:1;D:1;D:1;D:1;D:1;D:1;C:31",
647 "|Ra_src[h]:Source right ascension"
648 "|Dec_src[deg]:Source declination"
649 "|Ra_cmd[h]:Command right ascension"
650 "|Dec_cmd[deg]:Command declination"
651 "|Offset[deg]:Wobble offset"
652 "|Angle[deg]:Wobble angle"
653 "|Name[string]:Source name if available"),
654 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",
655 "|Ra[h]:Command right ascension"
656 "|Dec[deg]:Command declination"
657 "|Zd_nom[deg]:Nominal zenith distance"
658 "|Az_nom[deg]:Nominal azimuth angle"
659 "|Zd_cur[deg]:Current zenith distance (calculated from image)"
660 "|Az_cur[deg]:Current azimuth angle (calculated from image)"
661 "|Zd_enc[deg]:Feedback zenith axis (from encoder)"
662 "|Az_enc[deg]:Feedback azimuth angle (from encoder)"
663 "|N_leds[cnt]:Number of detected LEDs"
664 "|N_rings[cnt]:Number of rings used to calculate the camera center"
665 "|Xc[pix]:X position of center in CCD camera frame"
666 "|Yc[pix]:Y position of center in CCD camera frame"
667 "|Ic[au]:Average intensity (LED intensity weighted with their frequency of occurance in the calculation)"
668 "|Xs[pix]:X position of start in CCD camera frame"
669 "|Ys[pix]:Y position of star in CCD camera frame"
670 "|Ms[mag]:Artifical magnitude of star (calculated form image))"
671 "|Mc[mag]:Catalog magnitude of star"),
672 fDimStatus("DRIVE_CONTROL/STATUS", "C:2;C:1", "")
673
674 {
675 }
676
677 void UpdateSource()
678 {
679 const vector<char> empty(6*sizeof(double)+31, 0);
680 fDimSource.setQuality(0);
681 fDimSource.Update(empty);
682 }
683
684 void UpdateSource(const array<double, 6> &arr, const string &name="")
685 {
686 vector<char> dat(6*sizeof(double)+31, 0);
687 memcpy(dat.data(), arr.data(), 6*sizeof(double));
688 strncpy(dat.data()+6*sizeof(double), name.c_str(), 30);
689
690 fDimSource.setQuality(1);
691 fDimSource.Update(dat);
692 }
693
694 // 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
695};
696
697// ------------------------------------------------------------------------
698
699struct Source
700{
701 Source() : ra(0), dec(0), offset(0)
702 {
703 angle[0] = angle[1] = 0;
704 }
705
706 double ra;
707 double dec;
708 double offset;
709 array<double, 2> angle;
710};
711
712
713template <class T, class S>
714class StateMachineDrive : public T, public ba::io_service, public ba::io_service::work
715{
716private:
717 S fDrive;
718
719 string fDatabase;
720
721 typedef map<string, Source> sources;
722 sources fSources;
723
724 string fLastCommand; // Last tracking (RADEC) command
725 int fAutoResume; // 0: disabled, 1: enables, 2: resuming
726
727 // Status 0: Error
728 // Status 1: Unlocked
729 // Status 2: Locked
730 // Status 3: Stopping || Moving
731 // Status 4: Tracking
732
733 bool CheckEventSize(size_t has, const char *name, size_t size)
734 {
735 if (has==size)
736 return true;
737
738 ostringstream msg;
739 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
740 T::Fatal(msg);
741 return false;
742 }
743
744 enum Coordinates
745 {
746 kPoint,
747 kTrackSlow,
748 kTrackFast
749 };
750
751 string AngleToStr(double angle)
752 {
753 /* Handle sign */
754 const char sgn = angle<0?'-':'+';
755
756 /* Round interval and express in smallest units required */
757 double a = round(3600. * fabs(angle)); // deg to seconds
758
759 /* Separate into fields */
760 const double ad = trunc(a/3600.);
761 a -= ad * 3600.;
762 const double am = trunc(a/60.);
763 a -= am * 60.;
764 const double as = trunc(a);
765
766 /* Return results */
767 ostringstream str;
768 str << sgn << " " << uint16_t(ad) << " " << uint16_t(am) << " " << as;
769 return str.str();
770 }
771
772 int SendCommand(const string &str, bool upd=true)
773 {
774 // This happens if fLastCommand should be send,
775 // but the last command was not a tracking command
776 if (str.empty())
777 {
778 T::Info("Last command was not a tracking command. RESUME ignored.");
779 return T::GetCurrentState();
780 }
781
782 fLastCommand = str.compare(0, 6, "RADEC ")==0 ? str : "";
783
784 fDrive.PostMessage(str);
785 T::Message("Sending: "+str);
786
787 if (upd)
788 fDrive.UpdateSource();
789
790 return T::GetCurrentState();
791 }
792
793 int Resume()
794 {
795 if (fLastCommand.empty())
796 {
797 T::Info("Last command was not a tracking command. RESUME ignored.");
798 return T::GetCurrentState();
799 }
800
801 return SendCommand(fLastCommand, false);
802 }
803
804 int SendCoordinates(const EventImp &evt, const Coordinates type)
805 {
806 if (!CheckEventSize(evt.GetSize(), "SendCoordinates", 16))
807 return T::kSM_FatalError;
808
809 const double *dat = evt.Ptr<double>();
810
811 string command;
812
813 switch (type)
814 {
815 case kPoint: command += "ZDAZ "; break;
816 case kTrackSlow: command += "RADEC "; break;
817 case kTrackFast: command += "GRB "; break;
818 }
819
820 if (type!=kPoint)
821 {
822 const array<double, 6> dim = {{ dat[0], dat[1], dat[0], dat[1], 0, 0 }};
823 fDrive.UpdateSource(dim);
824 }
825
826 command += AngleToStr(dat[0]) + ' ' + AngleToStr(dat[1]);
827 return SendCommand(command, type==kPoint);
828 }
829
830 int StartWobble(const double &srcra, const double &srcdec,
831 const double &woboff, const double &wobang,
832 const string name="")
833 {
834 const double ra = srcra *M_PI/12;
835 const double dec = srcdec*M_PI/180;
836 const double off = woboff*M_PI/180;
837 const double dir = wobang*M_PI/180;
838
839 const double cosdir = cos(dir);
840 const double sindir = sin(dir);
841 const double cosoff = cos(off);
842 const double sinoff = sin(off);
843 const double cosdec = cos(dec);
844 const double sindec = sin(dec);
845
846 if (off==0)
847 {
848 const array<double, 6> dim = {{ srcra, srcdec, srcra, srcdec, 0, 0 }};
849 fDrive.UpdateSource(dim, name);
850
851 string command = "RADEC ";
852 command += AngleToStr(srcra) + ' ' + AngleToStr(srcdec);
853 return SendCommand(command, false);
854 }
855
856 const double sintheta = sindec*cosoff + cosdec*sinoff*cosdir;
857 if (sintheta >= 1)
858 {
859 T::Error("cos(Zd) > 1");
860 return T::GetCurrentState();
861 }
862
863 const double costheta = sqrt(1 - sintheta*sintheta);
864
865 const double cosdeltara = (cosoff - sindec*sintheta)/(cosdec*costheta);
866 const double sindeltara = sindir*sinoff/costheta;
867
868 const double ndec = asin(sintheta)*180/M_PI;
869 const double nra = (atan2(sindeltara, cosdeltara) + ra)*12/M_PI;
870
871 const array<double, 6> dim = {{ srcra, srcdec, nra, ndec, woboff, wobang }};
872 fDrive.UpdateSource(dim, name);
873
874 string command = "RADEC ";
875 command += AngleToStr(nra) + ' ' + AngleToStr(ndec);
876 return SendCommand(command, false);
877 }
878
879 int Wobble(const EventImp &evt)
880 {
881 if (!CheckEventSize(evt.GetSize(), "Wobble", 32))
882 return T::kSM_FatalError;
883
884 const double *dat = evt.Ptr<double>();
885
886 return StartWobble(dat[0], dat[1], dat[2], dat[3]);
887 }
888
889 const sources::const_iterator GetSourceFromDB(const char *ptr, const char *last)
890 {
891 if (find(ptr, last, '\0')==last)
892 {
893 T::Fatal("TrackWobble - The name transmitted by dim is not null-terminated.");
894 throw uint32_t(T::kSM_FatalError);
895 }
896
897 const string name(ptr);
898
899 const sources::const_iterator it = fSources.find(name);
900 if (it==fSources.end())
901 {
902 T::Error("Source '"+name+"' not found in list.");
903 throw uint32_t(T::GetCurrentState());
904 }
905
906 return it;
907 }
908
909 int TrackWobble(const EventImp &evt)
910 {
911 if (evt.GetSize()<=2)
912 {
913 ostringstream msg;
914 msg << "Track - Received event has " << evt.GetSize() << " bytes, but expected at least 3.";
915 T::Fatal(msg);
916 return T::kSM_FatalError;
917 }
918
919 const uint16_t wobble = evt.GetUShort();
920 if (wobble!=1 && wobble!=2)
921 {
922 ostringstream msg;
923 msg << "TrackWobble - Wobble id " << wobble << " undefined, only 1 and 2 allowed.";
924 T::Error(msg);
925 return T::GetCurrentState();
926 }
927
928 const char *ptr = evt.Ptr<char>(2);
929 const char *last = ptr+evt.GetSize()-2;
930
931 try
932 {
933 const sources::const_iterator it = GetSourceFromDB(ptr, last);
934
935 const string &name = it->first;
936 const Source &src = it->second;
937
938 return StartWobble(src.ra, src.dec, src.offset, src.angle[wobble-1], name);
939 }
940 catch (const uint32_t &e)
941 {
942 return e;
943 }
944 }
945
946 int StartTrackWobble(const char *ptr, size_t size, const double &offset=0, const double &angle=0)
947 {
948 const char *last = ptr+size;
949
950 try
951 {
952 const sources::const_iterator it = GetSourceFromDB(ptr, last);
953
954 const string &name = it->first;
955 const Source &src = it->second;
956
957 return StartWobble(src.ra, src.dec, offset, angle, name);
958 }
959 catch (const uint32_t &e)
960 {
961 return e;
962 }
963
964 }
965
966 int Track(const EventImp &evt)
967 {
968 if (evt.GetSize()<=16)
969 {
970 ostringstream msg;
971 msg << "Track - Received event has " << evt.GetSize() << " bytes, but expected at least 17.";
972 T::Fatal(msg);
973 return T::kSM_FatalError;
974 }
975
976 const double *dat = evt.Ptr<double>();
977 const char *ptr = evt.Ptr<char>(16);
978 const size_t size = evt.GetSize()-16;
979
980 return StartTrackWobble(ptr, size, dat[0], dat[1]);
981 }
982
983 int TrackOn(const EventImp &evt)
984 {
985 if (evt.GetSize()==0)
986 {
987 ostringstream msg;
988 msg << "TrackOn - Received event has " << evt.GetSize() << " bytes, but expected at least 1.";
989 T::Fatal(msg);
990 return T::kSM_FatalError;
991 }
992
993 return StartTrackWobble(evt.Ptr<char>(), evt.GetSize());
994 }
995
996
997 int TakeTPoint(const EventImp &evt)
998 {
999 if (evt.GetSize()<=4)
1000 {
1001 ostringstream msg;
1002 msg << "TakePoint - Received event has " << evt.GetSize() << " bytes, but expected at least 5.";
1003 T::Fatal(msg);
1004 return T::kSM_FatalError;
1005 }
1006
1007 const float mag = evt.Get<float>();
1008 const char *ptr = evt.Ptr<char>(4);
1009 const size_t size = evt.GetSize()-4;
1010
1011 string src(ptr, size);
1012
1013 while (src.find_first_of(' '))
1014 src.erase(src.find_first_of(' '), 1);
1015
1016 SendCommand("TPOIN "+src+" "+to_string(mag), false);;
1017
1018 return T::GetCurrentState();
1019 }
1020
1021 int SetLedBrightness(const EventImp &evt)
1022 {
1023 if (!CheckEventSize(evt.GetSize(), "SetLedBrightness", 8))
1024 return T::kSM_FatalError;
1025
1026 const uint32_t *led = evt.Ptr<uint32_t>();
1027
1028 ostringstream cmd;
1029 cmd << "LEDS " << led[0] << " " << led[1];
1030 return SendCommand(cmd.str(), false);
1031 }
1032
1033
1034 int SetVerbosity(const EventImp &evt)
1035 {
1036 if (!CheckEventSize(evt.GetSize(), "SetVerbosity", 1))
1037 return T::kSM_FatalError;
1038
1039 fDrive.SetVerbose(evt.GetBool());
1040
1041 return T::GetCurrentState();
1042 }
1043
1044 int SetAutoResume(const EventImp &evt)
1045 {
1046 if (!CheckEventSize(evt.GetSize(), "SetAutoResume", 1))
1047 return T::kSM_FatalError;
1048
1049 fAutoResume = evt.GetBool();
1050
1051 return T::GetCurrentState();
1052 }
1053
1054 int Unlock()
1055 {
1056 return Drive::State::kNotReady;
1057 }
1058
1059 int Print()
1060 {
1061 for (auto it=fSources.begin(); it!=fSources.end(); it++)
1062 {
1063 const string &name = it->first;
1064 const Source &src = it->second;
1065
1066 T::Out() << name << ",";
1067 T::Out() << src.ra << "," << src.dec << "," << src.offset << ",";
1068 T::Out() << src.angle[0] << "," << src.angle[1] << endl;
1069 }
1070 return T::GetCurrentState();
1071 }
1072
1073 int ReloadSources()
1074 {
1075 try
1076 {
1077 ReadDatabase();
1078 }
1079 catch (const exception &e)
1080 {
1081 T::Error("Reading sources from databse failed: "+string(e.what()));
1082 }
1083 return T::GetCurrentState();
1084 }
1085
1086 int Disconnect()
1087 {
1088 // Close all connections
1089 fDrive.PostClose(false);
1090
1091 /*
1092 // Now wait until all connection have been closed and
1093 // all pending handlers have been processed
1094 poll();
1095 */
1096
1097 return T::GetCurrentState();
1098 }
1099
1100 int Reconnect(const EventImp &evt)
1101 {
1102 // Close all connections to supress the warning in SetEndpoint
1103 fDrive.PostClose(false);
1104
1105 // Now wait until all connection have been closed and
1106 // all pending handlers have been processed
1107 poll();
1108
1109 if (evt.GetBool())
1110 fDrive.SetEndpoint(evt.GetString());
1111
1112 // Now we can reopen the connection
1113 fDrive.PostClose(true);
1114
1115 return T::GetCurrentState();
1116 }
1117
1118 Time fSunRise;
1119
1120 Time GetSunRise(const Time &time=Time())
1121 {
1122#ifdef HAVE_LIBNOVA
1123 const double lon = -(17.+53./60+26.525/3600);
1124 const double lat = 28.+45./60+42.462/3600;
1125
1126 ln_lnlat_posn observer;
1127 observer.lng = lon;
1128 observer.lat = lat;
1129
1130 // This caluclates the sun-rise of the next day after 12:00 noon
1131 ln_rst_time sun_day;
1132 if (ln_get_solar_rst(time.JD(), &observer, &sun_day)==1)
1133 {
1134 T::Fatal("GetSunRise reported the sun to be circumpolar!");
1135 return Time(Time::none);
1136 }
1137
1138 if (Time(sun_day.rise)>=time)
1139 return Time(sun_day.rise);
1140
1141 if (ln_get_solar_rst(time.JD()+0.5, &observer, &sun_day)==1)
1142 {
1143 T::Fatal("GetSunRise reported the sun to be circumpolar!");
1144 return Time(Time::none);
1145 }
1146
1147 return Time(sun_day.rise);
1148#else
1149 return Time(boost::date_time::pos_infin);
1150#endif
1151 }
1152
1153 int Execute()
1154 {
1155 // Dispatch (execute) at most one handler from the queue. In contrary
1156 // to run_one(), it doesn't wait until a handler is available
1157 // which can be dispatched, so poll_one() might return with 0
1158 // handlers dispatched. The handlers are always dispatched/executed
1159 // synchronously, i.e. within the call to poll_one()
1160 poll_one();
1161
1162 if (T::GetCurrentState()==Drive::State::kLocked)
1163 return Drive::State::kLocked;
1164
1165
1166 if (T::GetCurrentState()>Drive::State::kLocked)
1167 {
1168 Time now;
1169 if (now>fSunRise)
1170 {
1171 SendCommand("PREPS Park", false);
1172
1173 fSunRise = GetSunRise(now);
1174 if (!fSunRise)
1175 return T::kSM_FatalError;
1176
1177 ostringstream msg;
1178 msg << "Next sun-rise will be at " << fSunRise;
1179 T::Info(msg);
1180
1181 return Drive::State::kLocked;
1182 }
1183 }
1184
1185 const int state = fDrive.GetState();
1186
1187 if (!fLastCommand.empty())
1188 {
1189 // If auto resume is enabled and the drive is in error,
1190 // resume tracking
1191 if (fAutoResume==1 && state==StateMachineImp::kSM_Error)
1192 {
1193 Resume();
1194 fAutoResume = 2;
1195 }
1196
1197 // If drive got out of the error state,
1198 // enable auto resume again
1199 if (fAutoResume==2 && state!=StateMachineImp::kSM_Error)
1200 fAutoResume = 1;
1201 }
1202
1203 return state;
1204 }
1205
1206
1207public:
1208 StateMachineDrive(ostream &out=cout) :
1209 T(out, "DRIVE_CONTROL"), ba::io_service::work(static_cast<ba::io_service&>(*this)),
1210 fDrive(*this, *this), fAutoResume(false), fSunRise(GetSunRise())
1211 {
1212 // State names
1213 T::AddStateName(State::kDisconnected, "Disconnected",
1214 "No connection to cosy");
1215
1216 T::AddStateName(State::kConnected, "Connected",
1217 "Cosy connected, drive stopped");
1218
1219 T::AddStateName(State::kNotReady, "NotReady",
1220 "Drive system not ready for movement");
1221
1222 T::AddStateName(State::kLocked, "Locked",
1223 "Drive system is locked (will not accept commands)");
1224
1225 T::AddStateName(State::kReady, "Ready",
1226 "Drive system ready for movement");
1227
1228 T::AddStateName(State::kArmed, "Armed",
1229 "Cosy armed, drive stopped");
1230
1231 T::AddStateName(State::kMoving, "Moving",
1232 "Telescope moving");
1233
1234 T::AddStateName(State::kTracking, "Tracking",
1235 "Telescope is in tracking mode");
1236
1237 T::AddStateName(State::kOnTrack, "OnTrack",
1238 "Telescope tracking stable");
1239
1240 // State::kIdle
1241 // State::kArmed
1242 // State::kMoving
1243 // State::kTracking
1244
1245 // Init
1246 // -----------
1247 // "ARM lock"
1248 // "STGMD off"
1249
1250 /*
1251 [ ] WAIT -> WM_WAIT
1252 [x] STOP! -> WM_STOP
1253 [x] RADEC ra(+ d m s.f) dec(+ d m s.f)
1254 [x] GRB ra(+ d m s.f) dec(+ d m s.f)
1255 [x] ZDAZ zd(+ d m s.f) az (+ d m s.f)
1256 [ ] CELEST id offset angle
1257 [ ] MOON wobble offset
1258 [ ] PREPS string
1259 [ ] TPOIN star mag
1260 [ ] ARM lock/unlock
1261 [ ] STGMD on/off
1262 */
1263
1264 // Drive Commands
1265 T::AddEvent("MOVE_TO", "D:2", State::kArmed) // ->ZDAZ
1266 (bind(&StateMachineDrive::SendCoordinates, this, placeholders::_1, kPoint))
1267 ("Move the telescope to the given local coordinates"
1268 "|Zd[deg]:Zenith distance"
1269 "|Az[deg]:Azimuth");
1270
1271 T::AddEvent("TRACK", "D:2", State::kArmed, State::kTracking, State::kOnTrack) // ->RADEC/GRB
1272 (bind(&StateMachineDrive::SendCoordinates, this, placeholders::_1, kTrackSlow))
1273 ("Move the telescope to the given sky coordinates and start tracking them"
1274 "|Ra[h]:Right ascension"
1275 "|Dec[deg]:Declination");
1276
1277 T::AddEvent("WOBBLE", "D:4", State::kArmed, State::kTracking, State::kOnTrack) // ->RADEC/GRB
1278 (bind(&StateMachineDrive::Wobble, this, placeholders::_1))
1279 ("Move the telescope to the given wobble position around the given sky coordinates and start tracking them"
1280 "|Ra[h]:Right ascension"
1281 "|Dec[deg]:Declination"
1282 "|Offset[deg]:Wobble offset"
1283 "|Angle[deg]:Wobble angle");
1284
1285 T::AddEvent("TRACK_SOURCE", "D:2;C", State::kArmed, State::kTracking, State::kOnTrack) // ->RADEC/GRB
1286 (bind(&StateMachineDrive::Track, this, placeholders::_1))
1287 ("Move the telescope to the given wobble position around the given source and start tracking"
1288 "|Offset[deg]:Wobble offset"
1289 "|Angle[deg]:Wobble angle"
1290 "|Name[string]:Source name");
1291
1292 T::AddEvent("TRACK_WOBBLE", "S:1;C", State::kArmed, State::kTracking, State::kOnTrack) // ->RADEC/GRB
1293 (bind(&StateMachineDrive::TrackWobble, this, placeholders::_1))
1294 ("Move the telescope to the given wobble position around the given source and start tracking"
1295 "|id:Wobble angle id (1 or 2)"
1296 "|Name[string]:Source name");
1297
1298 T::AddEvent("TRACK_ON", "S:1;C", State::kArmed, State::kTracking, State::kOnTrack) // ->RADEC/GRB
1299 (bind(&StateMachineDrive::TrackOn, this, placeholders::_1))
1300 ("Move the telescope to the given position and start tracking"
1301 "|Name[string]:Source name");
1302
1303 T::AddEvent("RESUME", StateMachineImp::kSM_Error)
1304 (bind(&StateMachineDrive::Resume, this))
1305 ("If drive is in Error state, this can b used to resume the last tracking command, if the last command sent to cosy was a tracking command.");
1306
1307 T::AddEvent("MOON", State::kArmed, State::kTracking, State::kOnTrack)
1308 (bind(&StateMachineDrive::SendCommand, this, "MOON 0 0", true))
1309 ("Start tracking the moon");
1310 T::AddEvent("VENUS", State::kArmed, State::kTracking, State::kOnTrack)
1311 (bind(&StateMachineDrive::SendCommand, this, "CELEST 2 0 0", true))
1312 ("Start tracking Venus");
1313 T::AddEvent("MARS", State::kArmed, State::kTracking, State::kOnTrack)
1314 (bind(&StateMachineDrive::SendCommand, this, "CELEST 4 0 0", true))
1315 ("Start tracking Mars");
1316 T::AddEvent("JUPITER", State::kArmed, State::kTracking, State::kOnTrack)
1317 (bind(&StateMachineDrive::SendCommand, this, "CELEST 5 0 0", true))
1318 ("Start tracking Jupiter");
1319 T::AddEvent("SATURN", State::kArmed, State::kTracking, State::kOnTrack)
1320 (bind(&StateMachineDrive::SendCommand, this, "CELEST 6 0 0", true))
1321 ("Start tracking Saturn");
1322
1323 T::AddEvent("PARK", State::kArmed, State::kMoving, State::kTracking, State::kOnTrack, 0x100)
1324 (bind(&StateMachineDrive::SendCommand, this, "PREPS Park", false))
1325 ("Park the telescope");
1326
1327 T::AddEvent("TAKE_TPOINT")
1328 (bind(&StateMachineDrive::SendCommand, this, "TPOIN FACT 0", false))
1329 ("Take a TPoint");
1330
1331 T::AddEvent("TPOINT", "F:1;C")
1332 (bind(&StateMachineDrive::TakeTPoint, this, placeholders::_1))
1333 ("Take a TPoint (given values will be written to the TPoint files)"
1334 "|mag[float]:Magnitude of the star"
1335 "|name[string]:Name of the star");
1336
1337 T::AddEvent("SET_LED_BRIGHTNESS", "I:2")
1338 (bind(&StateMachineDrive::SetLedBrightness, this, placeholders::_1))
1339 ("Set the LED brightness of the top and bottom leds"
1340 "|top[au]:Allowed range 0-32767 for top LEDs"
1341 "|bot[au]:Allowed range 0-32767 for bottom LEDs");
1342
1343 T::AddEvent("LEDS_OFF")
1344 (bind(&StateMachineDrive::SendCommand, this, "LEDS 0 0", false))
1345 ("Switch off TPoint LEDs");
1346
1347 T::AddEvent("STOP")
1348 (bind(&StateMachineDrive::SendCommand, this, "STOP!", true))
1349 ("Stop any kind of movement.");
1350
1351// T::AddEvent("ARM", State::kConnected)
1352// (bind(&StateMachineSendCommand, this, "ARM lock"))
1353// ("");
1354
1355 T::AddEvent("UNLOCK", Drive::State::kLocked)
1356 (bind(&StateMachineDrive::Unlock, this))
1357 ("Unlock locked state.");
1358
1359 T::AddEvent("SET_AUTORESUME", "B")
1360 (bind(&StateMachineDrive::SetAutoResume, this, placeholders::_1))
1361 ("Enable/disable auto resume"
1362 "|resume[bool]:if enabled, drive is tracking and goes to error state, the last tracking command is repeated automatically.");
1363
1364 // Verbosity commands
1365 T::AddEvent("SET_VERBOSE", "B")
1366 (bind(&StateMachineDrive::SetVerbosity, this, placeholders::_1))
1367 ("Set verbosity state"
1368 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
1369
1370 // Conenction commands
1371 T::AddEvent("DISCONNECT", State::kConnected, State::kArmed)
1372 (bind(&StateMachineDrive::Disconnect, this))
1373 ("disconnect from ethernet");
1374
1375 T::AddEvent("RECONNECT", "O", State::kDisconnected, State::kConnected, State::kArmed)
1376 (bind(&StateMachineDrive::Reconnect, this, placeholders::_1))
1377 ("(Re)connect ethernet connection to FTM, a new address can be given"
1378 "|[host][string]:new ethernet address in the form <host:port>");
1379
1380
1381 T::AddEvent("PRINT")
1382 (bind(&StateMachineDrive::Print, this))
1383 ("Print source list.");
1384
1385 T::AddEvent("RELOAD_SOURCES")
1386 (bind(&StateMachineDrive::ReloadSources, this))
1387 ("Reload sources from database after database has changed..");
1388
1389 fDrive.StartConnect();
1390 }
1391
1392 void SetEndpoint(const string &url)
1393 {
1394 fDrive.SetEndpoint(url);
1395 }
1396
1397 void ReadDatabase(bool print=true)
1398 {
1399#ifdef HAVE_SQL
1400 Database db(fDatabase);
1401
1402 T::Message("Connected to '"+db.uri()+"'");
1403
1404 const mysqlpp::StoreQueryResult res =
1405 db.query("SELECT fSourceName, fRightAscension, fDeclination FROM source").store();
1406
1407 fSources.clear();
1408 for (vector<mysqlpp::Row>::const_iterator v=res.begin(); v<res.end(); v++)
1409 {
1410 Source src;
1411 src.ra = (*v)[1];
1412 src.dec = (*v)[2];
1413 const string name = (*v)[0].c_str();
1414
1415 // FIXME: Check double names
1416 fSources[name] = src;
1417
1418 if (print)
1419 {
1420 ostringstream msg;
1421 msg << " " << name << setprecision(8) << ": Ra=" << src.ra << "h Dec=" << src.dec << "deg";
1422 T::Message(msg);
1423 }
1424 }
1425#else
1426 T::Warn("MySQL support not compiled into the program.");
1427#endif
1428 }
1429
1430 int EvalOptions(Configuration &conf)
1431 {
1432 if (!fSunRise)
1433 return 1;
1434
1435 fDrive.SetVerbose(!conf.Get<bool>("quiet"));
1436
1437 const vector<string> &vec = conf.Vec<string>("source");
1438
1439 for (vector<string>::const_iterator it=vec.begin(); it!=vec.end(); it++)
1440 {
1441 istringstream stream(*it);
1442
1443 string name;
1444 double ra=0;
1445 double dec=0;
1446
1447 int i=0;
1448
1449 string buffer;
1450 while (getline(stream, buffer, ','))
1451 {
1452 istringstream is(buffer);
1453
1454 switch (i++)
1455 {
1456 case 0: name = buffer; break;
1457 case 1: ra = ConnectionDrive::ReadAngle(is); break;
1458 case 2: dec = ConnectionDrive::ReadAngle(is); break;
1459 }
1460
1461 if (is.fail())
1462 break;
1463 }
1464
1465 if (i==3)
1466 {
1467 Source src;
1468 src.ra = ra;
1469 src.dec = dec;
1470
1471 // FIXME: Check double names
1472 fSources[name] = src;
1473 }
1474 }
1475
1476 fDrive.SetDeviationCondition(conf.Get<uint16_t>("deviation-limit"),
1477 conf.Get<uint16_t>("deviation-count"),
1478 conf.Get<uint16_t>("deviation-max"));
1479
1480 fAutoResume = conf.Get<bool>("auto-resume");
1481
1482 if (conf.Has("source-database"))
1483 {
1484 fDatabase = conf.Get<string>("source-database");
1485 ReadDatabase();
1486 }
1487
1488 if (fSunRise.IsValid())
1489 {
1490 ostringstream msg;
1491 msg << "Next sun-rise will be at " << fSunRise;
1492 T::Message(msg);
1493 }
1494
1495 // The possibility to connect should be last, so that
1496 // everything else is already initialized.
1497 SetEndpoint(conf.Get<string>("addr"));
1498
1499 return -1;
1500 }
1501};
1502
1503// ------------------------------------------------------------------------
1504
1505#include "Main.h"
1506
1507
1508template<class T, class S, class R>
1509int RunShell(Configuration &conf)
1510{
1511 return Main::execute<T, StateMachineDrive<S, R>>(conf);
1512}
1513
1514void SetupConfiguration(Configuration &conf)
1515{
1516 const string def = "localhost:7404";
1517
1518 po::options_description control("Drive control options");
1519 control.add_options()
1520 ("no-dim,d", po_switch(), "Disable dim services")
1521 ("addr,a", var<string>(def), "Network address of cosy")
1522 ("quiet,q", po_bool(true), "Disable printing contents of all received messages (except dynamic data) in clear text.")
1523 ("source-database", var<string>(), "Database link as in\n\tuser:password@server[:port]/database.")
1524 ("source", vars<string>(), "Additional source entry in the form \"name,hh:mm:ss,dd:mm:ss\"")
1525 ("deviation-limit", var<uint16_t>(60), "Deviation limit in arcsec to get 'OnTrack'")
1526 ("deviation-count", var<uint16_t>(3), "Minimum number of reported deviation below deviation-limit to get 'OnTrack'")
1527 ("deviation-max", var<uint16_t>(120), "Maximum deviation in arcsec allowed to keep status 'OnTrack'")
1528 ("auto-resume", po_bool(false), "Enable auto result during tracking if connection is lost")
1529 ;
1530
1531 conf.AddOptions(control);
1532}
1533
1534/*
1535 Extract usage clause(s) [if any] for SYNOPSIS.
1536 Translators: "Usage" and "or" here are patterns (regular expressions) which
1537 are used to match the usage synopsis in program output. An example from cp
1538 (GNU coreutils) which contains both strings:
1539 Usage: cp [OPTION]... [-T] SOURCE DEST
1540 or: cp [OPTION]... SOURCE... DIRECTORY
1541 or: cp [OPTION]... -t DIRECTORY SOURCE...
1542 */
1543void PrintUsage()
1544{
1545 cout <<
1546 "The drivectrl is an interface to cosy.\n"
1547 "\n"
1548 "The default is that the program is started without user intercation. "
1549 "All actions are supposed to arrive as DimCommands. Using the -c "
1550 "option, a local shell can be initialized. With h or help a short "
1551 "help message about the usuage can be brought to the screen.\n"
1552 "\n"
1553 "Usage: drivectrl [-c type] [OPTIONS]\n"
1554 " or: drivectrl [OPTIONS]\n";
1555 cout << endl;
1556}
1557
1558void PrintHelp()
1559{
1560 Main::PrintHelp<StateMachineDrive<StateMachine,ConnectionDrive>>();
1561
1562 /* Additional help text which is printed after the configuration
1563 options goes here */
1564
1565 /*
1566 cout << "bla bla bla" << endl << endl;
1567 cout << endl;
1568 cout << "Environment:" << endl;
1569 cout << "environment" << endl;
1570 cout << endl;
1571 cout << "Examples:" << endl;
1572 cout << "test exam" << endl;
1573 cout << endl;
1574 cout << "Files:" << endl;
1575 cout << "files" << endl;
1576 cout << endl;
1577 */
1578}
1579
1580int main(int argc, const char* argv[])
1581{
1582 Configuration conf(argv[0]);
1583 conf.SetPrintUsage(PrintUsage);
1584 Main::SetupConfiguration(conf);
1585 SetupConfiguration(conf);
1586
1587 if (!conf.DoParse(argc, argv, PrintHelp))
1588 return 127;
1589
1590 //try
1591 {
1592 // No console access at all
1593 if (!conf.Has("console"))
1594 {
1595 if (conf.Get<bool>("no-dim"))
1596 return RunShell<LocalStream, StateMachine, ConnectionDrive>(conf);
1597 else
1598 return RunShell<LocalStream, StateMachineDim, ConnectionDimDrive>(conf);
1599 }
1600 // Cosole access w/ and w/o Dim
1601 if (conf.Get<bool>("no-dim"))
1602 {
1603 if (conf.Get<int>("console")==0)
1604 return RunShell<LocalShell, StateMachine, ConnectionDrive>(conf);
1605 else
1606 return RunShell<LocalConsole, StateMachine, ConnectionDrive>(conf);
1607 }
1608 else
1609 {
1610 if (conf.Get<int>("console")==0)
1611 return RunShell<LocalShell, StateMachineDim, ConnectionDimDrive>(conf);
1612 else
1613 return RunShell<LocalConsole, StateMachineDim, ConnectionDimDrive>(conf);
1614 }
1615 }
1616 /*catch (std::exception& e)
1617 {
1618 cerr << "Exception: " << e.what() << endl;
1619 return -1;
1620 }*/
1621
1622 return 0;
1623}
Note: See TracBrowser for help on using the repository browser.