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

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