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

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