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

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