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

Last change on this file since 14310 was 14310, checked in by tbretz, 12 years ago
Fixed a problem with the visibility and current-predition if sources have their maximum at the same time.
File size: 96.0 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
1858 vector<pair<ln_equ_posn, double>> fMoonCoords;
1859
1860 void CalcMoonCoords(double jd)
1861 {
1862 jd = floor(jd);
1863
1864 fMoonCoords.clear();
1865 for (double h=0; h<1; h+=1./(24*12))
1866 {
1867 ln_equ_posn moon;
1868 ln_get_lunar_equ_coords_prec(jd+h, &moon, 0.01);
1869
1870 const double disk = ln_get_lunar_disk(jd+h);
1871
1872 fMoonCoords.push_back(make_pair(moon, disk));
1873 }
1874 }
1875
1876 pair<vector<float>, pair<Time, float>> GetVisibility(ln_equ_posn *src, ln_lnlat_posn *observer, double jd)
1877 {
1878 jd = floor(jd);
1879
1880 const double jd0 = fmod(fSun.fSetAstronomical.JD(), 1);
1881 const double jd1 = fmod(fSun.fRiseAstronomical.JD(), 1);
1882
1883 ln_equ_posn moon;
1884 ln_equ_posn *pos = src ? src : &moon;
1885
1886 double max = 0;
1887 double maxjd = 0;
1888
1889 int cnt = 0;
1890
1891 int i=0;
1892
1893 vector<float> alt;
1894 for (double h=0; h<1; h+=1./(24*12), i++)
1895 {
1896 if (src==0)
1897 moon = fMoonCoords[i].first; //ln_get_lunar_equ_coords_prec(jd+h, &moon, 0.01);
1898
1899 ln_hrz_posn hrz;
1900 ln_get_hrz_from_equ(pos, observer, jd+h, &hrz);
1901
1902 if (h>jd0 && h<jd1)
1903 alt.push_back(hrz.alt);
1904
1905 if (hrz.alt>max)
1906 {
1907 max = hrz.alt;
1908 maxjd = jd+h;
1909 }
1910
1911 if (h>jd0 && h<jd1 && hrz.alt>15)
1912 cnt++;
1913 }
1914
1915 if (max<=15 || cnt==0)
1916 return make_pair(vector<float>(), make_pair(Time(), 0));
1917
1918 return make_pair(alt, make_pair(maxjd, maxjd>jd+jd0&&maxjd<jd+jd1?max:0));
1919 }
1920
1921 pair<vector<float>, pair<Time, float>> GetLightCondition(ln_equ_posn *src, ln_lnlat_posn *observer, double jd)
1922 {
1923 jd = floor(jd);
1924
1925 const double jd0 = fmod(fSun.fSetAstronomical.JD(), 1);
1926 const double jd1 = fmod(fSun.fRiseAstronomical.JD(), 1);
1927
1928 double max = -1;
1929 double maxjd = 0;
1930
1931 int cnt = 0;
1932 int i = 0;
1933
1934 vector<float> vec;
1935 for (double h=0; h<1; h+=1./(24*12), i++)
1936 {
1937 double cur = -1;
1938
1939 if (h>jd0 && h<jd1)
1940 {
1941 ln_equ_posn moon = fMoonCoords[i].first;//ln_get_lunar_equ_coords_prec(jd+h, &moon, 0.01);
1942 const double disk = fMoonCoords[i].second;//ln_get_lunar_disk(jd+h);
1943
1944 ln_hrz_posn hrz;
1945 ln_get_hrz_from_equ(&moon, observer, jd+h, &hrz);
1946
1947 Moon m;
1948 m.ra = moon.ra;
1949 m.dec = moon.dec;
1950
1951 const double angle = m.Angle(src->ra, src->dec);
1952
1953 const double lc = angle*hrz.alt*pow(disk, 6)/360/360;
1954
1955 cur = 7.7+4942*lc;
1956
1957 vec.push_back(cur); // Covert LC to pixel current in uA
1958 }
1959
1960 if (cur>max)
1961 {
1962 max = cur;
1963 maxjd = jd+h;
1964 }
1965
1966 if (h>jd0 && h<jd1 && cur>0)
1967 cnt++;
1968 }
1969
1970 if (max<=0 || cnt==0)
1971 return make_pair(vector<float>(), make_pair(Time(), 0));
1972
1973 return make_pair(vec, make_pair(maxjd, maxjd>jd+jd0&&maxjd<jd+jd1?max:-1));
1974 }
1975#endif
1976
1977 void UpdateAstronomy()
1978 {
1979 const double lon = -(17.+53./60+26.525/3600);
1980 const double lat = 28.+45./60+42.462/3600;
1981
1982 Time now;
1983
1984 CalcMoonCoords(now.JD());
1985
1986 fSun = Sun (lon, lat, now);
1987 fMoon = Moon(lon, lat, now);
1988
1989 vector<string> color(8, HTML::kWhite);
1990 color[fSun.state%8] = HTML::kBlue;
1991
1992 ostringstream out;
1993 out << setprecision(3);
1994 out << now.JavaDate() << '\n';
1995 out << color[0] << '\t' << fSun.fRiseDarkTime.GetAsStr("%H:%M") << '\n';
1996 out << color[1] << '\t' << fSun.fRiseAstronomical.GetAsStr("%H:%M") << '\n';
1997 out << color[2] << '\t' << fSun.fRiseCivil.GetAsStr("%H:%M") << '\n';
1998 out << color[3] << '\t' << fSun.fRiseDayTime.GetAsStr("%H:%M") << '\n';
1999
2000 out << color[4] << '\t' << fSun.fSetDayTime.GetAsStr("%H:%M") << '\n';
2001 out << color[5] << '\t' << fSun.fSetCivil.GetAsStr("%H:%M") << '\n';
2002 out << color[6] << '\t' << fSun.fSetAstronomical.GetAsStr("%H:%M") << '\n';
2003 out << color[7] << '\t' << fSun.fSetDarkTime.GetAsStr("%H:%M") << '\n';
2004
2005 ofstream(fPath+"/sun.data") << out.str();
2006
2007 color.assign(3, HTML::kWhite);
2008 color[fMoon.state%3] = HTML::kBlue;
2009
2010 out.str("");
2011 out << now.JavaDate() << '\n';
2012
2013 out << color[0] << '\t' << fMoon.fRise.GetAsStr("%H:%M") << '\n';
2014 out << color[1] << '\t' << fMoon.fTransit.GetAsStr("%H:%M") << '\n';
2015 out << color[2] << '\t' << fMoon.fSet.GetAsStr("%H:%M") << '\n';
2016
2017 out << (fSun.isday?HTML::kWhite:fMoon.color) << '\t' << fMoon.description << '\n';
2018
2019 if (!fMoon.visible)
2020 out << HTML::kWhite << "\t&mdash;\t\n";
2021 else
2022 {
2023 string col = HTML::kWhite;
2024 if (!fSun.isday)
2025 {
2026 col = HTML::kGreen;
2027 if (fMoon.zd>25)
2028 col = HTML::kYellow;
2029 if (fMoon.zd>45 && fMoon.zd<80)
2030 col = HTML::kRed;
2031 if (fMoon.zd>=80)
2032 col = HTML::kRed;
2033 }
2034 out << col << '\t' << fMoon.zd << '\t' << GetDir(fMoon.az) << '\n';
2035 }
2036
2037 ostringstream out2, out3, out4;
2038 out2 << setprecision(3);
2039 out2 << now.JavaDate() << '\n';
2040 out3 << now.JavaDate() << '\n';
2041 out4 << now.JavaDate() << '\n';
2042
2043 multimap<Time, pair<string, float>> culmination;
2044 multimap<Time, pair<string, float>> lightcond;
2045 vector<vector<float>> alt;
2046 vector<vector<float>> cur;
2047
2048#ifdef HAVE_NOVA
2049 ln_lnlat_posn observer;
2050 observer.lng = lon;
2051 observer.lat = lat;
2052
2053 const pair<vector<float>, pair<Time, float>> vism = GetVisibility(0, &observer, now.JD());
2054 if (vism.first.size()>0)
2055 {
2056 alt.push_back(vism.first);
2057 culmination.insert(make_pair(vism.second.first, make_pair("Moon", vism.second.second)));
2058 }
2059#endif
2060
2061#ifdef HAVE_SQL
2062 try
2063 {
2064 const mysqlpp::StoreQueryResult res =
2065 Database(fDatabase).query("SELECT fSourceName, fRightAscension, fDeclination FROM source").store();
2066
2067 out << HTML::kWhite << '\t';
2068 out2 << HTML::kWhite << '\t';
2069 out3 << HTML::kWhite << '\t';
2070 out4 << HTML::kWhite << '\t';
2071
2072 for (vector<mysqlpp::Row>::const_iterator v=res.begin(); v<res.end(); v++)
2073 {
2074 const string name = (*v)[0].c_str();
2075 const double ra = (*v)[1];
2076 const double dec = (*v)[2];
2077#ifdef HAVE_NOVA
2078 ln_equ_posn pos;
2079 pos.ra = ra*15;
2080 pos.dec = dec;
2081
2082 ln_hrz_posn hrz;
2083 ln_get_hrz_from_equ(&pos, &observer, now.JD(), &hrz);
2084
2085 const pair<vector<float>, pair<Time, float>> vis = GetVisibility(&pos, &observer, now.JD());
2086 if (vis.first.size()>0)
2087 {
2088 alt.push_back(vis.first);
2089 culmination.insert(make_pair(vis.second.first, make_pair(name, vis.second.second)));
2090
2091 const pair<vector<float>, pair<Time, float>> lc = GetLightCondition(&pos, &observer, now.JD());
2092 if (lc.first.size()>0)
2093 {
2094 cur.push_back(lc.first);
2095 lightcond.insert(make_pair(lc.second.first, make_pair(name, lc.second.second)));
2096 }
2097 }
2098
2099 string col = HTML::kWhite;
2100 if (hrz.alt>5)
2101 col = HTML::kRed;
2102 if (hrz.alt>25)
2103 col = HTML::kYellow;
2104 if (hrz.alt>60)
2105 col = HTML::kGreen;
2106
2107 out2 << "<tr bgcolor='" << col << "'>";
2108 out2 << "<td>" << name << "</td>";
2109 if (hrz.alt>5)
2110 {
2111 out2 << "<td>" << 90-hrz.alt << "&deg;</td>";
2112 out2 << "<td>" << GetDir(hrz.az) << "</td>";
2113 }
2114 else
2115 out2 << "<td/><td/>";
2116 out2 << "</tr>";
2117#endif
2118 const int32_t angle = fMoon.Angle(ra, dec);
2119
2120 out << "<tr bgcolor='" << Moon::Color(angle) << "'>";
2121 out << "<td>" << name << "</td>";
2122 out << "<td>" << round(angle) << "&deg;</td>";
2123 out << "</tr>";
2124 }
2125
2126 for (auto it=culmination.begin(); it!=culmination.end(); it++)
2127 {
2128 if (it!=culmination.begin())
2129 out3 << ", ";
2130 out3 << "<B>" << it->second.first << "</B>";
2131 if (it->second.second>0)
2132 out3 << " [" << nearbyint(90-it->second.second) << "&deg;]";
2133 }
2134
2135 out4 << setprecision(3);
2136 for (auto it=lightcond.begin(); it!=lightcond.end(); it++)
2137 {
2138 if (it!=lightcond.begin())
2139 out4 << ", ";
2140 out4 << "<B>" << it->second.first << "</B>";
2141 if (it->second.second>0)
2142 out4 << " [" << nearbyint(it->second.second) << "]";
2143 }
2144
2145 ostringstream title;
2146 title << fSun.fSetAstronomical.GetAsStr("%H:%M");
2147 title << " / ";
2148 title << ((fSun.fRiseAstronomical-fSun.fSetAstronomical)/20).minutes();
2149 title << "' / ";
2150 title << fSun.fRiseAstronomical.GetAsStr("%H:%M");
2151
2152 out << '\n';
2153 out2 << '\n';
2154 out3 << '\n';
2155 out4 << '\n';
2156 out << HTML::kWhite << '\t' << Time()-now << '\n';
2157 out2 << HTML::kWhite << '\t' << Time()-now << '\n';
2158
2159 WriteBinaryVec(now, "hist-visibility", alt, 75, 15, "Alt "+title.str());
2160 WriteBinaryVec(now, "hist-current-prediction", cur, 100, 0, "I " +title.str());
2161 }
2162 catch (const exception &e)
2163 {
2164 out << '\n';
2165 out2 << '\n';
2166 out << HTML::kWhite << '\t' << "ERROR - "+string(e.what()) << '\n';
2167 out2 << HTML::kWhite << '\t' << "ERROR - "+string(e.what()) << '\n';
2168 out3 << HTML::kWhite << '\t' << "ERROR - "+string(e.what()) << '\n';
2169 out4 << HTML::kWhite << '\t' << "ERROR - "+string(e.what()) << '\n';
2170 }
2171#endif
2172
2173 ofstream(fPath+"/moon.data") << out.str();
2174 ofstream(fPath+"/source-list.data") << out2.str();
2175 ofstream(fPath+"/visibility.data") << out3.str();
2176 ofstream(fPath+"/current-prediction.data") << out4.str();
2177 }
2178
2179 int Execute()
2180 {
2181 // Dispatch (execute) at most one handler from the queue. In contrary
2182 // to run_one(), it doesn't wait until a handler is available
2183 // which can be dispatched, so poll_one() might return with 0
2184 // handlers dispatched. The handlers are always dispatched/executed
2185 // synchronously, i.e. within the call to poll_one()
2186 //poll_one();
2187
2188 Time now;
2189 if (now-fLastUpdate<boost::posix_time::seconds(1))
2190 return fDimDNS.online() ? kStateRunning : kStateDimNetworkNA;
2191 fLastUpdate=now;
2192
2193 // ==============================================================
2194
2195 const bool data_taking =
2196 fDimMcp.state()==MCP::State::kTriggerOn ||
2197 fDimMcp.state()==MCP::State::kTakingData;
2198
2199 const bool data_run =
2200 fMcpConfigurationName=="data" ||
2201 fMcpConfigurationName=="data-rt";
2202
2203 const bool bias_on =
2204 fDimBiasControl.state()==BIAS::State::kRamping ||
2205 fDimBiasControl.state()==BIAS::State::kOverCurrent ||
2206 fDimBiasControl.state()==BIAS::State::kVoltageOn;
2207
2208 const bool haderr = fErrorList.size()>0;
2209
2210 bool newerr = false;
2211
2212 newerr |= SetError(!fDimDNS.online(),
2213 "<b><#darkred>DIM network not available</#></b>");
2214 newerr |= SetError(!fDimControl.online(),
2215 "<b>dimctrl offline</b>");
2216 newerr |= SetError(fDimDataLogger.state()<20 || fDimDataLogger.state()>40,
2217 "<b>datalogger not ready</b>");
2218
2219 //newerr |= SetError(fDimDriveControl.state()==Drive::State::kLocked,
2220 // "<b><#darkred>Drive in LOCKED state, drive was automatically parked</#></b>");
2221
2222 newerr |= SetError(fDimDriveControl.state()>0xff && data_taking && data_run,
2223 "Drive in ERROR state during data-taking");
2224 newerr |= SetError(fDriveControlMoonDist>155,
2225 "Moon within the field-of-view of the cones");
2226 newerr |= SetError(fDriveControlMoonDist>=0 && fDriveControlMoonDist<3,
2227 "Moon within the field-of-view of the camera");
2228
2229 newerr |= SetError(fDimBiasControl.state()<BIAS::State::kRamping && data_taking,
2230 "BIAS not operating during data-taking");
2231 newerr |= SetError(fDimBiasControl.state()==BIAS::State::kOverCurrent,
2232 "BIAS channels in OverCurrent");
2233 newerr |= SetError(fDimBiasControl.state()==BIAS::State::kNotReferenced,
2234 "BIAS voltage not at reference");
2235
2236
2237 newerr |= SetError(bias_on && fFeedbackCalibration.size()>0 && fBiasControlCurrentMed>80,
2238 "Median current exceeds 80&micro;A/pix exceeds 80&micro;A/pix");
2239 newerr |= SetError(bias_on && fFeedbackCalibration.size()>0 && fBiasControlCurrentMax>100,
2240 "Maximum current exceeds 100&micro;A/pix");
2241
2242 newerr |= SetError(fFscControlHumidityAvg>60,
2243 "Average camera humidity exceed 60%");
2244
2245 newerr |= SetError(fMagicWeatherHist[kHum].size()>0 && fMagicWeatherHist[kHum].back()>98 && data_taking,
2246 "Outside humidity exceeds 98% during data-taking");
2247 newerr |= SetError(fMagicWeatherHist[kGusts].size()>0 && fMagicWeatherHist[kGusts].back()>98 && fDimDriveControl.state()==Drive::State::kTracking,
2248 "Wind gusts exceed 50km/h during tracking");
2249
2250 newerr |= SetError(fFscControlTemperatureHist.size()>0 && fFscControlTemperatureHist.back()>8,
2251 "Sensor temperature exceeds outside temperature by more than 8&deg;C");
2252
2253 newerr |= SetError(fFtmControlTriggerRateTooLow>2 && fDimMcp.state()==MCP::State::kTakingData,
2254 "Trigger rate below 1Hz during data taking");
2255
2256 newerr |= SetError(fDimTimeCheck.state()==1,
2257 "Warning NTP time difference of drive PC exceeds 1s");
2258 newerr |= SetError(fDimTimeCheck.state()<1,
2259 "Warning timecheck not running");
2260
2261 newerr |= SetError(fDimFeedback.state()!=Feedback::State::kCalibrating &&
2262 fDimBiasControl.state()==BIAS::State::kVoltageOn &&
2263 fBiasControlVoltageMed>3 &&
2264 fFeedbackCalibration.size()==0,
2265 "Bias voltage switched on, but bias crate not calibrated");
2266
2267 newerr |= SetError(fLastRunFinishedWithZeroEvents,
2268 "Last run finshed, but contained zero events.");
2269
2270 newerr |= SetError(fFreeSpace<50000000000,
2271 "Less than 50GB disk space left.");
2272
2273 fLastRunFinishedWithZeroEvents = false;
2274
2275 // FTM in Connected instead of Idle --> power cyclen
2276
2277 /* // Check offline and disconnected status?
2278 Out() << fDimMcp << endl;
2279 Out() << fDimControl << endl;
2280 Out() << fDimDataLogger << endl;
2281 Out() << fDimDriveControl << endl;
2282 Out() << fDimFadControl << endl;
2283 Out() << fDimFtmControl << endl;
2284 Out() << fDimBiasControl << endl;
2285 Out() << fDimFeedback << endl;
2286 Out() << fDimRateControl << endl;
2287 Out() << fDimFscControl << endl;
2288 Out() << fDimMagicWeather << endl;
2289 Out() << fDimRateScan << endl;
2290 Out() << fDimChat << endl;
2291 */
2292
2293 // FTU in error
2294 // FAD lost
2295
2296 // --------------------------------------------------------------
2297 ostringstream out;
2298
2299 if (newerr)
2300 {
2301 SetAudio("error");
2302
2303 out << now.JavaDate() << '\n';
2304 out << HTML::kWhite << '\t';
2305 out << "<->" << fErrorHist.rget() << "<->";
2306 out << '\n';
2307
2308 ofstream(fPath+"/errorhist.data") << out.str();
2309 }
2310
2311 out.str("");
2312 out << Header(now) << '\t' << (fErrorList.size()>0) << '\t' << (fDimControl.state()>-3) << '\n';
2313 out << setprecision(3);
2314 out << HTML::kWhite << '\t';
2315 for (auto it=fErrorList.begin(); it!=fErrorList.end(); it++)
2316 out << *it << "<br/>";
2317 out << '\n';
2318
2319 if (haderr || fErrorList.size()>0)
2320 ofstream(fPath+"/error.data") << out.str();
2321
2322 // ==============================================================
2323
2324 out.str("");
2325 out << Header(now) << '\t' << (fErrorList.size()>0) << '\t' << (fDimControl.state()>-3) << '\n';
2326 out << setprecision(3);
2327
2328 // -------------- System status --------------
2329 if (fDimDNS.online() && fDimMcp.state()>=MCP::State::kIdle) // Idle
2330 {
2331 string col = HTML::kBlue;
2332 switch (fMcpConfigurationState)
2333 {
2334 case MCP::State::kIdle:
2335 col = HTML::kWhite;
2336 break;
2337 case MCP::State::kConfiguring1:
2338 case MCP::State::kConfiguring2:
2339 case MCP::State::kConfiguring3:
2340 case MCP::State::kConfigured:
2341 case MCP::State::kTriggerOn:
2342 col = HTML::kBlue;
2343 break;
2344 case MCP::State::kTakingData:
2345 col = HTML::kBlue;
2346 if (fDimFadControl.state()==FAD::State::kWritingData)
2347 col = HTML::kGreen;
2348 break;
2349 }
2350
2351 const bool other =
2352 fDimRateControl.state()==RateControl::State::kSettingGlobalThreshold ||
2353 fDimRateScan.state()==RateScan::State::kInProgress;
2354
2355 if (other)
2356 col = HTML::kBlue;
2357
2358 out << col << '\t';
2359
2360 if (!other)
2361 {
2362 switch (fMcpConfigurationState)
2363 {
2364 case MCP::State::kIdle:
2365 out << "Idle [" << fMcpConfigurationName << "]";
2366 break;
2367 case MCP::State::kConfiguring1:
2368 case MCP::State::kConfiguring2:
2369 case MCP::State::kConfiguring3:
2370 out << "Configuring [" << fMcpConfigurationName << "]";
2371 break;
2372 case MCP::State::kConfigured:
2373 out << "Configured [" << fMcpConfigurationName << "]";
2374 break;
2375 case MCP::State::kTriggerOn:
2376 case MCP::State::kTakingData:
2377 out << fMcpConfigurationName;
2378 if (fFadControlDrsRuns[2]>0)
2379 out << "(" << fFadControlDrsRuns[2] << ")";
2380 break;
2381 }
2382 }
2383 else
2384 if (fDimRateControl.state()==RateControl::State::kSettingGlobalThreshold)
2385 out << "Calibrating threshold";
2386 else
2387 if (fDimRateScan.state()==RateScan::State::kInProgress)
2388 out << "Rate scan in progress";
2389
2390 if (fMcpConfigurationState>MCP::State::kConfigured &&
2391 fDimRateControl.state()!=RateControl::State::kSettingGlobalThreshold)
2392 {
2393 ostringstream evt;
2394 if (fMcpConfigurationMaxEvents>0)
2395 {
2396 const int64_t de = int64_t(fMcpConfigurationMaxEvents) - int64_t(fFadControlNumEvents);
2397 if (de>=0 && fMcpConfigurationState==MCP::State::kTakingData)
2398 evt << de;
2399 else
2400 evt << fMcpConfigurationMaxEvents;
2401 }
2402 else
2403 {
2404 if (fMcpConfigurationState==MCP::State::kTakingData)
2405 {
2406 if (fFadControlNumEvents>2999)
2407 evt << floor(fFadControlNumEvents/1000) << 'k';
2408 else
2409 evt << fFadControlNumEvents;
2410 }
2411 }
2412
2413 ostringstream tim;
2414 if (fMcpConfigurationMaxTime>0)
2415 {
2416 const uint32_t dt = (Time()-fMcpConfigurationRunStart).total_seconds();
2417 if (dt<=fMcpConfigurationMaxTime && fMcpConfigurationState==MCP::State::kTakingData)
2418 tim << fMcpConfigurationMaxTime-dt << 's';
2419 else
2420 tim << fMcpConfigurationMaxTime << 's';
2421 }
2422 else
2423 {
2424 if (fMcpConfigurationState==MCP::State::kTakingData)
2425 tim << fMcpConfigurationRunStart.SecondsTo();
2426 }
2427
2428 const bool has_evt = !evt.str().empty();
2429 const bool has_tim = !tim.str().empty();
2430
2431 if (has_evt || has_tim)
2432 out << " [";
2433 out << evt.str();
2434 if (has_evt && has_tim)
2435 out << '/';
2436 out << tim.str();
2437 if (has_evt || has_tim)
2438 out << ']';
2439 }
2440 }
2441 else
2442 out << HTML::kWhite;
2443 out << '\n';
2444
2445 // ------------------ Drive -----------------
2446 if (fDimDNS.online() && fDimDriveControl.state()>=Drive::State::kArmed) // Armed, Moving, Tracking
2447 {
2448 const uint32_t dev = fDriveControlTrackingDevHist.size()>0 ? round(fDriveControlTrackingDevHist.back()) : 0;
2449 const State rc = fDimDriveControl.description();
2450 string col = HTML::kGreen;
2451 if (fDimDriveControl.state()==Drive::State::kMoving) // Moving
2452 col = HTML::kBlue;
2453 if (fDimDriveControl.state()==Drive::State::kArmed) // Armed
2454 col = HTML::kWhite;
2455 if (fDimDriveControl.state()==Drive::State::kTracking) // Tracking
2456 {
2457 if (dev>60) // ~1.5mm
2458 col = HTML::kYellow;
2459 if (dev>120) // ~1/4 of a pixel ~ 2.5mm
2460 col = HTML::kRed;
2461 }
2462 if (fDimDriveControl.state()==0x100)
2463 col = HTML::kRed;
2464 out << col << '\t';
2465
2466 //out << rc.name << '\t';
2467 out << fDriveControlPointingAz << ' ';
2468 out << fDriveControlPointingZd << "&deg;";
2469 out << setprecision(2);
2470 if (fDimDriveControl.state()==Drive::State::kTracking)
2471 {
2472 out << " &plusmn; " << dev << '"';
2473 if (!fDriveControlSourceName.empty())
2474 out << " [" << fDriveControlSourceName << ']';
2475 }
2476 if (fDimDriveControl.state()==Drive::State::kMoving)
2477 out << " &#10227;";
2478 out << setprecision(3);
2479 }
2480 else
2481 out << HTML::kWhite << '\t';
2482
2483 if (fSun.time.IsValid() && fMoon.time.IsValid())
2484 {
2485 if (fSun.visible)
2486 {
2487 out << " &#9788;";
2488 if (fDimDriveControl.state()<Drive::State::kArmed)
2489 out << " [" << fSun.fSetCivil.MinutesTo() << "&darr;]";
2490 }
2491 else
2492 if (!fSun.visible && fMoon.visible)
2493 {
2494 out << " &#9790;";
2495 if (fDimDriveControl.state()<Drive::State::kArmed)
2496 out << " [" << fMoon.disk << "%]";
2497 }
2498 }
2499 if (fDimDNS.online() && fDimDriveControl.state()==0x100) // Armed, Moving, Tracking
2500 out << " [ERR]";
2501 out << '\n';
2502
2503 // ------------------- FSC ------------------
2504 if (fDimDNS.online() && fDimFscControl.state()>FSC::State::kDisconnected && fFscControlTemperatureHist.size()>0)
2505 {
2506 string col = HTML::kGreen;
2507 if (fFscControlTemperatureHist.back()>5)
2508 col = HTML::kYellow;
2509 if (fFscControlTemperatureHist.back()>8)
2510 col = HTML::kRed;
2511
2512 out << col << '\t' << fFscControlTemperatureHist.back() << '\n';
2513 }
2514 else
2515 out << HTML::kWhite << '\n';
2516
2517 // --------------- MagicWeather -------------
2518 if (fDimDNS.online() && fDimMagicWeather.state()==MagicWeather::State::kReceiving && fMagicWeatherHist[kWeatherBegin].size()>0)
2519 {
2520 /*
2521 const float diff = fMagicWeatherHist[kTemp].back()-fMagicWeatherHist[kDew].back();
2522 string col1 = HTML::kRed;
2523 if (diff>0.3)
2524 col1 = HTML::kYellow;
2525 if (diff>0.7)
2526 col1 = HTML::kGreen;
2527 */
2528
2529 const float wind = fMagicWeatherHist[kGusts].back();
2530 const float hum = fMagicWeatherHist[kHum].back();
2531 string col = HTML::kGreen;
2532 if (wind>35 || hum>95)
2533 col = HTML::kYellow;
2534 if (wind>45 || hum>98)
2535 col = HTML::kRed;
2536
2537 out << col << '\t';
2538 out << fMagicWeatherHist[kHum].back() << '\t';
2539 out << setprecision(2);
2540 out << fMagicWeatherHist[kGusts].back() << '\n';
2541 out << setprecision(3);
2542 }
2543 else
2544 out << HTML::kWhite << "\n";
2545
2546 // --------------- FtmControl -------------
2547 if (fDimDNS.online() && fDimFtmControl.state()==FTM::State::kTriggerOn)
2548 {
2549 string col = HTML::kGreen;
2550 if (fFtmControlTriggerRateHist.size()>0)
2551 {
2552 if (fFtmControlTriggerRateHist.back()<15)
2553 col = HTML::kYellow;
2554 if (fFtmControlTriggerRateHist.back()>100)
2555 col = HTML::kRed;
2556
2557 out << col << '\t' << fFtmControlTriggerRateHist.back() << " Hz";
2558 }
2559
2560 if (fDimBiasControl.state()==BIAS::State::kVoltageOn)
2561 out << " (" << fFtmPatchThresholdMed << ')';
2562 out << '\n';
2563 }
2564 else
2565 out << HTML::kWhite << '\n';
2566
2567 // --------------- BiasControl -------------
2568 if (fDimDNS.online() &&
2569 (fDimBiasControl.state()==BIAS::State::kRamping ||
2570 fDimBiasControl.state()==BIAS::State::kOverCurrent ||
2571 fDimBiasControl.state()==BIAS::State::kVoltageOn ||
2572 fDimBiasControl.state()==BIAS::State::kVoltageOff))
2573 {
2574 const bool off = fDimBiasControl.state()==BIAS::State::kVoltageOff;
2575 const bool oc = fDimBiasControl.state()==BIAS::State::kOverCurrent;
2576
2577 string col = fBiasControlVoltageMed>3?HTML::kGreen:HTML::kWhite;
2578 if (fDimBiasControl.state()!=BIAS::State::kVoltageOff)
2579 {
2580 if (fBiasControlCurrentMed>60 || fBiasControlCurrentMax>80)
2581 col = HTML::kYellow;
2582 if (fBiasControlCurrentMed>70 || fBiasControlCurrentMax>90)
2583 col = HTML::kRed;
2584 }
2585
2586 // Bias in overcurrent => Red
2587 if (fDimBiasControl.state()==BIAS::State::kOverCurrent)
2588 col = HTML::kRed;
2589
2590 // MCP in ReadyForDatataking/Configuring/Configured/TriggerOn/TakingData
2591 // and Bias not in "data-taking state' => Red
2592 if (fMcpConfigurationState>MCP::State::kIdle &&
2593 fDimBiasControl.state()!=BIAS::State::kVoltageOn &&
2594 fDimBiasControl.state()!=BIAS::State::kVoltageOff)
2595 col = HTML::kRed;
2596
2597 const bool cal = fFeedbackCalibration.size();
2598
2599 // Feedback is currently calibrating => Blue
2600 if (fDimFeedback.state()==Feedback::State::kCalibrating)
2601 {
2602 out << HTML::kBlue << '\t';
2603 out << "***\t";
2604 out << "***\t";
2605 }
2606 else
2607 {
2608 out << setprecision(2);
2609 out << col << '\t';
2610 out << (off ? 0 : fBiasControlCurrentMed) << '\t';
2611 if (oc)
2612 out << "(OC) ";
2613 else
2614 {
2615 if (cal)
2616 out << (off ? 0 : fBiasControlCurrentMax);
2617 else
2618 out << "&mdash; ";
2619 }
2620 out << '\t';
2621 out << setprecision(3);
2622 }
2623 if (cal && fDimFeedback.state()!=Feedback::State::kCalibrating)
2624 out << setprecision(2) << fBiasControlPowerTot << " W" << setprecision(3);
2625 else
2626 out << (off ? 0 : fBiasControlVoltageMed) << " V";
2627 out << '\n';
2628 }
2629 else
2630 out << HTML::kWhite << '\n';
2631
2632 ofstream(fPath+"/fact.data") << out.str();
2633
2634 // ==============================================================
2635
2636 out.str("");
2637 out << Header(now) << '\t' << (fErrorList.size()>0) << '\t' << (fDimControl.state()>-3) << '\n';
2638
2639 if (!fDimDNS.online())
2640 out << HTML::kWhite << "\tOffline\n\n\n\n\n\n\n\n\n\n\n\n\n";
2641 else
2642 {
2643 ostringstream dt;
2644 dt << (Time()-fRunTime);
2645
2646 out << HTML::kGreen << '\t' << fDimDNS.version() << '\n';
2647
2648 out << GetStateHtml(fDimControl, 0);
2649 out << GetStateHtml(fDimMcp, 4);
2650 out << GetStateHtml(fDimDataLogger, 1);
2651 out << GetStateHtml(fDimDriveControl, 2);
2652 out << GetStateHtml(fDimTimeCheck, 1);
2653 out << GetStateHtml(fDimFadControl, FAD::State::kConnected);
2654 out << GetStateHtml(fDimFtmControl, FTM::State::kConnected);
2655 out << GetStateHtml(fDimBiasControl, BIAS::State::kConnected);
2656 out << GetStateHtml(fDimFeedback, 4);
2657 out << GetStateHtml(fDimRateControl, 4);
2658 out << GetStateHtml(fDimFscControl, 2);
2659 out << GetStateHtml(fDimRateScan, 4);
2660 out << GetStateHtml(fDimMagicWeather, 2);
2661 out << GetStateHtml(fDimTngWeather, 2);
2662 out << GetStateHtml(fDimChat, 0);
2663 out << GetStateHtml(fDimSkypeClient, 1);
2664
2665 string col = HTML::kRed;
2666 if (fFreeSpace>uint64_t(199999999999))
2667 col = HTML::kYellow;
2668 if (fFreeSpace>uint64_t(999999999999))
2669 col = HTML::kGreen;
2670 if (fFreeSpace==UINT64_MAX)
2671 col = HTML::kWhite;
2672
2673 out << col << '\t' << Tools::Scientific(fFreeSpace) << "B\n";
2674
2675 out << HTML::kGreen << '\t' << dt.str().substr(0, dt.str().length()-7) << '\n';
2676 }
2677
2678 ofstream(fPath+"/status.data") << out.str();
2679
2680 if (now-fLastAstroCalc>boost::posix_time::seconds(15))
2681 {
2682 UpdateAstronomy();
2683 fLastAstroCalc = now;
2684 }
2685
2686 return fDimDNS.online() ? kStateRunning : kStateDimNetworkNA;
2687 }
2688
2689
2690public:
2691 StateMachineSmartFACT(ostream &out=cout) : StateMachineDim(out, fIsServer?"SMART_FACT":""),
2692 fLastAstroCalc(boost::date_time::neg_infin),
2693 fPath("www/smartfact/data"),
2694 fControlScriptDepth(0),
2695 fMcpConfigurationState(DimState::kOffline),
2696 fMcpConfigurationMaxTime(0),
2697 fMcpConfigurationMaxEvents(0),
2698 fLastRunFinishedWithZeroEvents(false),
2699 fTngWeatherDustTime(Time::none),
2700 fBiasControlVoltageMed(0),
2701 fBiasControlCurrentMed(0),
2702 fBiasControlCurrentMax(0),
2703 fFscControlHumidityAvg(0),
2704 fDriveControlMoonDist(-1),
2705 fFadControlNumEvents(0),
2706 fFadControlDrsRuns(3),
2707 fRateScanDataId(0),
2708 fRateScanBoard(0),
2709 fFreeSpace(UINT64_MAX),
2710 // ---
2711 fDimMcp ("MCP"),
2712 fDimDataLogger ("DATA_LOGGER"),
2713 fDimDriveControl("DRIVE_CONTROL"),
2714 fDimTimeCheck ("TIME_CHECK"),
2715 fDimMagicWeather("MAGIC_WEATHER"),
2716 fDimTngWeather ("TNG_WEATHER"),
2717 fDimFeedback ("FEEDBACK"),
2718 fDimBiasControl ("BIAS_CONTROL"),
2719 fDimFtmControl ("FTM_CONTROL"),
2720 fDimFadControl ("FAD_CONTROL"),
2721 fDimFscControl ("FSC_CONTROL"),
2722 fDimRateControl ("RATE_CONTROL"),
2723 fDimRateScan ("RATE_SCAN"),
2724 fDimChat ("CHAT"),
2725 fDimSkypeClient ("SKYPE_CLIENT")
2726 {
2727 fDimDNS.Subscribe(*this);
2728 fDimControl.Subscribe(*this);
2729 fDimMcp.Subscribe(*this);
2730 fDimDataLogger.Subscribe(*this);
2731 fDimDriveControl.Subscribe(*this);
2732 fDimTimeCheck.Subscribe(*this);
2733 fDimMagicWeather.Subscribe(*this);
2734 fDimTngWeather.Subscribe(*this);
2735 fDimFeedback.Subscribe(*this);
2736 fDimBiasControl.Subscribe(*this);
2737 fDimFtmControl.Subscribe(*this);
2738 fDimFadControl.Subscribe(*this);
2739 fDimFscControl.Subscribe(*this);
2740 fDimRateControl.Subscribe(*this);
2741 fDimRateScan.Subscribe(*this);
2742 fDimChat.Subscribe(*this);
2743 fDimSkypeClient.Subscribe(*this);
2744
2745 fDimFscControl.SetCallback(bind(&StateMachineSmartFACT::HandleFscControlStateChange, this, placeholders::_1));
2746 fDimDriveControl.SetCallback(bind(&StateMachineSmartFACT::HandleDriveControlStateChange, this, placeholders::_1));
2747 fDimControl.SetCallback(bind(&StateMachineSmartFACT::HandleControlStateChange, this, placeholders::_1));
2748 fDimControl.AddCallback("dotest.dim", bind(&StateMachineSmartFACT::HandleDoTest, this, placeholders::_1));
2749
2750 Subscribe("DIM_CONTROL/MESSAGE")
2751 (bind(&StateMachineSmartFACT::HandleDimControlMessage, this, placeholders::_1));
2752
2753 Subscribe("MCP/CONFIGURATION")
2754 (bind(&StateMachineSmartFACT::HandleMcpConfiguration, this, placeholders::_1));
2755
2756 Subscribe("DRIVE_CONTROL/POINTING_POSITION")
2757 (bind(&StateMachineSmartFACT::HandleDrivePointing, this, placeholders::_1));
2758 Subscribe("DRIVE_CONTROL/TRACKING_POSITION")
2759 (bind(&StateMachineSmartFACT::HandleDriveTracking, this, placeholders::_1));
2760 Subscribe("DRIVE_CONTROL/SOURCE_POSITION")
2761 (bind(&StateMachineSmartFACT::HandleDriveSource, this, placeholders::_1));
2762
2763 Subscribe("FSC_CONTROL/TEMPERATURE")
2764 (bind(&StateMachineSmartFACT::HandleFscTemperature, this, placeholders::_1));
2765 Subscribe("FSC_CONTROL/HUMIDITY")
2766 (bind(&StateMachineSmartFACT::HandleFscHumidity, this, placeholders::_1));
2767
2768 Subscribe("MAGIC_WEATHER/DATA")
2769 (bind(&StateMachineSmartFACT::HandleMagicWeatherData, this, placeholders::_1));
2770 Subscribe("TNG_WEATHER/DUST")
2771 (bind(&StateMachineSmartFACT::HandleTngWeatherDust, this, placeholders::_1));
2772
2773 Subscribe("FEEDBACK/DEVIATION")
2774 (bind(&StateMachineSmartFACT::HandleFeedbackDeviation, this, placeholders::_1));
2775 Subscribe("FEEDBACK/CALIBRATION")
2776 (bind(&StateMachineSmartFACT::HandleFeedbackCalibration, this, placeholders::_1));
2777
2778 Subscribe("BIAS_CONTROL/VOLTAGE")
2779 (bind(&StateMachineSmartFACT::HandleBiasVoltage, this, placeholders::_1));
2780 Subscribe("BIAS_CONTROL/CURRENT")
2781 (bind(&StateMachineSmartFACT::HandleBiasCurrent, this, placeholders::_1));
2782
2783 Subscribe("FAD_CONTROL/CONNECTIONS")
2784 (bind(&StateMachineSmartFACT::HandleFadConnections, this, placeholders::_1));
2785 Subscribe("FAD_CONTROL/EVENTS")
2786 (bind(&StateMachineSmartFACT::HandleFadEvents, this, placeholders::_1));
2787 Subscribe("FAD_CONTROL/START_RUN")
2788 (bind(&StateMachineSmartFACT::HandleFadStartRun, this, placeholders::_1));
2789 Subscribe("FAD_CONTROL/DRS_RUNS")
2790 (bind(&StateMachineSmartFACT::HandleFadDrsRuns, this, placeholders::_1));
2791 Subscribe("FAD_CONTROL/EVENT_DATA")
2792 (bind(&StateMachineSmartFACT::HandleFadEventData, this, placeholders::_1));
2793 Subscribe("FAD_CONTROL/STATS")
2794 (bind(&StateMachineSmartFACT::HandleStats, this, placeholders::_1));
2795
2796 Subscribe("DATA_LOGGER/STATS")
2797 (bind(&StateMachineSmartFACT::HandleStats, this, placeholders::_1));
2798
2799 Subscribe("FTM_CONTROL/TRIGGER_RATES")
2800 (bind(&StateMachineSmartFACT::HandleFtmTriggerRates, this, placeholders::_1));
2801 Subscribe("FTM_CONTROL/STATIC_DATA")
2802 (bind(&StateMachineSmartFACT::HandleFtmStaticData, this, placeholders::_1));
2803 Subscribe("FTM_CONTROL/FTU_LIST")
2804 (bind(&StateMachineSmartFACT::HandleFtmFtuList, this, placeholders::_1));
2805
2806 Subscribe("RATE_CONTROL/THRESHOLD")
2807 (bind(&StateMachineSmartFACT::HandleRateControlThreshold,this, placeholders::_1));
2808
2809 Subscribe("RATE_SCAN/DATA")
2810 (bind(&StateMachineSmartFACT::HandleRateScanData, this, placeholders::_1));
2811
2812 Subscribe("CHAT/MESSAGE")
2813 (bind(&StateMachineSmartFACT::HandleChatMsg, this, placeholders::_1));
2814
2815
2816 // =================================================================
2817
2818 // State names
2819 AddStateName(kStateDimNetworkNA, "DimNetworkNotAvailable",
2820 "The Dim DNS is not reachable.");
2821
2822 AddStateName(kStateRunning, "Running", "");
2823
2824 // =================================================================
2825
2826 AddEvent("PRINT")
2827 (bind(&StateMachineSmartFACT::Print, this))
2828 ("Print a list of the states of all connected servers.");
2829
2830 }
2831 int EvalOptions(Configuration &conf)
2832 {
2833 if (!fPixelMap.Read(conf.Get<string>("pixel-map-file")))
2834 {
2835 Error("Reading mapping table from "+conf.Get<string>("pixel-map-file")+" failed.");
2836 return 1;
2837 }
2838
2839 fPath = conf.Get<string>("path");
2840 fDatabase = conf.Get<string>("source-database");
2841
2842 struct stat st;
2843 if (stat(fPath.c_str(), &st))
2844 {
2845 Error(fPath+" does not exist!");
2846 return 2;
2847 }
2848
2849 if ((st.st_mode&S_IFDIR)==0)
2850 {
2851 Error(fPath+" not a directory!");
2852 return 3;
2853 }
2854
2855 if ((st.st_mode&S_IWUSR)==0)
2856 {
2857 Error(fPath+" has no write permission!");
2858 return 4;
2859 }
2860
2861 if ((st.st_mode&S_IXUSR)==0)
2862 {
2863 Error(fPath+" has no execute permission!");
2864 return 5;
2865 }
2866
2867 ostringstream out;
2868 out << Time().JavaDate() << '\n';
2869
2870 ofstream(fPath+"/error.data") << out.str();
2871
2872 return -1;
2873 }
2874};
2875
2876bool StateMachineSmartFACT::fIsServer = false;
2877
2878// ------------------------------------------------------------------------
2879
2880#include "Main.h"
2881
2882template<class T>
2883int RunShell(Configuration &conf)
2884{
2885 StateMachineSmartFACT::fIsServer = !conf.Get<bool>("client");
2886 return Main::execute<T, StateMachineSmartFACT>(conf);
2887}
2888
2889void SetupConfiguration(Configuration &conf)
2890{
2891 po::options_description control("Smart FACT");
2892 control.add_options()
2893 ("pixel-map-file", var<string>("FACTmapV5a.txt"), "Pixel mapping file. Used here to get the default reference voltage")
2894 ("path", var<string>("www/smartfact/data"), "Output path for the data-files")
2895 ("source-database", var<string>(""), "Database link as in\n\tuser:password@server[:port]/database.")
2896 ("client", po_bool(false), "For a standalone client choose this option.")
2897 ;
2898
2899 conf.AddOptions(control);
2900}
2901
2902/*
2903 Extract usage clause(s) [if any] for SYNOPSIS.
2904 Translators: "Usage" and "or" here are patterns (regular expressions) which
2905 are used to match the usage synopsis in program output. An example from cp
2906 (GNU coreutils) which contains both strings:
2907 Usage: cp [OPTION]... [-T] SOURCE DEST
2908 or: cp [OPTION]... SOURCE... DIRECTORY
2909 or: cp [OPTION]... -t DIRECTORY SOURCE...
2910 */
2911void PrintUsage()
2912{
2913 cout <<
2914 "SmartFACT is a tool writing the files needed for the SmartFACT web interface.\n"
2915 "\n"
2916 "The default is that the program is started without user intercation. "
2917 "All actions are supposed to arrive as DimCommands. Using the -c "
2918 "option, a local shell can be initialized. With h or help a short "
2919 "help message about the usuage can be brought to the screen.\n"
2920 "\n"
2921 "Usage: smartfact [-c type] [OPTIONS]\n"
2922 " or: smartfact [OPTIONS]\n";
2923 cout << endl;
2924}
2925
2926void PrintHelp()
2927{
2928 Main::PrintHelp<StateMachineSmartFACT>();
2929
2930 /* Additional help text which is printed after the configuration
2931 options goes here */
2932
2933 /*
2934 cout << "bla bla bla" << endl << endl;
2935 cout << endl;
2936 cout << "Environment:" << endl;
2937 cout << "environment" << endl;
2938 cout << endl;
2939 cout << "Examples:" << endl;
2940 cout << "test exam" << endl;
2941 cout << endl;
2942 cout << "Files:" << endl;
2943 cout << "files" << endl;
2944 cout << endl;
2945 */
2946}
2947
2948int main(int argc, const char* argv[])
2949{
2950 Configuration conf(argv[0]);
2951 conf.SetPrintUsage(PrintUsage);
2952 Main::SetupConfiguration(conf);
2953 SetupConfiguration(conf);
2954
2955 if (!conf.DoParse(argc, argv, PrintHelp))
2956 return 127;
2957
2958 if (!conf.Has("console"))
2959 return RunShell<LocalStream>(conf);
2960
2961 if (conf.Get<int>("console")==0)
2962 return RunShell<LocalShell>(conf);
2963 else
2964 return RunShell<LocalConsole>(conf);
2965
2966 return 0;
2967}
Note: See TracBrowser for help on using the repository browser.