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

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