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

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