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

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