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

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