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

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