source: trunk/FACT++/src/smartfact.cc@ 14716

Last change on this file since 14716 was 14712, checked in by tbretz, 12 years ago
Be a bit more coservative with the rates; adapted the tracking report to the new format; directly use th dev-paramater sent by the new drivectrl version
File size: 99.3 KB
Line 
1#ifdef HAVE_NOVA
2#include <libnova/solar.h>
3#include <libnova/lunar.h>
4#include <libnova/rise_set.h>
5#include <libnova/transform.h>
6#endif
7
8#ifdef HAVE_SQL
9#include "Database.h"
10#endif
11
12#include <sys/stat.h> //for file stats
13
14#include "Dim.h"
15#include "Event.h"
16#include "Shell.h"
17#include "StateMachineDim.h"
18#include "Connection.h"
19#include "Configuration.h"
20#include "Console.h"
21#include "PixelMap.h"
22#include "DimWriteStatistics.h"
23
24#include "tools.h"
25
26#include "LocalControl.h"
27
28#include "HeadersFAD.h"
29#include "HeadersBIAS.h"
30#include "HeadersFTM.h"
31#include "HeadersFSC.h"
32#include "HeadersMCP.h"
33#include "HeadersDrive.h"
34#include "HeadersFeedback.h"
35#include "HeadersRateScan.h"
36#include "HeadersRateControl.h"
37#include "HeadersMagicWeather.h"
38
39#include <boost/filesystem.hpp>
40
41using namespace std;
42
43// ------------------------------------------------------------------------
44
45#include "DimDescriptionService.h"
46#include "DimState.h"
47
48// ------------------------------------------------------------------------
49/*
50template<class T>
51 class buffer : public deque<T>
52 {
53 int32_t max_size;
54
55 public:
56 buffer(int32_t max=-1) : max_size(max) { }
57 const T &operator=(const T &t) const { push_back(t); if (max_size>0 && deque<T>::size()>max_size) deque<T>::pop_front(); }
58 operator T() const { return deque<T>::size()>0 ? deque<T>::back() : T(); }
59 bool valid() const { return deque<T>::size()>0; }
60 };
61*/
62
63// ------------------------------------------------------------------------
64
65namespace HTML
66{
67 const static string kWhite = "#ffffff";
68 const static string kYellow = "#fffff0";
69 const static string kRed = "#fff8f0";
70 const static string kGreen = "#f0fff0";
71 const static string kBlue = "#f0f0ff";
72};
73
74// ========================================================================
75// ========================================================================
76// ========================================================================
77
78class Sun
79{
80public:
81 Time time;
82
83 Time fRiseDayTime;
84 Time fRiseCivil;
85 Time fRiseAstronomical;
86 Time fRiseDarkTime;
87
88 Time fSetDayTime;
89 Time fSetCivil;
90 Time fSetAstronomical;
91 Time fSetDarkTime;
92
93 int state;
94 string description;
95 string color;
96
97 bool isday;
98 bool visible;
99
100public:
101 Sun() : time(Time::none)
102 {
103 }
104
105 // Could be done more efficient: Only recalcuate if
106 // the current time exceeds at least on of the stored times
107 Sun(double lon, double lat, const Time &t=Time()) : time(t)
108 {
109#ifdef HAVE_LIBNOVA
110 ln_lnlat_posn observer;
111 observer.lng = lon;
112 observer.lat = lat;
113
114 // get Julian day from local time
115 const double JD = time.JD();
116
117 ln_rst_time sun_day;
118 ln_rst_time sun_civil;
119 ln_rst_time sun_astronomical;
120 ln_rst_time sun_dark;
121
122 // Warning: return code of 1 means circumpolar and is not checked!
123 ln_get_solar_rst (JD-0.5, &observer, &sun_day);
124 ln_get_solar_rst_horizon(JD-0.5, &observer, - 6, &sun_civil);
125 ln_get_solar_rst_horizon(JD-0.5, &observer, -12, &sun_astronomical);
126 ln_get_solar_rst_horizon(JD-0.5, &observer, -18, &sun_dark);
127
128 fSetDayTime = Time(sun_day.set);
129 fSetCivil = Time(sun_civil.set);
130 fSetAstronomical = Time(sun_astronomical.set);
131 fSetDarkTime = Time(sun_dark.set);
132
133 fRiseDayTime = Time(sun_day.rise);
134 fRiseCivil = Time(sun_civil.rise);
135 fRiseAstronomical = Time(sun_astronomical.rise);
136 fRiseDarkTime = Time(sun_dark.rise);
137
138 const bool is_day = JD>sun_day.rise;
139 const bool is_night = JD>sun_dark.set;
140
141 ln_get_solar_rst (JD+0.5, &observer, &sun_day);
142 ln_get_solar_rst_horizon(JD+0.5, &observer, - 6, &sun_civil);
143 ln_get_solar_rst_horizon(JD+0.5, &observer, -12, &sun_astronomical);
144 ln_get_solar_rst_horizon(JD+0.5, &observer, -18, &sun_dark);
145
146 if (is_day)
147 {
148 fRiseDayTime = Time(sun_day.rise);
149 fRiseCivil = Time(sun_civil.rise);
150 fRiseAstronomical = Time(sun_astronomical.rise);
151 fRiseDarkTime = Time(sun_dark.rise);
152 }
153
154 if (is_night)
155 {
156 fSetDayTime = Time(sun_day.set);
157 fSetCivil = Time(sun_civil.set);
158 fSetAstronomical = Time(sun_astronomical.set);
159 fSetDarkTime = Time(sun_dark.set);
160 }
161
162 // case 0: midnight to sun-rise | !is_day && !is_night | rise/set
163 // case 1: sun-rise to sun-set | is_day && !is_night | set /rise
164 // case 2: sun-set to midnight | is_day && is_night | rise/set
165
166 isday = is_day^is_night;
167
168 state = isday ? 4 : 0;
169 if (time>fSetDayTime) state++;
170 if (time>fSetCivil) state++;
171 if (time>fSetAstronomical) state++;
172 if (time>fSetDarkTime) state++;
173
174 if (time>fRiseDarkTime) state++;
175 if (time>fRiseAstronomical) state++;
176 if (time>fRiseCivil) state++;
177 if (time>fRiseDayTime) state++;
178
179 string name[] =
180 {
181 "dark time",
182 "astron. twilight",
183 "civil twilight",
184 "sunrise",
185 "day time",
186 "sunset",
187 "civil twilight",
188 "astron. twilight",
189 "dark time"
190 };
191
192 description = state[name];
193
194 const string arr = isday ?
195 fSetDarkTime.MinutesTo(time)+"&darr;" :
196 fRiseDarkTime.MinutesTo(time)+"&uarr;";
197
198 description += " ["+arr+"]";
199
200 switch (state)
201 {
202 case 0: case 1: color = HTML::kGreen; break;
203 case 2: case 3: color = HTML::kYellow; break;
204 case 4: color = HTML::kRed; break;
205 case 5: case 6: color = HTML::kYellow; break;
206 case 7: case 8: color = HTML::kGreen; break;
207 }
208
209 visible = state>=3 && state<=5;
210#endif
211 }
212};
213
214class Moon
215{
216public:
217 Time time;
218
219 double ra;
220 double dec;
221
222 double zd;
223 double az;
224
225 double disk;
226
227 bool visible;
228
229 Time fRise;
230 Time fTransit;
231 Time fSet;
232
233 string description;
234 string color;
235
236 int state;
237
238 Moon() : time(Time::none)
239 {
240 }
241
242 // Could be done more efficient: Only recalcuate if
243 // the current time exceeds at least on of the stored times
244 Moon(double lon, double lat, const Time &t=Time()) : time(t)
245 {
246#ifdef HAVE_LIBNOVA
247 const double JD = time.JD();
248
249 ln_lnlat_posn observer;
250 observer.lng = lon;
251 observer.lat = lat;
252
253 //observer.lng.degrees = -5;
254 //observer.lng.minutes = 36;
255 //observer.lng.seconds = 30;
256 //observer.lat.degrees = 42;
257 //observer.lat.minutes = 35;
258 //observer.lat.seconds = 40;
259
260 ln_rst_time moon;
261 ln_get_lunar_rst(JD-0.5, &observer, &moon);
262
263 fRise = Time(moon.rise);
264 fTransit = Time(moon.transit);
265 fSet = Time(moon.set);
266
267 //visible =
268 // ((JD>moon.rise && JD<moon.set ) && moon.rise<moon.set) ||
269 // ((JD<moon.set || JD>moon.rise) && moon.rise>moon.set);
270
271 const bool is_up = JD>moon.rise;
272 const bool is_sinking = JD>moon.transit;
273 const bool is_dn = JD>moon.set;
274
275 ln_get_lunar_rst(JD+0.5, &observer, &moon);
276 if (is_up)
277 fRise = Time(moon.rise);
278 if (is_sinking)
279 fTransit = Time(moon.transit);
280 if (is_dn)
281 fSet = Time(moon.set);
282
283 ln_equ_posn pos;
284 ln_get_lunar_equ_coords(JD, &pos);
285
286 ln_hrz_posn hrz;
287 ln_get_hrz_from_equ (&pos, &observer, JD, &hrz);
288 az = hrz.az;
289 zd = 90-hrz.alt;
290
291 ra = pos.ra/15;
292 dec = pos.dec;
293
294 disk = ln_get_lunar_disk(JD)*100;
295 state = 0;
296 if (fRise <fTransit && fRise <fSet) state = 0; // not visible
297 if (fTransit<fSet && fTransit<fRise) state = 1; // before culm
298 if (fSet <fRise && fSet <fTransit) state = 2; // after culm
299
300 visible = state!=0;
301
302 // 0: not visible
303 // 1: visible before cul
304 // 2: visible after cul
305
306 if (!visible || disk<25)
307 color = HTML::kGreen;
308 else
309 color = disk>75 ? HTML::kRed : HTML::kYellow;
310
311 const string arr = fSet<fRise ?
312 fSet.MinutesTo(time) +"&darr;" :
313 fRise.MinutesTo(time)+"&uarr;";
314
315 ostringstream out;
316 out << setprecision(2);
317 out << (visible?"visible ":"") << (disk<0.1?0:disk) << "% [" << arr << "]";
318
319 description = out.str();
320#endif
321 }
322
323 double Angle(double r, double d) const
324 {
325 const double theta0 = M_PI/2-d*M_PI/180;
326 const double phi0 = r*M_PI/12;
327
328 const double theta1 = M_PI/2-dec*M_PI/180;
329 const double phi1 = ra*M_PI/12;
330
331 const double x0 = sin(theta0) * cos(phi0);
332 const double y0 = sin(theta0) * sin(phi0);
333 const double z0 = cos(theta0);
334
335 const double x1 = sin(theta1) * cos(phi1);
336 const double y1 = sin(theta1) * sin(phi1);
337 const double z1 = cos(theta1);
338
339 double arg = x0*x1 + y0*y1 + z0*z1;
340 if(arg > 1.0) arg = 1.0;
341 if(arg < -1.0) arg = -1.0;
342
343 return acos(arg) * 180/M_PI;
344 }
345
346 static string Color(double angle)
347 {
348 if (angle<10 || angle>150)
349 return HTML::kRed;
350 if (angle<20 || angle>140)
351 return HTML::kYellow;
352 return HTML::kGreen;
353 }
354};
355
356// ========================================================================
357// ========================================================================
358// ========================================================================
359
360class StateMachineSmartFACT : public StateMachineDim
361{
362public:
363 static bool fIsServer;
364
365private:
366 enum states_t
367 {
368 kStateDimNetworkNA = 1,
369 kStateRunning,
370 };
371
372 // ------------------------- History classes -----------------------
373
374 struct EventElement
375 {
376 Time time;
377 string msg;
378
379 EventElement(const Time &t, const string &s) : time(t), msg(s) { }
380 };
381
382 class EventHist : public deque<EventElement>
383 {
384 const boost::posix_time::time_duration deltat; //boost::posix_time::pos_infin
385 const uint64_t max;
386
387 public:
388 EventHist(const boost::posix_time::time_duration &dt=boost::posix_time::hours(12), uint64_t mx=UINT64_MAX) : deltat(dt), max(mx) { }
389
390 void add(const string &s, const Time &t=Time())
391 {
392 while (size()>0 && (front().time+deltat<t || size()>max))
393 pop_front();
394
395 push_back(EventElement(t, s));
396 }
397
398 string get() const
399 {
400 ostringstream out;
401
402 string last = "";
403 for (auto it=begin(); it!=end(); it++)
404 {
405 const string tm = it->time.GetAsStr("%H:%M:%S ");
406 out << (tm!=last?tm:"--:--:-- ") << it->msg << "<br/>";
407 last = tm;
408 }
409
410 return out.str();
411 }
412 string rget() const
413 {
414 ostringstream out;
415
416 for (auto it=rbegin(); it!=rend(); it++)
417 out << it->time.GetAsStr("%H:%M:%S ") << it->msg << "<br/>";
418
419 return out.str();
420 }
421 };
422
423 // ------------------------- Internal variables -----------------------
424
425 const Time fRunTime;
426
427 PixelMap fPixelMap;
428
429 string fDatabase;
430
431 Time fLastUpdate;
432 Time fLastAstroCalc;
433
434 string fPath;
435
436 // ----------------------------- Data storage -------------------------
437
438 EventHist fControlMessageHist;
439 EventHist fControlAlarmHist;
440 int32_t fControlScriptDepth;
441
442 int32_t fMcpConfigurationState; // For consistency
443 int64_t fMcpConfigurationMaxTime;
444 int64_t fMcpConfigurationMaxEvents;
445 string fMcpConfigurationName;
446 Time fMcpConfigurationRunStart;
447 EventHist fMcpConfigurationHist;
448
449 bool fLastRunFinishedWithZeroEvents;
450
451 enum weather_t { kWeatherBegin=0, kTemp = kWeatherBegin, kDew, kHum, kPress, kWind, kGusts, kDir, kWeatherEnd = kDir+1 };
452 deque<float> fMagicWeatherHist[kWeatherEnd];
453
454 deque<float> fTngWeatherDustHist;
455 Time fTngWeatherDustTime;
456
457 vector<float> fFeedbackCalibration;
458
459 float fFeedbackTempOffset;
460 float fFeedbackUserOffset;
461
462 vector<float> fBiasControlVoltageVec;
463
464 float fBiasControlPowerTot;
465 float fBiasControlVoltageMed;
466 float fBiasControlCurrentMed;
467 float fBiasControlCurrentMax;
468
469 deque<float> fBiasControlCurrentHist;
470 deque<float> fFscControlTemperatureHist;
471
472 float fFscControlHumidityAvg;
473
474 float fDriveControlPointingZd;
475 string fDriveControlPointingAz;
476 string fDriveControlSourceName;
477 float fDriveControlMoonDist;
478
479 deque<float> fDriveControlTrackingDevHist;
480
481 int64_t fFadControlNumEvents;
482 int64_t fFadControlStartRun;
483 int32_t fFadControlDrsStep;
484 vector<uint32_t> fFadControlDrsRuns;
485
486 deque<float> fFtmControlTriggerRateHist;
487 int32_t fFtmControlTriggerRateTooLow;
488 uint32_t fFtmControlState;
489
490 float fFtmPatchThresholdMed;
491 float fFtmBoardThresholdMed;
492
493 bool fFtmControlFtuOk;
494
495 deque<float> fRateControlThreshold;
496
497 uint64_t fRateScanDataId;
498 uint8_t fRateScanBoard;
499 deque<float> fRateScanDataHist[41];
500
501 set<string> fErrorList;
502 EventHist fErrorHist;
503 EventHist fChatHist;
504
505 uint64_t fFreeSpace;
506
507 Sun fSun;
508 Moon fMoon;
509
510 // --------------------------- File header ----------------------------
511
512 Time fAudioTime;
513 string fAudioName;
514
515 string Header(const Time &d)
516 {
517 ostringstream msg;
518 msg << d.JavaDate() << '\t' << fAudioTime.JavaDate() << '\t' << fAudioName;
519 return msg.str();
520 }
521
522 string Header(const EventImp &d)
523 {
524 return Header(d.GetTime());
525 }
526
527 void SetAudio(const string &name)
528 {
529 fAudioName = name;
530 fAudioTime = Time();
531 }
532
533 // ------------- Initialize variables before the Dim stuff ------------
534
535 DimVersion fDimDNS;
536 DimControl fDimControl;
537 DimDescribedState fDimMcp;
538 DimDescribedState fDimDataLogger;
539 DimDescribedState fDimDriveControl;
540 DimDescribedState fDimTimeCheck;
541 DimDescribedState fDimMagicWeather;
542 DimDescribedState fDimTngWeather;
543 DimDescribedState fDimFeedback;
544 DimDescribedState fDimBiasControl;
545 DimDescribedState fDimFtmControl;
546 DimDescribedState fDimFadControl;
547 DimDescribedState fDimFscControl;
548 DimDescribedState fDimAgilentControl;
549 DimDescribedState fDimPwrControl;
550 DimDescribedState fDimLidControl;
551 DimDescribedState fDimRateControl;
552 DimDescribedState fDimRateScan;
553 DimDescribedState fDimChat;
554 DimDescribedState fDimSkypeClient;
555
556 // -------------------------------------------------------------------
557
558 string GetDir(const double angle)
559 {
560 static const char *dir[] =
561 {
562 "N", "NNE", "NE", "ENE",
563 "E", "ESE", "SE", "SSE",
564 "S", "SSW", "SW", "WSW",
565 "W", "WNW", "NW", "NNW"
566 };
567
568 const uint16_t idx = uint16_t(floor(angle/22.5+16.5))%16;
569 return dir[idx];
570 }
571
572 // -------------------------------------------------------------------
573
574 bool CheckDataSize(const EventImp &d, const char *name, size_t size, bool min=false)
575 {
576 if (d.GetSize()==0)
577 return false;
578
579 if ((!min && d.GetSize()==size) || (min && d.GetSize()>size))
580 return true;
581
582 ostringstream msg;
583 msg << name << " - Received service has " << d.GetSize() << " bytes, but expected ";
584 if (min)
585 msg << "more than ";
586 msg << size << ".";
587 Warn(msg);
588 return false;
589 }
590
591 // -------------------------------------------------------------------
592
593 template<class T>
594 void WriteBinaryVec(const Time &tm, const string &fname, const vector<T> &vec, double scale, double offset=0, const string &title="")
595 {
596 if (vec.size()==0)
597 return;
598
599 ostringstream out;
600 out << tm.JavaDate() << '\n';
601 out << offset << '\n';
602 out << offset+scale << '\n';
603 out << setprecision(3);
604 if (!title.empty())
605 out << title << '\x7f';
606 else
607 {
608 const Statistics stat(vec[0]);
609 out << stat.min << '\n';
610 out << stat.med << '\n';
611 out << stat.max << '\x7f';
612 }
613 for (auto it=vec.begin(); it!=vec.end(); it++)
614 {
615 // The valid range is from 1 to 127
616 // \0 is used to seperate different curves
617 vector<uint8_t> val(it->size());
618 for (uint64_t i=0; i<it->size(); i++)
619 {
620 float range = nearbyint(126*(double(it->at(i))-offset)/scale); // [-2V; 2V]
621 if (range>126)
622 range=126;
623 if (range<0)
624 range=0;
625 val[i] = (uint8_t)range;
626 }
627
628 const char *ptr = reinterpret_cast<char*>(val.data());
629 out.write(ptr, val.size()*sizeof(uint8_t));
630 out << '\x7f';
631 }
632
633 ofstream(fPath+"/"+fname+".bin") << out.str();
634 }
635
636 template<class T>
637 void WriteBinaryVec(const EventImp &d, const string &fname, const vector<T> &vec, double scale, double offset=0, const string &title="")
638 {
639 WriteBinaryVec(d.GetTime(), fname, vec, scale, offset, title);
640 }
641
642 template<class T>
643 void WriteBinary(const Time &tm, const string &fname, const T &t, double scale, double offset=0)
644 {
645 WriteBinaryVec(tm, fname, vector<T>(&t, &t+1), scale, offset);
646 }
647
648 template<class T>
649 void WriteBinary(const EventImp &d, const string &fname, const T &t, double scale, double offset=0)
650 {
651 WriteBinaryVec(d.GetTime(), fname, vector<T>(&t, &t+1), scale, offset);
652 }
653
654 // -------------------------------------------------------------------
655
656 struct Statistics
657 {
658 float min;
659 float max;
660 float med;
661 float avg;
662 //float rms;
663
664 template<class T>
665 Statistics(const T &t, size_t offset_min=0, size_t offset_max=0)
666 : min(0), max(0), med(0), avg(0)
667 {
668 if (t.size()==0)
669 return;
670
671 T copy(t);
672 sort(copy.begin(), copy.end());
673
674 if (offset_min>t.size())
675 offset_min = 0;
676 if (offset_max>t.size())
677 offset_max = 0;
678
679 min = copy[offset_min];
680 max = copy[copy.size()-1-offset_max];
681 avg = accumulate (t.begin(), t.end(), 0.)/t.size();
682
683 const size_t p = t.size()/2;
684
685 med = copy[p];
686 }
687 };
688
689 void HandleControlMessageImp(const EventImp &d)
690 {
691 if (d.GetSize()==0)
692 return;
693
694 fControlMessageHist.add(d.GetText(), d.GetTime());
695
696 ostringstream out;
697 out << setprecision(3);
698 out << Header(d) << '\n';
699 out << HTML::kWhite << '\t';
700 out << "<->" << fControlMessageHist.get() << "</->";
701 out << '\n';
702
703 ofstream(fPath+"/scriptlog.data") << out.str();
704 }
705
706 int HandleDimControlMessage(const EventImp &d)
707 {
708 if (d.GetSize()==0)
709 return GetCurrentState();
710
711 if (d.GetQoS()==MessageImp::kAlarm)
712 {
713 if (d.GetSize()==1)
714 for (auto it=fControlAlarmHist.begin(); it!=fControlAlarmHist.end(); it++)
715 it->time = Time(Time::none);
716 else
717 fControlAlarmHist.add(d.GetText(), d.GetTime());
718 }
719
720 if (d.GetQoS()==MessageImp::kComment)
721 HandleControlMessageImp(d);
722
723 return GetCurrentState();
724 }
725
726 int HandleControlStateChange(const EventImp &d)
727 {
728 if (d.GetSize()==0)
729 return StateMachineImp::kSM_KeepState;
730
731 if (fDimControl.scriptdepth>0)
732 return StateMachineImp::kSM_KeepState;
733
734 if (d.GetQoS()>=2)
735 return StateMachineImp::kSM_KeepState;
736
737#if BOOST_VERSION < 104600
738 const string file = boost::filesystem::path(fDimControl.file).filename();
739#else
740 const string file = boost::filesystem::path(fDimControl.file).filename().string();
741#endif
742
743 // [0] DimControl::kReady (Idle)
744 // [1] DimControl::kLoad
745 // [2] DimControl::kStarted
746 if (d.GetQoS()==1)
747 {
748 fControlMessageHist.clear();
749 HandleControlMessageImp(Event(d, "========================================", 41));
750 }
751
752 HandleControlMessageImp(Event(d, ("----- "+fDimControl.shortmsg+" -----").data(), fDimControl.shortmsg.length()+13));
753 if (!file.empty() && d.GetQoS()<2)
754 HandleControlMessageImp(Event(d, file.data(), file.length()+1));
755
756 // Not that this will also "ding" just after program startup
757 // if the dimctrl is still in state -3
758 if (d.GetQoS()==0)
759 {
760 HandleControlMessageImp(Event(d, "========================================", 41));
761 if (fDimControl.last.second!=DimState::kOffline)
762 SetAudio("ding");
763 }
764
765 return StateMachineImp::kSM_KeepState;
766 }
767
768 void AddMcpConfigurationHist(const EventImp &d, const string &msg)
769 {
770 fMcpConfigurationHist.add(msg, d.GetTime());
771
772 ostringstream out;
773 out << d.GetJavaDate() << '\n';
774 out << HTML::kWhite << '\t';
775 out << "<->" << fMcpConfigurationHist.rget() << "</->";
776 out << '\n';
777
778 ofstream(fPath+"/observations.data") << out.str();
779 }
780
781 int HandleFscControlStateChange(const EventImp &d)
782 {
783 const int32_t &last = fDimFscControl.last.second;
784 const int32_t &state = fDimFscControl.state();
785
786 if (last==DimState::kOffline || state==DimState::kOffline)
787 return StateMachineImp::kSM_KeepState;
788
789 if (last<FSC::State::kConnected && state==FSC::State::kConnected)
790 {
791 AddMcpConfigurationHist(d, "<B>Camera swiched on</B>");
792 SetAudio("startup");
793 }
794
795 if (last==FSC::State::kConnected && state<FSC::State::kConnected)
796 {
797 AddMcpConfigurationHist(d, "<B>Camera swiched off</B>");
798 SetAudio("shutdown");
799 }
800
801 return StateMachineImp::kSM_KeepState;
802 }
803
804 int HandleMcpConfiguration(const EventImp &d)
805 {
806 if (!CheckDataSize(d, "Mcp:Configuration", 16, true))
807 {
808 fMcpConfigurationState = DimState::kOffline;
809 fMcpConfigurationMaxTime = 0;
810 fMcpConfigurationMaxEvents = 0;
811 fMcpConfigurationName = "";
812 fMcpConfigurationRunStart = Time(Time::none);
813 return GetCurrentState();
814 }
815
816 // If a run ends...
817 if (fMcpConfigurationState==MCP::State::kTakingData && d.GetQoS()==MCP::State::kIdle)
818 {
819 // ...and no script is running just play a simple 'tick'
820 // ...and a script is running just play a simple 'tick'
821 if (/*fDimControl.state()<-2 &&*/ fDimControl.scriptdepth==0)
822 SetAudio("dong");
823 else
824 SetAudio("losticks");
825
826 fLastRunFinishedWithZeroEvents = fFadControlNumEvents==0;
827
828 ostringstream out;
829 out << "<#darkred>" << d.Ptr<char>(16);
830 if (!fDriveControlSourceName.empty())
831 out << " [" << fDriveControlSourceName << ']';
832 out << " (N=" << fFadControlNumEvents << ')';
833 out << "</#>";
834
835 AddMcpConfigurationHist(d, out.str());
836 }
837
838 if (d.GetQoS()==MCP::State::kTakingData)
839 {
840 fMcpConfigurationRunStart = Time();
841 SetAudio("losticks");
842
843 ostringstream out;
844 out << "<#darkgreen>" << fMcpConfigurationName;
845 if (!fDriveControlSourceName.empty())
846 out << " [" << fDriveControlSourceName << ']';
847 if (fFadControlStartRun>0)
848 out << " (Run " << fFadControlStartRun << ')';
849 out << "</#>";
850
851 AddMcpConfigurationHist(d, out.str());
852 }
853
854 fMcpConfigurationState = d.GetQoS();
855 fMcpConfigurationMaxTime = d.Get<uint64_t>();
856 fMcpConfigurationMaxEvents = d.Get<uint64_t>(8);
857 fMcpConfigurationName = d.Ptr<char>(16);
858
859 return GetCurrentState();
860 }
861
862 void WriteWeather(const EventImp &d, const string &name, int i, float min, float max)
863 {
864 const Statistics stat(fMagicWeatherHist[i]);
865
866 ostringstream out;
867 out << setprecision(3);
868 out << d.GetJavaDate() << '\n';
869
870 out << HTML::kWhite << '\t' << fMagicWeatherHist[i].back() << '\n';
871 out << HTML::kWhite << '\t' << stat.min << '\n';
872 out << HTML::kWhite << '\t' << stat.avg << '\n';
873 out << HTML::kWhite << '\t' << stat.max << '\n';
874
875 ofstream(fPath+"/"+name+".data") << out.str();
876
877 WriteBinary(d, "hist-magicweather-"+name, fMagicWeatherHist[i], max-min, min);
878 }
879
880 int HandleMagicWeatherData(const EventImp &d)
881 {
882 if (!CheckDataSize(d, "MagicWeather:Data", 7*4+2))
883 return GetCurrentState();
884
885 // Store a history of the last 300 entries
886 for (int i=kWeatherBegin; i<kWeatherEnd; i++)
887 {
888 fMagicWeatherHist[i].push_back(d.Ptr<float>(2)[i]);
889 if (fMagicWeatherHist[i].size()>300)
890 fMagicWeatherHist[i].pop_front();
891 }
892
893 ostringstream out;
894 out << d.GetJavaDate() << '\n';
895 if (fSun.time.IsValid() && fMoon.time.IsValid())
896 {
897 out << fSun.color << '\t' << fSun.description << '\n';
898 out << setprecision(2);
899 out << (fSun.isday?HTML::kWhite:fMoon.color) << '\t' << fMoon.description << '\n';
900 }
901 else
902 out << "\n\n";
903 out << setprecision(3);
904 for (int i=0; i<6; i++)
905 out << HTML::kWhite << '\t' << fMagicWeatherHist[i].back() << '\n';
906 out << HTML::kWhite << '\t' << GetDir(fMagicWeatherHist[kDir].back()) << '\n';
907 out << HTML::kWhite << '\t';
908 if (fTngWeatherDustHist.size()>0)
909 out << fTngWeatherDustHist.back() << '\t' << fTngWeatherDustTime.GetAsStr("%H:%M") << '\n';
910 else
911 out << "\t\n";
912
913 ofstream(fPath+"/weather.data") << out.str();
914
915 WriteWeather(d, "temp", kTemp, -5, 35);
916 WriteWeather(d, "dew", kDew, -5, 35);
917 WriteWeather(d, "hum", kHum, 0, 100);
918 WriteWeather(d, "wind", kWind, 0, 100);
919 WriteWeather(d, "gusts", kGusts, 0, 100);
920 WriteWeather(d, "press", kPress, 700, 1000);
921
922 return GetCurrentState();
923 }
924
925 int HandleTngWeatherDust(const EventImp &d)
926 {
927 if (!CheckDataSize(d, "TngWeather:Dust", 4))
928 return GetCurrentState();
929
930 fTngWeatherDustTime = d.GetTime();
931
932 fTngWeatherDustHist.push_back(d.GetFloat());
933 if (fTngWeatherDustHist.size()>300)
934 fTngWeatherDustHist.pop_front();
935
936 const Statistics stat(fTngWeatherDustHist);
937
938 const double scale = stat.max>0 ? pow(10, ceil(log10(stat.max))) : 0;
939
940 WriteBinary(d, "hist-tng-dust", fTngWeatherDustHist, scale);
941
942 ostringstream out;
943 out << d.GetJavaDate() << '\n';
944
945 ofstream(fPath+"/tngdust.data") << out.str();
946
947 return GetCurrentState();
948 }
949
950 int HandleDriveControlStateChange(const EventImp &d)
951 {
952 const int32_t &last = fDimFscControl.last.second;
953 const int32_t &state = fDimFscControl.state();
954
955 if (last==DimState::kOffline || state==DimState::kOffline)
956 return StateMachineImp::kSM_KeepState;
957
958 if (last<Drive::State::kArmed && state>=Drive::State::kArmed)
959 AddMcpConfigurationHist(d, "Drive connected");
960
961 if (last>=Drive::State::kArmed && state<Drive::State::kArmed)
962 AddMcpConfigurationHist(d, "Drive disconnected");
963
964 return StateMachineImp::kSM_KeepState;
965 }
966
967 int HandleDrivePointing(const EventImp &d)
968 {
969 if (!CheckDataSize(d, "DriveControl:Pointing", 16))
970 return GetCurrentState();
971
972 fDriveControlPointingZd = d.Get<double>();
973
974 const double az = d.Get<double>(8);
975
976 fDriveControlPointingAz = GetDir(az);
977
978 ostringstream out;
979 out << d.GetJavaDate() << '\n';
980
981 out << setprecision(0) << fixed;
982 out << HTML::kWhite << '\t' << az << '\t' << fDriveControlPointingAz << '\n';
983 out << HTML::kWhite << '\t' << fDriveControlPointingZd << '\n';
984
985 ofstream(fPath+"/pointing.data") << out.str();
986
987 return GetCurrentState();
988 }
989
990 int HandleDriveTracking(const EventImp &d)
991 {
992 if (!CheckDataSize(d, "DriveControl:Tracking", 64))
993 return GetCurrentState();
994
995 const double Ra = d.Get<double>(0*8);
996 const double Dec = d.Get<double>(1*8);
997 const double Zd = d.Get<double>(3*8);
998 const double Az = d.Get<double>(4*8);
999
1000 const double dev = d.Get<double>(7*8);
1001
1002 fDriveControlTrackingDevHist.push_back(dev);
1003 if (fDriveControlTrackingDevHist.size()>300)
1004 fDriveControlTrackingDevHist.pop_front();
1005
1006 WriteBinary(d, "hist-control-deviation", fDriveControlTrackingDevHist, 120);
1007
1008 ostringstream out;
1009 out << d.GetJavaDate() << '\n';
1010
1011 out << HTML::kWhite << '\t' << fDriveControlSourceName << '\n';
1012 out << setprecision(5);
1013 out << HTML::kWhite << '\t' << Ra << '\n';
1014 out << HTML::kWhite << '\t' << Dec << '\n';
1015 out << setprecision(3);
1016 out << HTML::kWhite << '\t' << Zd << '\n';
1017 out << HTML::kWhite << '\t' << Az << '\n';
1018 out << HTML::kWhite << '\t' << dev << '\n';
1019
1020 fDriveControlMoonDist = -1;
1021
1022 if (fMoon.visible)
1023 {
1024 const double angle = fMoon.Angle(Ra, Dec);
1025 out << Moon::Color(angle) << '\t' << setprecision(3) << angle << '\n';
1026
1027 fDriveControlMoonDist = angle;
1028 }
1029 else
1030 out << HTML::kWhite << "\t&mdash; \n";
1031
1032 ofstream(fPath+"/tracking.data") << out.str();
1033
1034 return GetCurrentState();
1035 }
1036
1037 int HandleDriveSource(const EventImp &d)
1038 {
1039 if (!CheckDataSize(d, "DriveControl:Source", 7*4+2, true))
1040 return GetCurrentState();
1041
1042 const double *ptr = d.Ptr<double>();
1043
1044 const double ra = ptr[0]; // Ra[h]
1045 const double dec = ptr[1]; // Dec[deg]
1046 const double woff = ptr[4]; // Wobble offset [deg]
1047 const double wang = ptr[5]; // Wobble angle [deg]
1048
1049 fDriveControlSourceName = d.Ptr<char>(6*8);
1050
1051 ostringstream out;
1052 out << d.GetJavaDate() << '\n';
1053
1054 out << HTML::kWhite << '\t' << fDriveControlSourceName << '\n';
1055 out << setprecision(5);
1056 out << HTML::kWhite << '\t' << ra << '\n';
1057 out << HTML::kWhite << '\t' << dec << '\n';
1058 out << setprecision(3);
1059 out << HTML::kWhite << '\t' << woff << '\n';
1060 out << HTML::kWhite << '\t' << wang << '\n';
1061
1062 ofstream(fPath+"/source.data") << out.str();
1063
1064 return GetCurrentState();
1065 }
1066
1067 int HandleFeedbackCalibration(const EventImp &d)
1068 {
1069 if (!CheckDataSize(d, "Feedback:Calibration", 3*4*416))
1070 {
1071 fFeedbackCalibration.clear();
1072 return GetCurrentState();
1073 }
1074
1075 const float *ptr = d.Ptr<float>();
1076 fFeedbackCalibration.assign(ptr+2*416, ptr+3*416);
1077
1078 return GetCurrentState();
1079 }
1080
1081 int HandleFeedbackDeviation(const EventImp &d)
1082 {
1083 if (!CheckDataSize(d, "Feedback:Deviation", (2*416+2)*4))
1084 return GetCurrentState();
1085
1086 const float *ptr = d.Ptr<float>();
1087 vector<float> dev(ptr+416, ptr+416+320);
1088
1089 fFeedbackTempOffset = ptr[2*416];
1090 fFeedbackUserOffset = ptr[2*416+1];
1091
1092 for (int i=0; i<320; i++)
1093 dev[i] -= fFeedbackTempOffset+fFeedbackUserOffset;
1094
1095 // Write the 160 patch values to a file
1096 WriteBinary(d, "cam-feedback-deviation", dev, 1);
1097
1098 const Statistics stat(dev, 3);
1099
1100 ostringstream out;
1101 out << d.GetJavaDate() << '\n';
1102 out << HTML::kWhite << '\t' << fFeedbackUserOffset << '\n';
1103 out << setprecision(3);
1104 out << HTML::kWhite << '\t' << fFeedbackTempOffset << '\n';
1105 out << HTML::kWhite << '\t' << stat.min << '\n';
1106 out << HTML::kWhite << '\t' << stat.med << '\n';
1107 out << HTML::kWhite << '\t' << stat.avg << '\n';
1108 out << HTML::kWhite << '\t' << stat.max << '\n';
1109 ofstream(fPath+"/feedback.data") << out.str();
1110
1111 return GetCurrentState();
1112 }
1113
1114 int HandleBiasVoltage(const EventImp &d)
1115 {
1116 if (!CheckDataSize(d, "BiasControl:Voltage", 1664))
1117 {
1118 fBiasControlVoltageVec.clear();
1119 return GetCurrentState();
1120 }
1121
1122 fBiasControlVoltageVec.assign(d.Ptr<float>(), d.Ptr<float>()+320);
1123
1124 const Statistics stat(fBiasControlVoltageVec);
1125
1126 fBiasControlVoltageMed = stat.med;
1127
1128 vector<float> val(320, 0);
1129 for (int i=0; i<320; i++)
1130 {
1131 const int idx = (fPixelMap.hv(i).hw()/9)*2+fPixelMap.hv(i).group();
1132 val[idx] = fBiasControlVoltageVec[i];
1133 }
1134
1135 if (fDimBiasControl.state()==BIAS::State::kVoltageOn)
1136 WriteBinary(d, "cam-biascontrol-voltage", val, 10, 65);
1137 else
1138 WriteBinary(d, "cam-biascontrol-voltage", val, 75);
1139
1140 ostringstream out;
1141 out << setprecision(3);
1142 out << d.GetJavaDate() << '\n';
1143 out << HTML::kWhite << '\t' << stat.min << '\n';
1144 out << HTML::kWhite << '\t' << stat.med << '\n';
1145 out << HTML::kWhite << '\t' << stat.avg << '\n';
1146 out << HTML::kWhite << '\t' << stat.max << '\n';
1147 ofstream(fPath+"/voltage.data") << out.str();
1148
1149 return GetCurrentState();
1150 }
1151
1152 int HandleBiasCurrent(const EventImp &d)
1153 {
1154 if (!CheckDataSize(d, "BiasControl:Current", 832))
1155 return GetCurrentState();
1156
1157 // Convert dac counts to uA
1158 vector<float> v(320);
1159 for (int i=0; i<320; i++)
1160 v[i] = d.Ptr<uint16_t>()[i] * 5000./4096;
1161
1162 const bool cal = fFeedbackCalibration.size()>0 && fBiasControlVoltageVec.size()>0;
1163
1164 double power_tot = 0;
1165 double power_apd = 0;
1166
1167 // 3900 Ohm/n + 1000 Ohm + 1100 Ohm (with n=4 or n=5)
1168 const double R[2] = { 3075, 2870 };
1169
1170 // Calibrate the data (subtract offset)
1171 if (cal)
1172 for (int i=0; i<320; i++)
1173 {
1174 // Measued current minus leakage current (bias crate calibration)
1175 v[i] -= fBiasControlVoltageVec[i]/fFeedbackCalibration[i]*1e6;
1176
1177 // Total power participated in the camera at the G-APD
1178 // and the serial resistors (total voltage minus voltage
1179 // drop at resistors in bias crate)
1180 power_tot += v[i]*(fBiasControlVoltageVec[i] - 1100e-6*v[i])*1e-6;
1181
1182 // Group index (0 or 1) of the of the pixel (4 or 5 pixel patch)
1183 const int g = fPixelMap.hv(i).group();
1184
1185 // Current per G-APD
1186 v[i] /= g ? 5 : 4;
1187
1188 // Power consumption per G-APD
1189 if (i!=66 && i!=191 && i!=193)
1190 power_apd += v[i]*(fBiasControlVoltageVec[i]-R[g]*v[i]*1e-6)*1e-6;
1191 }
1192
1193 // Divide by number of summed channels, convert to mW
1194 power_apd /= 317e-3; // [mW]
1195
1196 if (power_tot<1e-3)
1197 power_tot = 0;
1198 if (power_apd<1e-3)
1199 power_apd = 0;
1200
1201 fBiasControlPowerTot = power_tot;
1202
1203 // Get the maximum of each patch
1204 vector<float> val(320, 0);
1205 for (int i=0; i<320; i++)
1206 {
1207 const int idx = (fPixelMap.hv(i).hw()/9)*2+fPixelMap.hv(i).group();
1208 val[idx] = v[i];
1209 }
1210
1211 // Write the 160 patch values to a file
1212 WriteBinary(d, "cam-biascontrol-current", val, 100);
1213
1214 const Statistics stat(v, 0, 3);
1215
1216 // Exclude the three crazy channels
1217 fBiasControlCurrentMed = stat.med;
1218 fBiasControlCurrentMax = stat.max;
1219
1220 // Store a history of the last 60 entries
1221 fBiasControlCurrentHist.push_back(fBiasControlCurrentMed);
1222 if (fBiasControlCurrentHist.size()>360)
1223 fBiasControlCurrentHist.pop_front();
1224
1225 // write the history to a file
1226 WriteBinary(d, "hist-biascontrol-current", fBiasControlCurrentHist, 100);
1227
1228 const string col0 = cal ? HTML::kGreen : HTML::kWhite;
1229
1230 string col1 = col0;
1231 string col2 = col0;
1232 string col3 = col0;
1233 string col4 = col0;
1234
1235 if (cal && stat.min>65)
1236 col1 = kYellow;
1237 if (cal && stat.min>80)
1238 col1 = kRed;
1239
1240 if (cal && stat.med>65)
1241 col2 = kYellow;
1242 if (cal && stat.med>80)
1243 col2 = kRed;
1244
1245 if (cal && stat.avg>65)
1246 col3 = kYellow;
1247 if (cal && stat.avg>80)
1248 col3 = kRed;
1249
1250 if (cal && stat.max>65)
1251 col4 = kYellow;
1252 if (cal && stat.max>80)
1253 col4 = kRed;
1254
1255 ostringstream out;
1256 out << setprecision(2);
1257 out << d.GetJavaDate() << '\n';
1258 out << col0 << '\t' << (cal?"yes":"no") << '\n';
1259 out << col1 << '\t' << stat.min << '\n';
1260 out << col2 << '\t' << stat.med << '\n';
1261 out << col3 << '\t' << stat.avg << '\n';
1262 out << col4 << '\t' << stat.max << '\n';
1263 out << HTML::kWhite << '\t' << power_tot << "W [" << power_apd << "mW]\n";
1264 ofstream(fPath+"/current.data") << out.str();
1265
1266 return GetCurrentState();
1267 }
1268
1269 int HandleFadEvents(const EventImp &d)
1270 {
1271 if (!CheckDataSize(d, "FadControl:Events", 4*4))
1272 {
1273 fFadControlNumEvents = -1;
1274 return GetCurrentState();
1275 }
1276
1277 fFadControlNumEvents = d.Get<uint32_t>();
1278
1279 return GetCurrentState();
1280 }
1281
1282 int HandleFadStartRun(const EventImp &d)
1283 {
1284 if (!CheckDataSize(d, "FadControl:StartRun", 16))
1285 {
1286 fFadControlStartRun = -1;
1287 return GetCurrentState();
1288 }
1289
1290 fFadControlStartRun = d.Get<int64_t>();
1291
1292 return GetCurrentState();
1293 }
1294
1295 int HandleFadDrsRuns(const EventImp &d)
1296 {
1297 if (!CheckDataSize(d, "FadControl:DrsRuns", 4*4))
1298 {
1299 fFadControlDrsStep = -1;
1300 return GetCurrentState();
1301 }
1302
1303 const uint32_t *ptr = d.Ptr<uint32_t>();
1304 fFadControlDrsStep = ptr[0];
1305 fFadControlDrsRuns[0] = ptr[1];
1306 fFadControlDrsRuns[1] = ptr[2];
1307 fFadControlDrsRuns[2] = ptr[3];
1308
1309 return GetCurrentState();
1310 }
1311
1312 int HandleFadConnections(const EventImp &d)
1313 {
1314 if (!CheckDataSize(d, "FadControl:Connections", 41))
1315 {
1316 //fStatusEventBuilderLabel->setText("Offline");
1317 return GetCurrentState();
1318 }
1319
1320 string rc(40, '-'); // orange/red [45]
1321
1322 const uint8_t *ptr = d.Ptr<uint8_t>();
1323
1324 int c[4] = { '.', '.', '.', '.' };
1325
1326 for (int i=0; i<40; i++)
1327 {
1328 const uint8_t stat1 = ptr[i]&3;
1329 const uint8_t stat2 = ptr[i]>>3;
1330
1331 if (stat1==0 && stat2==0)
1332 rc[i] = '.'; // gray [46]
1333 else
1334 if (stat1>=2 && stat2==8)
1335 rc[i] = stat1==2?'+':'*'; // green [43] : check [42]
1336
1337 if (rc[i]<c[i/10])
1338 c[i/10] = rc[i];
1339 }
1340
1341 string col[4];
1342 for (int i=0; i<4; i++)
1343 switch (c[i])
1344 {
1345 case '.': col[i]=HTML::kWhite; break;
1346 case '-': col[i]=HTML::kRed; break;
1347 case '+': col[i]=HTML::kYellow; break;
1348 case '*': col[i]=HTML::kGreen; break;
1349 }
1350
1351 ostringstream out;
1352 out << setprecision(3);
1353 out << d.GetJavaDate() << '\n';
1354 out << col[0] << '\t' << rc.substr( 0, 10) << '\n';
1355 out << col[1] << '\t' << rc.substr(10, 10) << '\n';
1356 out << col[2] << '\t' << rc.substr(20, 10) << '\n';
1357 out << col[3] << '\t' << rc.substr(30, 10) << '\n';
1358 ofstream(fPath+"/fad.data") << out.str();
1359
1360 return GetCurrentState();
1361 }
1362
1363 int HandleFtmControlStateChange()
1364 {
1365 const int32_t &last = fDimFtmControl.last.second;
1366 const int32_t &state = fDimFtmControl.state();
1367
1368 // If a new run has been started ensure that the counter
1369 // is reset. The reset in HandleFtmTriggerRates might
1370 // arrive only after the run was started.
1371 if (last!=FTM::State::kTriggerOn && state==MCP::State::kTriggerOn)
1372 fFtmControlTriggerRateTooLow = -1;
1373
1374 return StateMachineImp::kSM_KeepState;
1375 }
1376
1377
1378 int HandleFtmTriggerRates(const EventImp &d)
1379 {
1380 if (!CheckDataSize(d, "FtmControl:TriggerRates", 24+160+640+8))
1381 {
1382 fFtmControlTriggerRateTooLow = 0;
1383 return GetCurrentState();
1384 }
1385
1386 fFtmControlState = d.GetQoS();
1387
1388 const FTM::DimTriggerRates &dim = d.Ref<FTM::DimTriggerRates>();
1389
1390 // New run started
1391 if (dim.fTriggerRate<0)
1392 {
1393 fFtmControlTriggerRateTooLow = -1;
1394 return GetCurrentState();
1395 }
1396
1397 // At the end of a run sometimes the trigger rate drops (the
1398 // service is trasmitted) before the run is 'officially' finished
1399 // by the MCP. Hence, we get a warning. So we have to require
1400 // two consecutive low rates.
1401 if (dim.fTriggerRate<1)
1402 fFtmControlTriggerRateTooLow++;
1403 else
1404 fFtmControlTriggerRateTooLow=0;
1405
1406 const float *brates = dim.fBoardRate; // Board rate
1407 const float *prates = dim.fPatchRate; // Patch rate
1408
1409 // Store a history of the last 60 entries
1410 fFtmControlTriggerRateHist.push_back(dim.fTriggerRate);
1411 if (fFtmControlTriggerRateHist.size()>300)
1412 fFtmControlTriggerRateHist.pop_front();
1413
1414 // FIXME: Add statistics for all kind of rates
1415
1416 WriteBinary(d, "hist-ftmcontrol-triggerrate",
1417 fFtmControlTriggerRateHist, 100);
1418 WriteBinary(d, "cam-ftmcontrol-boardrates",
1419 vector<float>(brates, brates+40), 10);
1420 WriteBinary(d, "cam-ftmcontrol-patchrates",
1421 vector<float>(prates, prates+160), 10);
1422
1423 ostringstream out;
1424 out << setprecision(3);
1425 out << d.GetJavaDate() << '\n';
1426 out << HTML::kWhite << '\t' << dim.fTriggerRate << '\n';
1427
1428 ofstream(fPath+"/trigger.data") << out.str();
1429
1430 const Statistics bstat(vector<float>(brates, brates+ 40));
1431 const Statistics pstat(vector<float>(prates, prates+160));
1432
1433 out.str("");
1434 out << d.GetJavaDate() << '\n';
1435 out << HTML::kWhite << '\t' << bstat.min << '\n';
1436 out << HTML::kWhite << '\t' << bstat.med << '\n';
1437 out << HTML::kWhite << '\t' << bstat.avg << '\n';
1438 out << HTML::kWhite << '\t' << bstat.max << '\n';
1439 ofstream(fPath+"/boardrates.data") << out.str();
1440
1441 out.str("");
1442 out << d.GetJavaDate() << '\n';
1443 out << HTML::kWhite << '\t' << pstat.min << '\n';
1444 out << HTML::kWhite << '\t' << pstat.med << '\n';
1445 out << HTML::kWhite << '\t' << pstat.avg << '\n';
1446 out << HTML::kWhite << '\t' << pstat.max << '\n';
1447 ofstream(fPath+"/patchrates.data") << out.str();
1448
1449 return GetCurrentState();
1450 }
1451
1452 int HandleFtmStaticData(const EventImp &d)
1453 {
1454 if (!CheckDataSize(d, "FtmControl:StaticData", sizeof(FTM::DimStaticData)))
1455 return GetCurrentState();
1456
1457 fFtmControlState = d.GetQoS();
1458
1459 const FTM::DimStaticData &dat = d.Ref<FTM::DimStaticData>();
1460
1461 vector<uint16_t> vecp(dat.fThreshold, dat.fThreshold+160);
1462 vector<uint16_t> vecb(dat.fMultiplicity, dat.fMultiplicity+40);
1463
1464 WriteBinary(d, "cam-ftmcontrol-thresholds-patch", vecp, 1000);
1465 WriteBinary(d, "cam-ftmcontrol-thresholds-board", vecb, 100);
1466
1467 const Statistics statp(vecp);
1468 const Statistics statb(vecb);
1469
1470 fFtmPatchThresholdMed = statp.med;
1471 fFtmBoardThresholdMed = statb.med;
1472
1473 ostringstream out;
1474 out << d.GetJavaDate() << '\n';
1475 out << HTML::kWhite << '\t' << statb.min << '\n';
1476 out << HTML::kWhite << '\t' << statb.med << '\n';
1477 out << HTML::kWhite << '\t' << statb.max << '\n';
1478 ofstream(fPath+"/thresholds-board.data") << out.str();
1479
1480 out.str("");
1481 out << d.GetJavaDate() << '\n';
1482 out << HTML::kWhite << '\t' << statp.min << '\n';
1483 out << HTML::kWhite << '\t' << statp.med << '\n';
1484 out << HTML::kWhite << '\t' << statp.max << '\n';
1485 ofstream(fPath+"/thresholds-patch.data") << out.str();
1486
1487 out.str("");
1488 out << d.GetJavaDate() << '\n';
1489 out << HTML::kWhite << '\t' << statb.med << '\n';
1490 out << HTML::kWhite << '\t' << statp.med << '\n';
1491 ofstream(fPath+"/thresholds.data") << out.str();
1492
1493 out.str("");
1494 out << d.GetJavaDate() << '\n';
1495 out << HTML::kWhite << '\t' << dat.fTriggerInterval << '\n';
1496 out << HTML::kWhite << '\t';
1497 if (dat.HasPedestal())
1498 out << dat.fTriggerSeqPed;
1499 else
1500 out << "&ndash;";
1501 out << ':';
1502 if (dat.HasLPext())
1503 out << dat.fTriggerSeqLPext;
1504 else
1505 out << "&ndash;";
1506 out << ':';
1507 if (dat.HasLPint())
1508 out << dat.fTriggerSeqLPint;
1509 else
1510 out << "&ndash;";
1511 out << '\n';
1512
1513 out << HTML::kWhite << '\t' << (dat.HasTrigger()?"on":"off") << " / " << (dat.HasExt1()?"on":"off") << " / " << (dat.HasExt2()?"on":"off") << '\n';
1514 out << HTML::kWhite << '\t' << (dat.HasVeto()?"on":"off") << " / " << (dat.HasClockConditioner()?"time cal":"marker") << '\n';
1515 out << HTML::kWhite << '\t' << dat.fMultiplicityPhysics << " / " << dat.fMultiplicityCalib << '\n';
1516 out << HTML::kWhite << '\t' << dat.fWindowPhysics << '\t' << dat.fWindowCalib << '\n';
1517 out << HTML::kWhite << '\t' << dat.fDelayTrigger << '\t' << dat.fDelayTimeMarker << '\n';
1518 out << HTML::kWhite << '\t' << dat.fDeadTime << '\n';
1519
1520 int64_t vp = dat.fPrescaling[0];
1521 for (int i=1; i<40; i++)
1522 if (vp!=dat.fPrescaling[i])
1523 vp = -1;
1524
1525 if (vp<0)
1526 out << HTML::kYellow << "\tdifferent\n";
1527 else
1528 out << HTML::kWhite << '\t' << 0.5*vp << "\n";
1529
1530 ofstream(fPath+"/ftm.data") << out.str();
1531
1532 // Active FTUs: IsActive(i)
1533 // Enabled Pix: IsEnabled(i)
1534
1535 return GetCurrentState();
1536 }
1537
1538 int HandleFtmFtuList(const EventImp &d)
1539 {
1540 if (!CheckDataSize(d, "FtmControl:FtuList", sizeof(FTM::DimFtuList)))
1541 return GetCurrentState();
1542
1543 const FTM::DimFtuList &sdata = d.Ref<FTM::DimFtuList>();
1544
1545 ostringstream out;
1546 out << d.GetJavaDate() << '\n';
1547
1548 int cnt = 0;
1549 for (int i=0; i<4; i++)
1550 {
1551 out << HTML::kWhite << '\t';
1552 for (int j=0; j<10; j++)
1553 if (sdata.IsActive(i*10+j))
1554 {
1555 if (sdata.fPing[i*10+j]==1)
1556 {
1557 out << '*';
1558 cnt++;
1559 }
1560 else
1561 out << sdata.fPing[i*10+j];
1562 }
1563 else
1564 out << '-';
1565 out << '\n';
1566 }
1567
1568 fFtmControlFtuOk = cnt==40;
1569
1570 ofstream(fPath+"/ftu.data") << out.str();
1571
1572 return GetCurrentState();
1573 }
1574
1575 int HandleFadEventData(const EventImp &d)
1576 {
1577 if (!CheckDataSize(d, "FadControl:EventData", 23040))
1578 return GetCurrentState();
1579
1580 //const float *avg = d.Ptr<float>();
1581 //const float *rms = d.Ptr<float>(1440*sizeof(float));
1582 const float *dat = d.Ptr<float>(1440*sizeof(float)*2);
1583 //const float *pos = d.Ptr<float>(1440*sizeof(float)*3);
1584
1585 vector<float> max(320, -2);
1586 for (int i=0; i<1440; i++)
1587 {
1588 if (i%9==8)
1589 continue;
1590
1591 const int idx = (fPixelMap.hw(i).hw()/9)*2+fPixelMap.hw(i).group();
1592 const double v = dat[i]/1000;
1593 if (v>max[idx])
1594 max[idx]=v;
1595 }
1596
1597 switch (fFadControlDrsStep)
1598 {
1599 case 0: WriteBinary(d, "cam-fadcontrol-eventdata", max, 2, -1); break;
1600 case 1: WriteBinary(d, "cam-fadcontrol-eventdata", max, 2, 0); break;
1601 default: WriteBinary(d, "cam-fadcontrol-eventdata", max, 0.25, 0); break;
1602 }
1603
1604 return GetCurrentState();
1605 }
1606
1607 int HandleStats(const EventImp &d)
1608 {
1609 if (!CheckDataSize(d, "Stats", 4*8))
1610 {
1611 fFreeSpace = UINT64_MAX;
1612 return GetCurrentState();
1613 }
1614
1615 const DimWriteStatistics::Stats &s = d.Ref<DimWriteStatistics::Stats>();
1616 fFreeSpace = s.freeSpace;
1617
1618 return GetCurrentState();
1619 }
1620
1621 int HandleFscTemperature(const EventImp &d)
1622 {
1623 if (!CheckDataSize(d, "FscControl:Temperature", 240))
1624 return GetCurrentState();
1625
1626 const float *ptr = d.Ptr<float>(4);
1627
1628 double avg = 0;
1629 double rms = 0;
1630 double min = 99;
1631 double max = -99;
1632
1633 int num = 0;
1634 for (const float *t=ptr; t<ptr+31; t++)
1635 {
1636 if (*t==0)
1637 continue;
1638
1639 if (*t>max)
1640 max = *t;
1641
1642 if (*t<min)
1643 min = *t;
1644
1645 avg += *t;
1646 rms += *t * *t;
1647
1648 num++;
1649 }
1650
1651 avg /= num;
1652 rms = sqrt(rms/num-avg*avg);
1653
1654 if (fMagicWeatherHist[kTemp].size()>0)
1655 {
1656 fFscControlTemperatureHist.push_back(avg-fMagicWeatherHist[kTemp].back());
1657 if (fFscControlTemperatureHist.size()>300)
1658 fFscControlTemperatureHist.pop_front();
1659 }
1660
1661 const Statistics stat(fFscControlTemperatureHist);
1662
1663 ostringstream out;
1664 out << setprecision(3);
1665 out << d.GetJavaDate() << '\n';
1666 out << HTML::kWhite << '\t' << fFscControlHumidityAvg << '\n';
1667 out << HTML::kWhite << '\t' << min << '\n';
1668 out << HTML::kWhite << '\t' << avg << '\n';
1669 out << HTML::kWhite << '\t' << max << '\n';
1670 out << HTML::kWhite << '\t' << stat.min << '\n';
1671 out << HTML::kWhite << '\t' << stat.avg << '\n';
1672 out << HTML::kWhite << '\t' << stat.max << '\n';
1673
1674 ofstream(fPath+"/fsc.data") << out.str();
1675
1676 WriteBinary(d, "hist-fsccontrol-temperature",
1677 fFscControlTemperatureHist, 10);
1678
1679 return GetCurrentState();
1680 }
1681
1682 int HandleFscHumidity(const EventImp &d)
1683 {
1684 if (!CheckDataSize(d, "FscControl:Humidity", 5*4))
1685 return GetCurrentState();
1686
1687 const float *ptr = d.Ptr<float>(4);
1688
1689 double avg =0;
1690 int num = 0;
1691
1692 for (const float *t=ptr; t<ptr+4; t++)
1693 if (*t>0 && *t<=100 && t!=ptr+2 /*excl broken sensor*/)
1694 {
1695 avg += *t;
1696 num++;
1697 }
1698
1699 fFscControlHumidityAvg = num>0 ? avg/num : 0;
1700
1701 return GetCurrentState();
1702 }
1703
1704 int HandleRateScanData(const EventImp &d)
1705 {
1706 if (!CheckDataSize(d, "RateScan:Data", 824))
1707 return GetCurrentState();
1708
1709 const uint64_t id = d.Get<uint64_t>();
1710 const float *rate = d.Ptr<float>(20);
1711
1712 if (fRateScanDataId!=id)
1713 {
1714 for (int i=0; i<41; i++)
1715 fRateScanDataHist[i].clear();
1716 fRateScanDataId = id;
1717 }
1718 fRateScanDataHist[0].push_back(log10(rate[0]));
1719
1720 double max = 0;
1721 for (int i=1; i<41; i++)
1722 {
1723 fRateScanDataHist[i].push_back(log10(rate[i]));
1724 if (rate[i]>max)
1725 max = rate[i];
1726 }
1727
1728 // Cycle by time!
1729 fRateScanBoard ++;
1730 fRateScanBoard %= 40;
1731
1732 WriteBinary(d, "hist-ratescan", fRateScanDataHist[0], 10, -2);
1733 WriteBinary(d, "cam-ratescan-board", fRateScanDataHist[fRateScanBoard+1], 10, -4);
1734
1735 ostringstream out;
1736 out << setprecision(3);
1737 out << d.GetJavaDate() << '\n';
1738 out << HTML::kWhite << '\t' << fFtmBoardThresholdMed << '\n';
1739 out << HTML::kWhite << '\t' << fFtmPatchThresholdMed << '\n';
1740 out << HTML::kWhite << '\t' << floor(pow(10, fRateScanDataHist[0].back())+.5) << '\n';
1741 out << HTML::kWhite << '\t' << floor(max+.5) << '\n';
1742
1743 ofstream(fPath+"/ratescan.data") << out.str();
1744
1745 out.str("");
1746 out << d.GetJavaDate() << '\n';
1747 out << HTML::kWhite << '\t' << int(fRateScanBoard) << '\n';
1748 out << HTML::kWhite << '\t' << pow(10, fRateScanDataHist[fRateScanBoard+1].back()) << '\n';
1749
1750 ofstream(fPath+"/ratescan_board.data") << out.str();
1751
1752 return GetCurrentState();
1753 }
1754
1755 int HandleRateControlThreshold(const EventImp &d)
1756 {
1757 if (!CheckDataSize(d, "RateControl:Threshold", 2))
1758 return GetCurrentState();
1759
1760 const uint16_t th = d.Get<uint16_t>();
1761
1762 fRateControlThreshold.push_back(th);
1763 if (fRateControlThreshold.size()>300)
1764 fRateControlThreshold.pop_front();
1765
1766 WriteBinary(d, "hist-ratecontrol-threshold", fRateControlThreshold, 1000);
1767
1768 return GetCurrentState();
1769 }
1770
1771 int HandleChatMsg(const EventImp &d)
1772 {
1773 if (d.GetSize()==0 || d.GetQoS()!=MessageImp::kComment)
1774 return GetCurrentState();
1775
1776 if (Time()<d.GetTime()+boost::posix_time::minutes(1))
1777 SetAudio("message");
1778
1779 fChatHist.add(d.GetText(), d.GetTime());
1780
1781 ostringstream out;
1782 out << setprecision(3);
1783 out << Header(d) << '\n';
1784 out << HTML::kWhite << '\t';
1785 out << "<->" << fChatHist.rget() << "</->";
1786 out << '\n';
1787
1788 ofstream(fPath+"/chat.data") << out.str();
1789
1790 return GetCurrentState();
1791 }
1792
1793 // -------------------------------------------------------------------
1794
1795 int HandleDoTest(const EventImp &d)
1796 {
1797 ostringstream out;
1798 out << d.GetJavaDate() << '\n';
1799
1800 switch (d.GetQoS())
1801 {
1802 case -3: out << HTML::kWhite << "\tNot running\n"; break;
1803 case -2: out << HTML::kBlue << "\tLoading\n"; break;
1804 case -1: out << HTML::kBlue << "\tStarted\n"; break;
1805 default: out << HTML::kGreen << "\tRunning [" << d.GetQoS() << "]\n"; break;
1806 }
1807
1808 ofstream(fPath+"/dotest.data") << out.str();
1809
1810 return StateMachineImp::kSM_KeepState;
1811 }
1812
1813 // -------------------------------------------------------------------
1814
1815 /*
1816 bool CheckEventSize(size_t has, const char *name, size_t size)
1817 {
1818 if (has==size)
1819 return true;
1820
1821 ostringstream msg;
1822 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
1823 Fatal(msg);
1824 return false;
1825 }*/
1826
1827 int Print() const
1828 {
1829 Out() << fDimDNS << endl;
1830 Out() << fDimMcp << endl;
1831 Out() << fDimControl << endl;
1832 Out() << fDimDataLogger << endl;
1833 Out() << fDimDriveControl << endl;
1834 Out() << fDimTimeCheck << endl;
1835 Out() << fDimFadControl << endl;
1836 Out() << fDimFtmControl << endl;
1837 Out() << fDimBiasControl << endl;
1838 Out() << fDimFeedback << endl;
1839 Out() << fDimRateControl << endl;
1840 Out() << fDimFscControl << endl;
1841 Out() << fDimAgilentControl << endl;
1842 Out() << fDimPwrControl << endl;
1843 Out() << fDimLidControl << endl;
1844 Out() << fDimMagicWeather << endl;
1845 Out() << fDimTngWeather << endl;
1846 Out() << fDimRateScan << endl;
1847 Out() << fDimChat << endl;
1848 Out() << fDimSkypeClient << endl;
1849
1850 return GetCurrentState();
1851 }
1852
1853 string GetStateHtml(const DimState &state, int green) const
1854 {
1855 if (!state.online())
1856 return HTML::kWhite+"\t&mdash;\n";
1857
1858 if (&state==&fDimControl)
1859 return HTML::kGreen +'\t'+(state.state()==0?"Idle":fDimControl.shortmsg)+'\n';
1860
1861 const State rc = state.description();
1862
1863 // Sate not found in list, server online (-3: offline; -2: not found)
1864 if (rc.index==-2)
1865 {
1866 ostringstream out;
1867 out << HTML::kWhite << '\t' << state.state() << '\n';
1868 return out.str();
1869 }
1870
1871 //ostringstream msg;
1872 //msg << HTML::kWhite << '\t' << rc.name << " [" << rc.index << "]\n";
1873 //return msg.str();
1874
1875 if (rc.index<0)
1876 return HTML::kWhite + "\t&mdash;\n";
1877
1878 string col = HTML::kGreen;
1879 if (rc.index<green)
1880 col = HTML::kYellow;
1881 if (rc.index>0xff)
1882 col = HTML::kRed;
1883
1884 return col + '\t' + rc.name + '\n';
1885 }
1886
1887 bool SetError(bool b, const string &err)
1888 {
1889 if (!b)
1890 {
1891 fErrorList.erase(err);
1892 return 0;
1893 }
1894
1895 const bool isnew = fErrorList.insert(err).second;
1896 if (isnew)
1897 fErrorHist.add(err);
1898
1899 return isnew;
1900 }
1901
1902#ifdef HAVE_NOVA
1903
1904 vector<pair<ln_equ_posn, double>> fMoonCoords;
1905
1906 void CalcMoonCoords(double jd)
1907 {
1908 jd = floor(jd);
1909
1910 fMoonCoords.clear();
1911 for (double h=0; h<1; h+=1./(24*12))
1912 {
1913 ln_equ_posn moon;
1914 ln_get_lunar_equ_coords_prec(jd+h, &moon, 0.01);
1915
1916 const double disk = ln_get_lunar_disk(jd+h);
1917
1918 fMoonCoords.push_back(make_pair(moon, disk));
1919 }
1920 }
1921
1922 pair<vector<float>, pair<Time, float>> GetVisibility(ln_equ_posn *src, ln_lnlat_posn *observer, double jd)
1923 {
1924 jd = floor(jd);
1925
1926 const double jd0 = fmod(fSun.fSetAstronomical.JD(), 1);
1927 const double jd1 = fmod(fSun.fRiseAstronomical.JD(), 1);
1928
1929 ln_equ_posn moon;
1930 ln_equ_posn *pos = src ? src : &moon;
1931
1932 double max = 0;
1933 double maxjd = 0;
1934
1935 int cnt = 0;
1936
1937 int i=0;
1938
1939 vector<float> alt;
1940 for (double h=0; h<1; h+=1./(24*12), i++)
1941 {
1942 if (src==0)
1943 moon = fMoonCoords[i].first; //ln_get_lunar_equ_coords_prec(jd+h, &moon, 0.01);
1944
1945 ln_hrz_posn hrz;
1946 ln_get_hrz_from_equ(pos, observer, jd+h, &hrz);
1947
1948 if (h>jd0 && h<jd1)
1949 alt.push_back(hrz.alt);
1950
1951 if (hrz.alt>max)
1952 {
1953 max = hrz.alt;
1954 maxjd = jd+h;
1955 }
1956
1957 if (h>jd0 && h<jd1 && hrz.alt>15)
1958 cnt++;
1959 }
1960
1961 if (max<=15 || cnt==0)
1962 return make_pair(vector<float>(), make_pair(Time(), 0));
1963
1964 return make_pair(alt, make_pair(maxjd, maxjd>jd+jd0&&maxjd<jd+jd1?max:0));
1965 }
1966
1967 pair<vector<float>, pair<Time, float>> GetLightCondition(ln_equ_posn *src, ln_lnlat_posn *observer, double jd)
1968 {
1969 jd = floor(jd);
1970
1971 const double jd0 = fmod(fSun.fSetAstronomical.JD(), 1);
1972 const double jd1 = fmod(fSun.fRiseAstronomical.JD(), 1);
1973
1974 double max = -1;
1975 double maxjd = 0;
1976
1977 int cnt = 0;
1978 int i = 0;
1979
1980 vector<float> vec;
1981 for (double h=0; h<1; h+=1./(24*12), i++)
1982 {
1983 double cur = -1;
1984
1985 if (h>jd0 && h<jd1)
1986 {
1987 ln_equ_posn moon = fMoonCoords[i].first;//ln_get_lunar_equ_coords_prec(jd+h, &moon, 0.01);
1988 const double disk = fMoonCoords[i].second;//ln_get_lunar_disk(jd+h);
1989
1990 ln_hrz_posn hrz;
1991 ln_get_hrz_from_equ(&moon, observer, jd+h, &hrz);
1992
1993 Moon m;
1994 m.ra = moon.ra;
1995 m.dec = moon.dec;
1996
1997 const double angle = m.Angle(src->ra, src->dec);
1998
1999 const double lc = angle*hrz.alt*pow(disk, 6)/360/360;
2000
2001 cur = 7.7+4942*lc;
2002
2003 vec.push_back(cur); // Covert LC to pixel current in uA
2004 }
2005
2006 if (cur>max)
2007 {
2008 max = cur;
2009 maxjd = jd+h;
2010 }
2011
2012 if (h>jd0 && h<jd1 && cur>0)
2013 cnt++;
2014 }
2015
2016 if (max<=0 || cnt==0)
2017 return make_pair(vector<float>(), make_pair(Time(), 0));
2018
2019 return make_pair(vec, make_pair(maxjd, maxjd>jd+jd0&&maxjd<jd+jd1?max:-1));
2020 }
2021#endif
2022
2023 void UpdateAstronomy()
2024 {
2025 const double lon = -(17.+53./60+26.525/3600);
2026 const double lat = 28.+45./60+42.462/3600;
2027
2028 Time now;
2029
2030 CalcMoonCoords(now.JD());
2031
2032 fSun = Sun (lon, lat, now);
2033 fMoon = Moon(lon, lat, now);
2034
2035 vector<string> color(8, HTML::kWhite);
2036 color[fSun.state%8] = HTML::kBlue;
2037
2038 ostringstream out;
2039 out << setprecision(3);
2040 out << now.JavaDate() << '\n';
2041 out << color[0] << '\t' << fSun.fRiseDarkTime.GetAsStr("%H:%M") << '\n';
2042 out << color[1] << '\t' << fSun.fRiseAstronomical.GetAsStr("%H:%M") << '\n';
2043 out << color[2] << '\t' << fSun.fRiseCivil.GetAsStr("%H:%M") << '\n';
2044 out << color[3] << '\t' << fSun.fRiseDayTime.GetAsStr("%H:%M") << '\n';
2045
2046 out << color[4] << '\t' << fSun.fSetDayTime.GetAsStr("%H:%M") << '\n';
2047 out << color[5] << '\t' << fSun.fSetCivil.GetAsStr("%H:%M") << '\n';
2048 out << color[6] << '\t' << fSun.fSetAstronomical.GetAsStr("%H:%M") << '\n';
2049 out << color[7] << '\t' << fSun.fSetDarkTime.GetAsStr("%H:%M") << '\n';
2050
2051 ofstream(fPath+"/sun.data") << out.str();
2052
2053 color.assign(3, HTML::kWhite);
2054 color[fMoon.state%3] = HTML::kBlue;
2055
2056 out.str("");
2057 out << now.JavaDate() << '\n';
2058
2059 out << color[0] << '\t' << fMoon.fRise.GetAsStr("%H:%M") << '\n';
2060 out << color[1] << '\t' << fMoon.fTransit.GetAsStr("%H:%M") << '\n';
2061 out << color[2] << '\t' << fMoon.fSet.GetAsStr("%H:%M") << '\n';
2062
2063 out << (fSun.isday?HTML::kWhite:fMoon.color) << '\t' << fMoon.description << '\n';
2064
2065 if (!fMoon.visible)
2066 out << HTML::kWhite << "\t&mdash;\t\n";
2067 else
2068 {
2069 string col = HTML::kWhite;
2070 if (!fSun.isday)
2071 {
2072 col = HTML::kGreen;
2073 if (fMoon.zd>25)
2074 col = HTML::kYellow;
2075 if (fMoon.zd>45 && fMoon.zd<80)
2076 col = HTML::kRed;
2077 if (fMoon.zd>=80)
2078 col = HTML::kRed;
2079 }
2080 out << col << '\t' << fMoon.zd << '\t' << GetDir(fMoon.az) << '\n';
2081 }
2082
2083 ostringstream out2, out3, out4;
2084 out2 << setprecision(3);
2085 out2 << now.JavaDate() << '\n';
2086 out3 << now.JavaDate() << '\n';
2087 out4 << now.JavaDate() << '\n';
2088
2089 multimap<Time, pair<string, float>> culmination;
2090 multimap<Time, pair<string, float>> lightcond;
2091 vector<vector<float>> alt;
2092 vector<vector<float>> cur;
2093
2094#ifdef HAVE_NOVA
2095 ln_lnlat_posn observer;
2096 observer.lng = lon;
2097 observer.lat = lat;
2098
2099 const pair<vector<float>, pair<Time, float>> vism = GetVisibility(0, &observer, now.JD());
2100 if (vism.first.size()>0)
2101 {
2102 alt.push_back(vism.first);
2103 culmination.insert(make_pair(vism.second.first, make_pair("Moon", vism.second.second)));
2104 }
2105#endif
2106
2107#ifdef HAVE_SQL
2108 try
2109 {
2110 const mysqlpp::StoreQueryResult res =
2111 Database(fDatabase).query("SELECT fSourceName, fRightAscension, fDeclination FROM source WHERE fSourceTypeKEY=1").store();
2112
2113 out << HTML::kWhite << '\t';
2114 out2 << HTML::kWhite << '\t';
2115 out3 << HTML::kWhite << '\t';
2116 out4 << HTML::kWhite << '\t';
2117
2118 for (vector<mysqlpp::Row>::const_iterator v=res.begin(); v<res.end(); v++)
2119 {
2120 const string name = (*v)[0].c_str();
2121 const double ra = (*v)[1];
2122 const double dec = (*v)[2];
2123#ifdef HAVE_NOVA
2124 ln_equ_posn pos;
2125 pos.ra = ra*15;
2126 pos.dec = dec;
2127
2128 ln_hrz_posn hrz;
2129 ln_get_hrz_from_equ(&pos, &observer, now.JD(), &hrz);
2130
2131 const pair<vector<float>, pair<Time, float>> vis = GetVisibility(&pos, &observer, now.JD());
2132 if (vis.first.size()>0)
2133 {
2134 alt.push_back(vis.first);
2135 culmination.insert(make_pair(vis.second.first, make_pair(name, vis.second.second)));
2136
2137 const pair<vector<float>, pair<Time, float>> lc = GetLightCondition(&pos, &observer, now.JD());
2138 if (lc.first.size()>0)
2139 {
2140 cur.push_back(lc.first);
2141 lightcond.insert(make_pair(lc.second.first, make_pair(name, lc.second.second)));
2142 }
2143 }
2144
2145 string col = HTML::kWhite;
2146 if (hrz.alt>5)
2147 col = HTML::kRed;
2148 if (hrz.alt>25)
2149 col = HTML::kYellow;
2150 if (hrz.alt>60)
2151 col = HTML::kGreen;
2152
2153 out2 << "<tr bgcolor='" << col << "'>";
2154 out2 << "<td>" << name << "</td>";
2155 if (hrz.alt>5)
2156 {
2157 out2 << "<td>" << 90-hrz.alt << "&deg;</td>";
2158 out2 << "<td>" << GetDir(hrz.az) << "</td>";
2159 }
2160 else
2161 out2 << "<td/><td/>";
2162 out2 << "</tr>";
2163#endif
2164 const int32_t angle = fMoon.Angle(ra, dec);
2165
2166 out << "<tr bgcolor='" << Moon::Color(angle) << "'>";
2167 out << "<td>" << name << "</td>";
2168 out << "<td>" << round(angle) << "&deg;</td>";
2169 out << "</tr>";
2170 }
2171
2172 for (auto it=culmination.begin(); it!=culmination.end(); it++)
2173 {
2174 if (it!=culmination.begin())
2175 out3 << ", ";
2176 out3 << "<B>" << it->second.first << "</B>";
2177 if (it->second.second>0)
2178 out3 << " [" << nearbyint(90-it->second.second) << "&deg;]";
2179 }
2180
2181 out4 << setprecision(3);
2182 for (auto it=lightcond.begin(); it!=lightcond.end(); it++)
2183 {
2184 if (it!=lightcond.begin())
2185 out4 << ", ";
2186 out4 << "<B>" << it->second.first << "</B>";
2187 if (it->second.second>0)
2188 out4 << " [" << nearbyint(it->second.second) << "]";
2189 }
2190
2191 if (fSun.fSetAstronomical>fSun.fRiseAstronomical)
2192 fSun.fSetAstronomical += boost::posix_time::hours(24);
2193
2194 ostringstream title;
2195 title << fSun.fSetAstronomical.GetAsStr("%H:%M");
2196 title << " / ";
2197 title << ((fSun.fRiseAstronomical-fSun.fSetAstronomical)/20).minutes();
2198 title << "' / ";
2199 title << fSun.fRiseAstronomical.GetAsStr("%H:%M");
2200
2201 out << '\n';
2202 out2 << '\n';
2203 out3 << '\n';
2204 out4 << '\n';
2205 out << HTML::kWhite << '\t' << Time()-now << '\n';
2206 out2 << HTML::kWhite << '\t' << Time()-now << '\n';
2207
2208 WriteBinaryVec(now, "hist-visibility", alt, 75, 15, "Alt "+title.str());
2209 WriteBinaryVec(now, "hist-current-prediction", cur, 100, 0, "I " +title.str());
2210 }
2211 catch (const exception &e)
2212 {
2213 out << '\n';
2214 out2 << '\n';
2215 out << HTML::kWhite << '\t' << "ERROR - "+string(e.what()) << '\n';
2216 out2 << HTML::kWhite << '\t' << "ERROR - "+string(e.what()) << '\n';
2217 out3 << HTML::kWhite << '\t' << "ERROR - "+string(e.what()) << '\n';
2218 out4 << HTML::kWhite << '\t' << "ERROR - "+string(e.what()) << '\n';
2219 }
2220#endif
2221
2222 ofstream(fPath+"/moon.data") << out.str();
2223 ofstream(fPath+"/source-list.data") << out2.str();
2224 ofstream(fPath+"/visibility.data") << out3.str();
2225 ofstream(fPath+"/current-prediction.data") << out4.str();
2226 }
2227
2228 int Execute()
2229 {
2230 // Dispatch (execute) at most one handler from the queue. In contrary
2231 // to run_one(), it doesn't wait until a handler is available
2232 // which can be dispatched, so poll_one() might return with 0
2233 // handlers dispatched. The handlers are always dispatched/executed
2234 // synchronously, i.e. within the call to poll_one()
2235 //poll_one();
2236
2237 Time now;
2238 if (now-fLastUpdate<boost::posix_time::seconds(1))
2239 return fDimDNS.online() ? kStateRunning : kStateDimNetworkNA;
2240 fLastUpdate=now;
2241
2242 // ==============================================================
2243
2244 const bool data_taking =
2245 fDimMcp.state()==MCP::State::kTriggerOn ||
2246 fDimMcp.state()==MCP::State::kTakingData;
2247
2248 const bool data_run =
2249 fMcpConfigurationName=="data" ||
2250 fMcpConfigurationName=="data-rt";
2251
2252 const bool bias_on =
2253 fDimBiasControl.state()==BIAS::State::kRamping ||
2254 fDimBiasControl.state()==BIAS::State::kOverCurrent ||
2255 fDimBiasControl.state()==BIAS::State::kVoltageOn;
2256
2257 const bool haderr = fErrorList.size()>0;
2258
2259 bool newerr = false;
2260
2261 newerr |= SetError(!fDimDNS.online(),
2262 "<b><#darkred>DIM network not available</#></b>");
2263 newerr |= SetError(!fDimControl.online(),
2264 "<b>no dimctrl server available</b>");
2265 newerr |= SetError(fDimDataLogger.state()<20 || fDimDataLogger.state()>40,
2266 "<b>datalogger not ready</b>");
2267
2268 //newerr |= SetError(fDimDriveControl.state()==Drive::State::kLocked,
2269 // "<b><#darkred>Drive in LOCKED state, drive was automatically parked</#></b>");
2270
2271 newerr |= SetError(fDimDriveControl.state()>0xff && data_taking && data_run,
2272 "Drive in ERROR state during data-taking");
2273 newerr |= SetError(fDriveControlMoonDist>155,
2274 "Moon within the field-of-view of the cones");
2275 newerr |= SetError(fDriveControlMoonDist>=0 && fDriveControlMoonDist<3,
2276 "Moon within the field-of-view of the camera");
2277
2278 newerr |= SetError(fDimBiasControl.state()<BIAS::State::kRamping && data_taking,
2279 "BIAS not operating during data-taking");
2280 newerr |= SetError(fDimBiasControl.state()==BIAS::State::kOverCurrent,
2281 "BIAS channels in OverCurrent");
2282 newerr |= SetError(fDimBiasControl.state()==BIAS::State::kNotReferenced,
2283 "BIAS voltage not at reference");
2284
2285
2286 newerr |= SetError(bias_on && fFeedbackCalibration.size()>0 && fBiasControlCurrentMed>80,
2287 "Median current exceeds 80&micro;A/pix exceeds 80&micro;A/pix");
2288 newerr |= SetError(bias_on && fFeedbackCalibration.size()>0 && fBiasControlCurrentMax>100,
2289 "Maximum current exceeds 100&micro;A/pix");
2290
2291 newerr |= SetError(fFscControlHumidityAvg>60,
2292 "Average camera humidity exceed 60%");
2293
2294 newerr |= SetError(fMagicWeatherHist[kHum].size()>0 && fMagicWeatherHist[kHum].back()>98 && data_taking,
2295 "Outside humidity exceeds 98% during data-taking");
2296 newerr |= SetError(fMagicWeatherHist[kGusts].size()>0 && fMagicWeatherHist[kGusts].back()>98 && (fDimDriveControl.state()==Drive::State::kTracking||fDimDriveControl.state()==Drive::State::kOnTrack),
2297 "Wind gusts exceed 50km/h during tracking");
2298
2299 newerr |= SetError(fDimFscControl.state()>=FSC::State::kConnected && fFscControlTemperatureHist.size()>0 && fFscControlTemperatureHist.back()>8,
2300 "Sensor temperature exceeds outside temperature by more than 8&deg;C");
2301
2302 newerr |= SetError(fFtmControlTriggerRateTooLow>2 && fDimFtmControl.state()==FTM::State::kTriggerOn,
2303 "Trigger rate below 1Hz while trigger switched on");
2304
2305 newerr |= SetError((fDimFtmControl.state()==FTM::State::kTriggerOn||fDimFtmControl.state()==FTM::State::kIdle) &&
2306 (fFtmControlState&FTM::kFtmLocked)==0,
2307 "FTM - clock conditioner not locked!");
2308
2309 newerr |= SetError(fDimTimeCheck.state()==1,
2310 "Warning NTP time difference of drive PC exceeds 1s");
2311 newerr |= SetError(fDimTimeCheck.state()<1,
2312 "Warning timecheck not running");
2313
2314 newerr |= SetError(fDimFeedback.state()!=Feedback::State::kCalibrating &&
2315 fDimBiasControl.state()==BIAS::State::kVoltageOn &&
2316 fBiasControlVoltageMed>3 &&
2317 fFeedbackCalibration.size()==0,
2318 "Bias voltage switched on, but bias crate not calibrated");
2319
2320 newerr |= SetError(fLastRunFinishedWithZeroEvents,
2321 "Last run finshed, but contained zero events.");
2322
2323 newerr |= SetError(fFreeSpace<50000000000,
2324 "Less than 50GB disk space left.");
2325
2326 for (auto it=fControlAlarmHist.begin(); it!=fControlAlarmHist.end(); it++)
2327 {
2328 newerr |= SetError(it->time.IsValid(), it->msg);
2329 if (!it->time)
2330 fControlAlarmHist.erase(it);
2331 }
2332
2333 fLastRunFinishedWithZeroEvents = false;
2334
2335 // FTM in Connected instead of Idle --> power cyclen
2336
2337 /* // Check offline and disconnected status?
2338 Out() << fDimMcp << endl;
2339 Out() << fDimControl << endl;
2340 Out() << fDimDataLogger << endl;
2341 Out() << fDimDriveControl << endl;
2342 Out() << fDimFadControl << endl;
2343 Out() << fDimFtmControl << endl;
2344 Out() << fDimBiasControl << endl;
2345 Out() << fDimFeedback << endl;
2346 Out() << fDimRateControl << endl;
2347 Out() << fDimFscControl << endl;
2348 Out() << fDimMagicWeather << endl;
2349 Out() << fDimRateScan << endl;
2350 Out() << fDimChat << endl;
2351 */
2352
2353 // FTU in error
2354 // FAD lost
2355
2356 // --------------------------------------------------------------
2357 ostringstream out;
2358
2359 if (newerr)
2360 {
2361 SetAudio("error");
2362
2363 out << now.JavaDate() << '\n';
2364 out << HTML::kWhite << '\t';
2365 out << "<->" << fErrorHist.rget() << "<->";
2366 out << '\n';
2367
2368 ofstream(fPath+"/errorhist.data") << out.str();
2369 }
2370
2371 out.str("");
2372 out << Header(now) << '\t' << (fErrorList.size()>0) << '\t' << (fDimControl.state()>0) << '\n';
2373 out << setprecision(3);
2374 out << HTML::kWhite << '\t';
2375 for (auto it=fErrorList.begin(); it!=fErrorList.end(); it++)
2376 out << *it << "<br/>";
2377 out << '\n';
2378
2379 if (haderr || fErrorList.size()>0)
2380 ofstream(fPath+"/error.data") << out.str();
2381
2382 // ==============================================================
2383
2384 out.str("");
2385 out << Header(now) << '\t' << (fErrorList.size()>0) << '\t' << (fDimControl.state()>0) << '\n';
2386 out << setprecision(3);
2387
2388 // -------------- System status --------------
2389 if (fDimDNS.online() && fDimMcp.state()>=MCP::State::kIdle) // Idle
2390 {
2391 string col = HTML::kBlue;
2392 switch (fMcpConfigurationState)
2393 {
2394 case MCP::State::kIdle:
2395 col = HTML::kWhite;
2396 break;
2397 case MCP::State::kConfiguring1:
2398 case MCP::State::kConfiguring2:
2399 case MCP::State::kConfiguring3:
2400 case MCP::State::kConfigured:
2401 case MCP::State::kTriggerOn:
2402 col = HTML::kBlue;
2403 break;
2404 case MCP::State::kTakingData:
2405 col = HTML::kBlue;
2406 if (fDimFadControl.state()==FAD::State::kWritingData)
2407 col = HTML::kGreen;
2408 break;
2409 }
2410
2411 const bool other =
2412 fDimRateControl.state()==RateControl::State::kSettingGlobalThreshold ||
2413 fDimRateScan.state()==RateScan::State::kInProgress;
2414
2415 if (other)
2416 col = HTML::kBlue;
2417
2418 out << col << '\t';
2419
2420 if (!other)
2421 {
2422 const string conf = fMcpConfigurationName.length()>0?" ["+fMcpConfigurationName+"]":"";
2423 switch (fMcpConfigurationState)
2424 {
2425 case MCP::State::kIdle:
2426 out << "Idle" << conf;
2427 break;
2428 case MCP::State::kConfiguring1:
2429 case MCP::State::kConfiguring2:
2430 case MCP::State::kConfiguring3:
2431 out << "Configuring" << conf;
2432 break;
2433 case MCP::State::kConfigured:
2434 out << "Configured" << conf;
2435 break;
2436 case MCP::State::kTriggerOn:
2437 case MCP::State::kTakingData:
2438 out << fMcpConfigurationName;
2439 if (fFadControlDrsRuns[2]>0)
2440 out << "(" << fFadControlDrsRuns[2] << ")";
2441 break;
2442 }
2443 }
2444 else
2445 if (fDimRateControl.state()==RateControl::State::kSettingGlobalThreshold)
2446 out << "Calibrating threshold";
2447 else
2448 if (fDimRateScan.state()==RateScan::State::kInProgress)
2449 out << "Rate scan in progress";
2450
2451 if (fMcpConfigurationState>MCP::State::kConfigured &&
2452 fDimRateControl.state()!=RateControl::State::kSettingGlobalThreshold)
2453 {
2454 ostringstream evt;
2455 if (fMcpConfigurationMaxEvents>0)
2456 {
2457 const int64_t de = int64_t(fMcpConfigurationMaxEvents) - int64_t(fFadControlNumEvents);
2458 if (de>=0 && fMcpConfigurationState==MCP::State::kTakingData)
2459 evt << de;
2460 else
2461 evt << fMcpConfigurationMaxEvents;
2462 }
2463 else
2464 {
2465 if (fMcpConfigurationState==MCP::State::kTakingData)
2466 {
2467 if (fFadControlNumEvents>2999)
2468 evt << floor(fFadControlNumEvents/1000) << 'k';
2469 else
2470 evt << fFadControlNumEvents;
2471 }
2472 }
2473
2474 ostringstream tim;
2475 if (fMcpConfigurationMaxTime>0)
2476 {
2477 const uint32_t dt = (Time()-fMcpConfigurationRunStart).total_seconds();
2478 if (dt<=fMcpConfigurationMaxTime && fMcpConfigurationState==MCP::State::kTakingData)
2479 tim << fMcpConfigurationMaxTime-dt << 's';
2480 else
2481 tim << fMcpConfigurationMaxTime << 's';
2482 }
2483 else
2484 {
2485 if (fMcpConfigurationState==MCP::State::kTakingData)
2486 tim << fMcpConfigurationRunStart.SecondsTo();
2487 }
2488
2489 const bool has_evt = !evt.str().empty();
2490 const bool has_tim = !tim.str().empty();
2491
2492 if (has_evt || has_tim)
2493 out << " [";
2494 out << evt.str();
2495 if (has_evt && has_tim)
2496 out << '/';
2497 out << tim.str();
2498 if (has_evt || has_tim)
2499 out << ']';
2500 }
2501 }
2502 else
2503 out << HTML::kWhite;
2504 out << '\n';
2505
2506 // ------------------ Drive -----------------
2507 if (fDimDNS.online() && fDimDriveControl.state()>=Drive::State::kArmed) // Armed, Moving, Tracking, OnTrack, Error
2508 {
2509 const uint32_t dev = fDriveControlTrackingDevHist.size()>0 ? round(fDriveControlTrackingDevHist.back()) : 0;
2510 const State rc = fDimDriveControl.description();
2511 string col = HTML::kGreen;
2512 if (fDimDriveControl.state()==Drive::State::kMoving) // Moving
2513 col = HTML::kBlue;
2514 if (fDimDriveControl.state()==Drive::State::kArmed) // Armed
2515 col = HTML::kWhite;
2516 if (fDimDriveControl.state()==Drive::State::kTracking || fDimDriveControl.state()==Drive::State::kOnTrack) // Tracking
2517 {
2518 if (dev>60) // ~1.5mm
2519 col = HTML::kYellow;
2520 if (dev>120) // ~1/4 of a pixel ~ 2.5mm
2521 col = HTML::kRed;
2522 }
2523 if (fDimDriveControl.state()==0x100)
2524 col = HTML::kRed;
2525 out << col << '\t';
2526
2527 //out << rc.name << '\t';
2528 out << fDriveControlPointingAz << ' ';
2529 out << fDriveControlPointingZd << "&deg;";
2530 out << setprecision(2);
2531 if (fDimDriveControl.state()==Drive::State::kTracking || fDimDriveControl.state()==Drive::State::kOnTrack)
2532 {
2533 out << " &plusmn; " << dev << '"';
2534 if (!fDriveControlSourceName.empty())
2535 out << " [" << fDriveControlSourceName << ']';
2536 }
2537 if (fDimDriveControl.state()==Drive::State::kMoving)
2538 out << " &#10227;";
2539 out << setprecision(3);
2540 }
2541 else
2542 out << HTML::kWhite << '\t';
2543
2544 if (fSun.time.IsValid() && fMoon.time.IsValid())
2545 {
2546 if (fSun.visible)
2547 {
2548 out << " &#9788;";
2549 if (fDimDriveControl.state()<Drive::State::kArmed)
2550 out << " [" << fSun.fSetCivil.MinutesTo() << "&darr;]";
2551 }
2552 else
2553 if (!fSun.visible && fMoon.visible)
2554 {
2555 out << " &#9790;";
2556 if (fDimDriveControl.state()<Drive::State::kArmed)
2557 out << " [" << fMoon.disk << "%]";
2558 }
2559 }
2560 if (fDimDNS.online() && fDimDriveControl.state()==0x100)
2561 out << " <ERR>";
2562 if (fDimDNS.online() && fDimDriveControl.state()==Drive::State::kLocked)
2563 out << " &otimes;";
2564 out << '\n';
2565
2566 // ------------------- FSC ------------------
2567 if (fDimDNS.online() && fDimFscControl.state()>FSC::State::kDisconnected && fFscControlTemperatureHist.size()>0)
2568 {
2569 string col = HTML::kGreen;
2570 if (fFscControlTemperatureHist.back()>5)
2571 col = HTML::kYellow;
2572 if (fFscControlTemperatureHist.back()>8)
2573 col = HTML::kRed;
2574
2575 out << col << '\t' << fFscControlTemperatureHist.back() << '\n';
2576 }
2577 else
2578 out << HTML::kWhite << '\n';
2579
2580 // --------------- MagicWeather -------------
2581 if (fDimDNS.online() && fDimMagicWeather.state()==MagicWeather::State::kReceiving && fMagicWeatherHist[kWeatherBegin].size()>0)
2582 {
2583 /*
2584 const float diff = fMagicWeatherHist[kTemp].back()-fMagicWeatherHist[kDew].back();
2585 string col1 = HTML::kRed;
2586 if (diff>0.3)
2587 col1 = HTML::kYellow;
2588 if (diff>0.7)
2589 col1 = HTML::kGreen;
2590 */
2591
2592 const float wind = fMagicWeatherHist[kGusts].back();
2593 const float hum = fMagicWeatherHist[kHum].back();
2594 string col = HTML::kGreen;
2595 if (wind>35 || hum>95)
2596 col = HTML::kYellow;
2597 if (wind>45 || hum>98)
2598 col = HTML::kRed;
2599
2600 out << col << '\t';
2601 out << fMagicWeatherHist[kHum].back() << '\t';
2602 out << setprecision(2);
2603 out << fMagicWeatherHist[kGusts].back() << '\n';
2604 out << setprecision(3);
2605 }
2606 else
2607 out << HTML::kWhite << "\n";
2608
2609 // --------------- FtmControl -------------
2610 if (fDimDNS.online() && fDimFtmControl.state()==FTM::State::kTriggerOn)
2611 {
2612 string col = HTML::kGreen;
2613 if (fFtmControlTriggerRateHist.size()>0)
2614 {
2615 if (fFtmControlTriggerRateHist.back()<15)
2616 col = HTML::kYellow;
2617 if (fFtmControlTriggerRateHist.back()>100)
2618 col = HTML::kRed;
2619
2620 out << col << '\t' << fFtmControlTriggerRateHist.back() << " Hz";
2621 }
2622
2623 if (fDimBiasControl.state()==BIAS::State::kVoltageOn)
2624 out << " (" << fFtmPatchThresholdMed << ')';
2625 out << '\n';
2626 }
2627 else
2628 out << HTML::kWhite << '\n';
2629
2630 // --------------- BiasControl -------------
2631 if (fDimDNS.online() &&
2632 (fDimBiasControl.state()==BIAS::State::kRamping ||
2633 fDimBiasControl.state()==BIAS::State::kOverCurrent ||
2634 fDimBiasControl.state()==BIAS::State::kVoltageOn ||
2635 fDimBiasControl.state()==BIAS::State::kVoltageOff))
2636 {
2637 const bool off = fDimBiasControl.state()==BIAS::State::kVoltageOff;
2638 const bool oc = fDimBiasControl.state()==BIAS::State::kOverCurrent;
2639
2640 string col = fBiasControlVoltageMed>3?HTML::kGreen:HTML::kWhite;
2641 if (fDimBiasControl.state()!=BIAS::State::kVoltageOff)
2642 {
2643 if (fBiasControlCurrentMed>60 || fBiasControlCurrentMax>80)
2644 col = HTML::kYellow;
2645 if (fBiasControlCurrentMed>70 || fBiasControlCurrentMax>90)
2646 col = HTML::kRed;
2647 }
2648
2649 // Bias in overcurrent => Red
2650 if (fDimBiasControl.state()==BIAS::State::kOverCurrent)
2651 col = HTML::kRed;
2652
2653 // MCP in ReadyForDatataking/Configuring/Configured/TriggerOn/TakingData
2654 // and Bias not in "data-taking state' => Red
2655 if (fMcpConfigurationState>MCP::State::kIdle &&
2656 fDimBiasControl.state()!=BIAS::State::kVoltageOn &&
2657 fDimBiasControl.state()!=BIAS::State::kVoltageOff)
2658 col = HTML::kRed;
2659
2660 const bool cal = fFeedbackCalibration.size();
2661
2662 // Feedback is currently calibrating => Blue
2663 if (fDimFeedback.state()==Feedback::State::kCalibrating)
2664 {
2665 out << HTML::kBlue << '\t';
2666 out << "***\t";
2667 out << "***\t";
2668 }
2669 else
2670 {
2671 out << setprecision(2);
2672 out << col << '\t';
2673 out << (off ? 0 : fBiasControlCurrentMed) << '\t';
2674 if (oc)
2675 out << "(OC) ";
2676 else
2677 {
2678 if (cal)
2679 out << (off ? 0 : fBiasControlCurrentMax);
2680 else
2681 out << "&mdash; ";
2682 }
2683 out << '\t';
2684 out << setprecision(3);
2685 }
2686 if (cal && fDimFeedback.state()!=Feedback::State::kCalibrating)
2687 out << setprecision(2) << fBiasControlPowerTot << " W" << setprecision(3);
2688 else
2689 out << (off ? 0 : fBiasControlVoltageMed) << " V";
2690 out << '\n';
2691 }
2692 else
2693 out << HTML::kWhite << '\n';
2694
2695 ofstream(fPath+"/fact.data") << out.str();
2696
2697 // ==============================================================
2698
2699 out.str("");
2700 out << Header(now) << '\t' << (fErrorList.size()>0) << '\t' << (fDimControl.state()>0) << '\n';
2701
2702 if (!fDimDNS.online())
2703 out << HTML::kWhite << "\tOffline\n\n\n\n\n\n\n\n\n\n\n\n\n";
2704 else
2705 {
2706 ostringstream dt;
2707 dt << (Time()-fRunTime);
2708
2709 out << HTML::kGreen << '\t' << fDimDNS.version() << '\n';
2710
2711 out << GetStateHtml(fDimControl, 0);
2712 out << GetStateHtml(fDimMcp, 4);
2713 out << GetStateHtml(fDimDataLogger, 1);
2714 out << GetStateHtml(fDimDriveControl, 2);
2715 out << GetStateHtml(fDimTimeCheck, 1);
2716 out << GetStateHtml(fDimFadControl, FAD::State::kConnected);
2717 out << GetStateHtml(fDimFtmControl, FTM::State::kConnected);
2718 out << GetStateHtml(fDimBiasControl, BIAS::State::kConnected);
2719 out << GetStateHtml(fDimFeedback, 4);
2720 out << GetStateHtml(fDimRateControl, 4);
2721 out << GetStateHtml(fDimFscControl, 2);
2722 out << GetStateHtml(fDimAgilentControl, 3);
2723 out << GetStateHtml(fDimPwrControl, 3);
2724 out << GetStateHtml(fDimLidControl, 2);
2725 out << GetStateHtml(fDimRateScan, 4);
2726 out << GetStateHtml(fDimMagicWeather, 2);
2727 out << GetStateHtml(fDimTngWeather, 2);
2728 out << GetStateHtml(fDimChat, 0);
2729 out << GetStateHtml(fDimSkypeClient, 1);
2730
2731 string col = HTML::kRed;
2732 if (fFreeSpace>uint64_t(199999999999))
2733 col = HTML::kYellow;
2734 if (fFreeSpace>uint64_t(999999999999))
2735 col = HTML::kGreen;
2736 if (fFreeSpace==UINT64_MAX)
2737 col = HTML::kWhite;
2738
2739 out << col << '\t' << Tools::Scientific(fFreeSpace) << "B\n";
2740
2741 out << HTML::kGreen << '\t' << dt.str().substr(0, dt.str().length()-7) << '\n';
2742 }
2743
2744 ofstream(fPath+"/status.data") << out.str();
2745
2746 if (now-fLastAstroCalc>boost::posix_time::seconds(15))
2747 {
2748 UpdateAstronomy();
2749 fLastAstroCalc = now;
2750 }
2751
2752 return fDimDNS.online() ? kStateRunning : kStateDimNetworkNA;
2753 }
2754
2755
2756public:
2757 StateMachineSmartFACT(ostream &out=cout) : StateMachineDim(out, fIsServer?"SMART_FACT":""),
2758 fLastAstroCalc(boost::date_time::neg_infin),
2759 fPath("www/smartfact/data"),
2760 fControlScriptDepth(0),
2761 fMcpConfigurationState(DimState::kOffline),
2762 fMcpConfigurationMaxTime(0),
2763 fMcpConfigurationMaxEvents(0),
2764 fLastRunFinishedWithZeroEvents(false),
2765 fTngWeatherDustTime(Time::none),
2766 fBiasControlVoltageMed(0),
2767 fBiasControlCurrentMed(0),
2768 fBiasControlCurrentMax(0),
2769 fFscControlHumidityAvg(0),
2770 fDriveControlMoonDist(-1),
2771 fFadControlNumEvents(0),
2772 fFadControlDrsRuns(3),
2773 fFtmControlState(FTM::kFtmLocked),
2774 fRateScanDataId(0),
2775 fRateScanBoard(0),
2776 fFreeSpace(UINT64_MAX),
2777 // ---
2778 fDimMcp ("MCP"),
2779 fDimDataLogger ("DATA_LOGGER"),
2780 fDimDriveControl ("DRIVE_CONTROL"),
2781 fDimTimeCheck ("TIME_CHECK"),
2782 fDimMagicWeather ("MAGIC_WEATHER"),
2783 fDimTngWeather ("TNG_WEATHER"),
2784 fDimFeedback ("FEEDBACK"),
2785 fDimBiasControl ("BIAS_CONTROL"),
2786 fDimFtmControl ("FTM_CONTROL"),
2787 fDimFadControl ("FAD_CONTROL"),
2788 fDimFscControl ("FSC_CONTROL"),
2789 fDimAgilentControl("AGILENT_CONTROL"),
2790 fDimPwrControl ("PWR_CONTROL"),
2791 fDimLidControl ("LID_CONTROL"),
2792 fDimRateControl ("RATE_CONTROL"),
2793 fDimRateScan ("RATE_SCAN"),
2794 fDimChat ("CHAT"),
2795 fDimSkypeClient ("SKYPE_CLIENT")
2796 {
2797 fDimDNS.Subscribe(*this);
2798 fDimControl.Subscribe(*this);
2799 fDimMcp.Subscribe(*this);
2800 fDimDataLogger.Subscribe(*this);
2801 fDimDriveControl.Subscribe(*this);
2802 fDimTimeCheck.Subscribe(*this);
2803 fDimMagicWeather.Subscribe(*this);
2804 fDimTngWeather.Subscribe(*this);
2805 fDimFeedback.Subscribe(*this);
2806 fDimBiasControl.Subscribe(*this);
2807 fDimFtmControl.Subscribe(*this);
2808 fDimFadControl.Subscribe(*this);
2809 fDimFscControl.Subscribe(*this);
2810 fDimAgilentControl.Subscribe(*this);
2811 fDimPwrControl.Subscribe(*this);
2812 fDimLidControl.Subscribe(*this);
2813 fDimRateControl.Subscribe(*this);
2814 fDimRateScan.Subscribe(*this);
2815 fDimChat.Subscribe(*this);
2816 fDimSkypeClient.Subscribe(*this);
2817
2818 fDimFscControl.SetCallback(bind(&StateMachineSmartFACT::HandleFscControlStateChange, this, placeholders::_1));
2819 fDimFtmControl.SetCallback(bind(&StateMachineSmartFACT::HandleFtmControlStateChange, this));
2820 fDimDriveControl.SetCallback(bind(&StateMachineSmartFACT::HandleDriveControlStateChange, this, placeholders::_1));
2821 fDimControl.SetCallback(bind(&StateMachineSmartFACT::HandleControlStateChange, this, placeholders::_1));
2822 fDimControl.AddCallback("dotest.dim", bind(&StateMachineSmartFACT::HandleDoTest, this, placeholders::_1));
2823
2824 Subscribe("DIM_CONTROL/MESSAGE")
2825 (bind(&StateMachineSmartFACT::HandleDimControlMessage, this, placeholders::_1));
2826
2827 Subscribe("MCP/CONFIGURATION")
2828 (bind(&StateMachineSmartFACT::HandleMcpConfiguration, this, placeholders::_1));
2829
2830 Subscribe("DRIVE_CONTROL/POINTING_POSITION")
2831 (bind(&StateMachineSmartFACT::HandleDrivePointing, this, placeholders::_1));
2832 Subscribe("DRIVE_CONTROL/TRACKING_POSITION")
2833 (bind(&StateMachineSmartFACT::HandleDriveTracking, this, placeholders::_1));
2834 Subscribe("DRIVE_CONTROL/SOURCE_POSITION")
2835 (bind(&StateMachineSmartFACT::HandleDriveSource, this, placeholders::_1));
2836
2837 Subscribe("FSC_CONTROL/TEMPERATURE")
2838 (bind(&StateMachineSmartFACT::HandleFscTemperature, this, placeholders::_1));
2839 Subscribe("FSC_CONTROL/HUMIDITY")
2840 (bind(&StateMachineSmartFACT::HandleFscHumidity, this, placeholders::_1));
2841
2842 Subscribe("MAGIC_WEATHER/DATA")
2843 (bind(&StateMachineSmartFACT::HandleMagicWeatherData, this, placeholders::_1));
2844 Subscribe("TNG_WEATHER/DUST")
2845 (bind(&StateMachineSmartFACT::HandleTngWeatherDust, this, placeholders::_1));
2846
2847 Subscribe("FEEDBACK/DEVIATION")
2848 (bind(&StateMachineSmartFACT::HandleFeedbackDeviation, this, placeholders::_1));
2849 Subscribe("FEEDBACK/CALIBRATION")
2850 (bind(&StateMachineSmartFACT::HandleFeedbackCalibration, this, placeholders::_1));
2851
2852 Subscribe("BIAS_CONTROL/VOLTAGE")
2853 (bind(&StateMachineSmartFACT::HandleBiasVoltage, this, placeholders::_1));
2854 Subscribe("BIAS_CONTROL/CURRENT")
2855 (bind(&StateMachineSmartFACT::HandleBiasCurrent, this, placeholders::_1));
2856
2857 Subscribe("FAD_CONTROL/CONNECTIONS")
2858 (bind(&StateMachineSmartFACT::HandleFadConnections, this, placeholders::_1));
2859 Subscribe("FAD_CONTROL/EVENTS")
2860 (bind(&StateMachineSmartFACT::HandleFadEvents, this, placeholders::_1));
2861 Subscribe("FAD_CONTROL/START_RUN")
2862 (bind(&StateMachineSmartFACT::HandleFadStartRun, this, placeholders::_1));
2863 Subscribe("FAD_CONTROL/DRS_RUNS")
2864 (bind(&StateMachineSmartFACT::HandleFadDrsRuns, this, placeholders::_1));
2865 Subscribe("FAD_CONTROL/EVENT_DATA")
2866 (bind(&StateMachineSmartFACT::HandleFadEventData, this, placeholders::_1));
2867 Subscribe("FAD_CONTROL/STATS")
2868 (bind(&StateMachineSmartFACT::HandleStats, this, placeholders::_1));
2869
2870 Subscribe("DATA_LOGGER/STATS")
2871 (bind(&StateMachineSmartFACT::HandleStats, this, placeholders::_1));
2872
2873 Subscribe("FTM_CONTROL/TRIGGER_RATES")
2874 (bind(&StateMachineSmartFACT::HandleFtmTriggerRates, this, placeholders::_1));
2875 Subscribe("FTM_CONTROL/STATIC_DATA")
2876 (bind(&StateMachineSmartFACT::HandleFtmStaticData, this, placeholders::_1));
2877 Subscribe("FTM_CONTROL/FTU_LIST")
2878 (bind(&StateMachineSmartFACT::HandleFtmFtuList, this, placeholders::_1));
2879
2880 Subscribe("RATE_CONTROL/THRESHOLD")
2881 (bind(&StateMachineSmartFACT::HandleRateControlThreshold,this, placeholders::_1));
2882
2883 Subscribe("RATE_SCAN/DATA")
2884 (bind(&StateMachineSmartFACT::HandleRateScanData, this, placeholders::_1));
2885
2886 Subscribe("CHAT/MESSAGE")
2887 (bind(&StateMachineSmartFACT::HandleChatMsg, this, placeholders::_1));
2888
2889
2890 // =================================================================
2891
2892 // State names
2893 AddStateName(kStateDimNetworkNA, "DimNetworkNotAvailable",
2894 "The Dim DNS is not reachable.");
2895
2896 AddStateName(kStateRunning, "Running", "");
2897
2898 // =================================================================
2899
2900 AddEvent("PRINT")
2901 (bind(&StateMachineSmartFACT::Print, this))
2902 ("Print a list of the states of all connected servers.");
2903
2904 }
2905 int EvalOptions(Configuration &conf)
2906 {
2907 if (!fPixelMap.Read(conf.Get<string>("pixel-map-file")))
2908 {
2909 Error("Reading mapping table from "+conf.Get<string>("pixel-map-file")+" failed.");
2910 return 1;
2911 }
2912
2913 fPath = conf.Get<string>("path");
2914 fDatabase = conf.Get<string>("source-database");
2915
2916 struct stat st;
2917 if (stat(fPath.c_str(), &st))
2918 {
2919 Error(fPath+" does not exist!");
2920 return 2;
2921 }
2922
2923 if ((st.st_mode&S_IFDIR)==0)
2924 {
2925 Error(fPath+" not a directory!");
2926 return 3;
2927 }
2928
2929 if ((st.st_mode&S_IWUSR)==0)
2930 {
2931 Error(fPath+" has no write permission!");
2932 return 4;
2933 }
2934
2935 if ((st.st_mode&S_IXUSR)==0)
2936 {
2937 Error(fPath+" has no execute permission!");
2938 return 5;
2939 }
2940
2941 ostringstream out;
2942 out << Time().JavaDate() << '\n';
2943
2944 ofstream(fPath+"/error.data") << out.str();
2945
2946 return -1;
2947 }
2948};
2949
2950bool StateMachineSmartFACT::fIsServer = false;
2951
2952// ------------------------------------------------------------------------
2953
2954#include "Main.h"
2955
2956template<class T>
2957int RunShell(Configuration &conf)
2958{
2959 StateMachineSmartFACT::fIsServer = !conf.Get<bool>("client");
2960 return Main::execute<T, StateMachineSmartFACT>(conf);
2961}
2962
2963void SetupConfiguration(Configuration &conf)
2964{
2965 po::options_description control("Smart FACT");
2966 control.add_options()
2967 ("pixel-map-file", var<string>("FACTmapV5a.txt"), "Pixel mapping file. Used here to get the default reference voltage")
2968 ("path", var<string>("www/smartfact/data"), "Output path for the data-files")
2969 ("source-database", var<string>(""), "Database link as in\n\tuser:password@server[:port]/database.")
2970 ("client", po_bool(false), "For a standalone client choose this option.")
2971 ;
2972
2973 conf.AddOptions(control);
2974}
2975
2976/*
2977 Extract usage clause(s) [if any] for SYNOPSIS.
2978 Translators: "Usage" and "or" here are patterns (regular expressions) which
2979 are used to match the usage synopsis in program output. An example from cp
2980 (GNU coreutils) which contains both strings:
2981 Usage: cp [OPTION]... [-T] SOURCE DEST
2982 or: cp [OPTION]... SOURCE... DIRECTORY
2983 or: cp [OPTION]... -t DIRECTORY SOURCE...
2984 */
2985void PrintUsage()
2986{
2987 cout <<
2988 "SmartFACT is a tool writing the files needed for the SmartFACT web interface.\n"
2989 "\n"
2990 "The default is that the program is started without user intercation. "
2991 "All actions are supposed to arrive as DimCommands. Using the -c "
2992 "option, a local shell can be initialized. With h or help a short "
2993 "help message about the usuage can be brought to the screen.\n"
2994 "\n"
2995 "Usage: smartfact [-c type] [OPTIONS]\n"
2996 " or: smartfact [OPTIONS]\n";
2997 cout << endl;
2998}
2999
3000void PrintHelp()
3001{
3002 Main::PrintHelp<StateMachineSmartFACT>();
3003
3004 /* Additional help text which is printed after the configuration
3005 options goes here */
3006
3007 /*
3008 cout << "bla bla bla" << endl << endl;
3009 cout << endl;
3010 cout << "Environment:" << endl;
3011 cout << "environment" << endl;
3012 cout << endl;
3013 cout << "Examples:" << endl;
3014 cout << "test exam" << endl;
3015 cout << endl;
3016 cout << "Files:" << endl;
3017 cout << "files" << endl;
3018 cout << endl;
3019 */
3020}
3021
3022int main(int argc, const char* argv[])
3023{
3024 Configuration conf(argv[0]);
3025 conf.SetPrintUsage(PrintUsage);
3026 Main::SetupConfiguration(conf);
3027 SetupConfiguration(conf);
3028
3029 if (!conf.DoParse(argc, argv, PrintHelp))
3030 return 127;
3031
3032 if (!conf.Has("console"))
3033 return RunShell<LocalStream>(conf);
3034
3035 if (conf.Get<int>("console")==0)
3036 return RunShell<LocalShell>(conf);
3037 else
3038 return RunShell<LocalConsole>(conf);
3039
3040 return 0;
3041}
Note: See TracBrowser for help on using the repository browser.