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

Last change on this file since 13948 was 13944, checked in by tbretz, 12 years ago
Some code cosmetics
File size: 70.5 KB
Line 
1#ifdef HAVE_LIBNOVA
2#include <libnova/solar.h>
3#include <libnova/lunar.h>
4#include <libnova/rise_set.h>
5#endif
6
7#include "Dim.h"
8#include "Event.h"
9#include "Shell.h"
10#include "StateMachineDim.h"
11#include "Connection.h"
12#include "Configuration.h"
13#include "Console.h"
14#include "Converter.h"
15#include "PixelMap.h"
16
17#include "tools.h"
18
19#include "LocalControl.h"
20
21#include "HeadersFAD.h"
22#include "HeadersBIAS.h"
23#include "HeadersFTM.h"
24#include "HeadersFSC.h"
25#include "HeadersMCP.h"
26#include "HeadersDrive.h"
27#include "HeadersFeedback.h"
28#include "HeadersRateScan.h"
29#include "HeadersRateControl.h"
30#include "HeadersMagicWeather.h"
31
32#include <boost/filesystem.hpp>
33
34using namespace std;
35
36// ------------------------------------------------------------------------
37
38#include "DimDescriptionService.h"
39#include "DimState.h"
40
41// ------------------------------------------------------------------------
42/*
43template<class T>
44 class buffer : public deque<T>
45 {
46 int32_t max_size;
47
48 public:
49 buffer(int32_t max=-1) : max_size(max) { }
50 const T &operator=(const T &t) const { push_back(t); if (max_size>0 && deque<T>::size()>max_size) deque<T>::pop_front(); }
51 operator T() const { return deque<T>::size()>0 ? deque<T>::back() : T(); }
52 bool valid() const { return deque<T>::size()>0; }
53 };
54*/
55
56// ------------------------------------------------------------------------
57
58namespace HTML
59{
60 const static string kWhite = "#ffffff";
61 const static string kYellow = "#fffff0";
62 const static string kRed = "#fff8f0";
63 const static string kGreen = "#f0fff0";
64 const static string kBlue = "#f0f0ff";
65};
66
67// ========================================================================
68// ========================================================================
69// ========================================================================
70
71class Astro
72{
73public:
74 Time time;
75
76 Time fSunRiseDayTime;
77 Time fSunRiseCivil;
78 Time fSunRiseAstronomical;
79 Time fSunRiseDarkTime;
80
81 Time fSunSetDayTime;
82 Time fSunSetCivil;
83 Time fSunSetAstronomical;
84 Time fSunSetDarkTime;
85
86 int state;
87 string description;
88 string color;
89
90 bool isday;
91
92public:
93 Astro(double lon, double lat, const Time &t=Time()) : time(t)
94 {
95#ifdef HAVE_LIBNOVA
96 ln_lnlat_posn observer;
97 observer.lng = lon;
98 observer.lat = lat;
99
100 // get Julian day from local time
101 const double JD = time.JD();
102
103 ln_rst_time sun_day;
104 ln_rst_time sun_civil;
105 ln_rst_time sun_astronomical;
106 ln_rst_time sun_dark;
107
108 // Warning: return code of 1 means circumpolar and is not checked!
109 //ln_get_lunar_rst (JD-0.5, &observer, &moon);
110 ln_get_solar_rst (JD-0.5, &observer, &sun_day);
111 ln_get_solar_rst_horizon(JD-0.5, &observer, - 6, &sun_civil);
112 ln_get_solar_rst_horizon(JD-0.5, &observer, -12, &sun_astronomical);
113 ln_get_solar_rst_horizon(JD-0.5, &observer, -18, &sun_dark);
114
115 fSunSetDayTime = Time(sun_day.set);
116 fSunSetCivil = Time(sun_civil.set);
117 fSunSetAstronomical = Time(sun_astronomical.set);
118 fSunSetDarkTime = Time(sun_dark.set);
119
120 fSunRiseDayTime = Time(sun_day.rise);
121 fSunRiseCivil = Time(sun_civil.rise);
122 fSunRiseAstronomical = Time(sun_astronomical.rise);
123 fSunRiseDarkTime = Time(sun_dark.rise);
124
125 const bool is_day = JD>sun_day.rise;
126 const bool is_night = JD>sun_dark.set;
127
128 //ln_get_lunar_rst (JD+0.5, &observer, &moon);
129 ln_get_solar_rst (JD+0.5, &observer, &sun_day);
130 ln_get_solar_rst_horizon(JD+0.5, &observer, - 6, &sun_civil);
131 ln_get_solar_rst_horizon(JD+0.5, &observer, -12, &sun_astronomical);
132 ln_get_solar_rst_horizon(JD+0.5, &observer, -18, &sun_dark);
133
134 if (is_day)
135 {
136 fSunRiseDayTime = Time(sun_day.rise);
137 fSunRiseCivil = Time(sun_civil.rise);
138 fSunRiseAstronomical = Time(sun_astronomical.rise);
139 fSunRiseDarkTime = Time(sun_dark.rise);
140 }
141
142 if (is_night)
143 {
144 fSunSetDayTime = Time(sun_day.set);
145 fSunSetCivil = Time(sun_civil.set);
146 fSunSetAstronomical = Time(sun_astronomical.set);
147 fSunSetDarkTime = Time(sun_dark.set);
148 }
149
150 // case 0: midnight to sun-rise | !is_day && !is_night | rise/set
151 // case 1: sun-rise to sun-set | is_day && !is_night | set /rise
152 // case 2: sun-set to midnight | is_day && is_night | rise/set
153 /*
154 if (is_day^is_night)
155 {
156 cout << "SunSet: " << fSunSetDayTime << endl;
157 cout << "SunRise: " << fSunRiseDayTime << endl;
158 }
159 else
160 {
161 cout << "SunRise: " << fSunRiseDayTime << endl;
162 cout << "SunSet: " << fSunSetDayTime << endl;
163 }*/
164
165 isday = is_day^is_night;
166
167 state = isday ? 4 : 0;
168 if (time>fSunSetDayTime) state++;
169 if (time>fSunSetCivil) state++;
170 if (time>fSunSetAstronomical) state++;
171 if (time>fSunSetDarkTime) state++;
172
173 if (time>fSunRiseDarkTime) state++;
174 if (time>fSunRiseAstronomical) state++;
175 if (time>fSunRiseCivil) state++;
176 if (time>fSunRiseDayTime) state++;
177
178 string name[] =
179 {
180 "dark time",
181 "astron. twilight",
182 "civil twilight",
183 "sunrise",
184 "day time",
185 "sunset",
186 "civil twilight",
187 "astron. twilight",
188 "dark time"
189 };
190
191 description = state[name];
192
193 string arr;
194 ostringstream out;
195 if (isday)
196 {
197 out << fSunSetDarkTime-time;
198 arr = "&darr;";
199 }
200 else
201 {
202 out << fSunRiseDayTime-time;
203 arr = "&uarr;";
204 }
205
206 description += " ["+out.str().substr(0, 5)+arr+"]";
207
208 switch (state)
209 {
210 case 0: case 1: color = HTML::kGreen; break;
211 case 2: case 3: color = HTML::kYellow; break;
212 case 4: color = HTML::kRed; break;
213 case 5: case 6: color = HTML::kYellow; break;
214 case 7: case 8: color = HTML::kGreen; break;
215 }
216#endif
217 }
218};
219
220class Moon
221{
222public:
223 double ra;
224 double dec;
225
226 double disk;
227
228 bool visible;
229
230 Time fMoonRise;
231 Time fMoonTransit;
232 Time fMoonSet;
233
234 string description;
235 string color;
236
237 Time time;
238
239 Moon(double lon, double lat, const Time &t=Time()) : time(t)
240 {
241#ifdef HAVE_LIBNOVA
242 const double JD = time.JD();
243
244 ln_lnlat_posn observer;
245 observer.lng = lon;
246 observer.lat = lat;
247
248 ln_rst_time moon;
249 ln_get_lunar_rst(JD-0.5, &observer, &moon);
250
251 fMoonRise = Time(moon.rise);
252 fMoonTransit = Time(moon.transit);
253 fMoonSet = Time(moon.set);
254
255 visible =
256 (JD>moon.rise && JD<moon.set && moon.rise<moon.set) ||
257 ((JD<moon.set || JD>moon.rise) && moon.rise>moon.set);
258
259 const bool is_up = JD>moon.rise;
260 const bool is_sinking = JD>moon.transit;
261 const bool is_dn = JD>moon.set;
262
263 ln_get_lunar_rst(JD+0.5, &observer, &moon);
264 if (is_up)
265 fMoonRise = Time(moon.rise);
266 if (is_sinking)
267 fMoonTransit = Time(moon.transit);
268 if (is_dn)
269 fMoonSet = Time(moon.set);
270
271 ln_equ_posn pos;
272 ln_get_lunar_equ_coords(JD, &pos);
273
274 ra = pos.ra/15;
275 dec = pos.dec;
276
277 disk = ln_get_lunar_disk(JD)*100;
278
279 if (!visible || disk<25)
280 color = HTML::kGreen;
281 else
282 color = disk>75 ? HTML::kRed : HTML::kYellow;
283
284 string arr;
285 ostringstream dt;
286 if (fMoonSet<fMoonRise)
287 {
288 dt << fMoonSet-time;
289 arr = "&darr;";
290 }
291 else
292 {
293 dt << fMoonRise-time;
294 arr = "&uarr;";
295 }
296
297 ostringstream out;
298 out << setprecision(2);
299 out << (visible?"visible ":"") << (disk<0.1?0:disk) << "% [" << dt.str().substr(0,5) << arr << "]";
300
301 description = out.str();
302#endif
303 }
304
305 double Angle(double r, double d)
306 {
307 const double theta0 = M_PI/2-d*M_PI/180;
308 const double phi0 = r*M_PI/12;
309
310 const double theta1 = M_PI/2-dec*M_PI/180;
311 const double phi1 = ra*M_PI/12;
312
313 const double x0 = sin(theta0) * cos(phi0);
314 const double y0 = sin(theta0) * sin(phi0);
315 const double z0 = cos(theta0);
316
317 const double x1 = sin(theta1) * cos(phi1);
318 const double y1 = sin(theta1) * sin(phi1);
319 const double z1 = cos(theta1);
320
321 double arg = x0*x1 + y0*y1 + z0*z1;
322 if(arg > 1.0) arg = 1.0;
323 if(arg < -1.0) arg = -1.0;
324
325 return acos(arg) * 180/M_PI;
326 }
327};
328
329// ========================================================================
330// ========================================================================
331// ========================================================================
332
333class StateMachineSmartFACT : public StateMachineDim
334{
335private:
336 const Time fRunTime;
337
338 enum states_t
339 {
340 kStateDimNetworkNA = 1,
341 kStateRunning,
342 };
343
344 // ------------------------- Internal variables -----------------------
345
346 PixelMap fPixelMap;
347
348 Time fLastUpdate;
349
350 string fPath;
351
352 // ----------------------------- Data storage -------------------------
353
354 deque<string> fControlMessageHist;
355 int32_t fControlScriptDepth;
356
357 uint32_t fMcpConfigurationState; // For consistency
358 int64_t fMcpConfigurationMaxTime;
359 int64_t fMcpConfigurationMaxEvents;
360 string fMcpConfigurationName;
361 Time fMcpConfigurationRunStart;
362
363 enum weather_t { kWeatherBegin=0, kTemp = kWeatherBegin, kDew, kHum, kPress, kWind, kGusts, kDir, kWeatherEnd = kDir+1 };
364 deque<float> fMagicWeatherHist[kWeatherEnd];
365
366 deque<float> fTngWeatherDustHist;
367 Time fTngWeatherDustTime;
368
369 vector<float> fFeedbackCalibration;
370
371 float fFeedbackTempOffset;
372 float fFeedbackUserOffset;
373
374 vector<float> fBiasControlVoltageVec;
375
376 float fBiasControlPowerTot;
377 float fBiasControlVoltageMed;
378 float fBiasControlCurrentMed;
379 float fBiasControlCurrentMax;
380
381 deque<float> fBiasControlCurrentHist;
382 deque<float> fFscControlTemperatureHist;
383
384 float fFscControlHumidityAvg;
385
386 float fDriveControlPointingZd;
387 string fDriveControlPointingAz;
388 string fDriveControlSourceName;
389 float fDriveControlMoonDist;
390
391 deque<float> fDriveControlTrackingDevHist;
392
393 int64_t fFadControlNumEvents;
394 int32_t fFadControlDrsStep;
395 uint32_t fFadControlDrsRuns[3];
396
397 float fFtmControlTriggerRateCam;
398 deque<float> fFtmControlTriggerRateHist;
399
400 float fFtmPatchThresholdMed;
401 float fFtmBoardThresholdMed;
402
403 bool fFtmControlFtuOk;
404
405 uint64_t fRateScanDataId;
406 uint8_t fRateScanBoard;
407 deque<float> fRateScanDataHist[41];
408
409 int fHasError;
410
411 // ------------- Initialize variables before the Dim stuff ------------
412
413 DimVersion fDimDNS;
414 DimControl fDimControl;
415 DimDescribedState fDimMcp;
416 DimDescribedState fDimDataLogger;
417 DimDescribedState fDimDriveControl;
418 DimDescribedState fDimMagicWeather;
419 DimDescribedState fDimTngWeather;
420 DimDescribedState fDimFeedback;
421 DimDescribedState fDimBiasControl;
422 DimDescribedState fDimFtmControl;
423 DimDescribedState fDimFadControl;
424 DimDescribedState fDimFscControl;
425 DimDescribedState fDimRateControl;
426 DimDescribedState fDimRateScan;
427 DimDescribedState fDimChatServer;
428
429 // -------------------------------------------------------------------
430
431 bool CheckDataSize(const EventImp &d, const char *name, size_t size, bool min=false)
432 {
433 if (d.GetSize()==0)
434 return false;
435
436 if ((!min && d.GetSize()==size) || (min && d.GetSize()>size))
437 return true;
438
439 ostringstream msg;
440 msg << name << " - Received service has " << d.GetSize() << " bytes, but expected ";
441 if (min)
442 msg << "more than ";
443 msg << size << ".";
444 Warn(msg);
445 return false;
446 }
447
448 // -------------------------------------------------------------------
449
450 template<class T>
451 void WriteBinary(const EventImp &d, const string &fname, const T &t, double scale, double offset=0)
452 {
453 const Statistics stat(t);
454
455 vector<uint8_t> val(t.size(), 0);
456 for (uint64_t i=0; i<t.size(); i++)
457 {
458 float range = nearbyint(128*(t[i]-offset)/scale); // [-2V; 2V]
459 if (range>127)
460 range=127;
461 if (range<0)
462 range=0;
463 val[i] = (uint8_t)range;
464 }
465
466 const char *ptr = reinterpret_cast<char*>(val.data());
467
468 ostringstream out;
469 out << d.GetJavaDate() << '\n';
470 out << offset << '\n';
471 out << offset+scale << '\n';
472 out << setprecision(3);
473 out << stat.min << '\n';
474 out << stat.med << '\n';
475 out << stat.max << '\n';
476 out.write(ptr, val.size()*sizeof(uint8_t));
477
478 ofstream(fPath+"/"+fname+".bin") << out.str();
479 }
480
481 // -------------------------------------------------------------------
482
483 struct Statistics
484 {
485 float min;
486 float max;
487 float med;
488 float avg;
489 //float rms;
490
491 template<class T>
492 Statistics(const T &t, size_t offset_min=0, size_t offset_max=0)
493 : min(0), max(0), med(0), avg(0)
494 {
495 if (t.size()==0)
496 return;
497
498 T copy(t);
499 sort(copy.begin(), copy.end());
500
501 if (offset_min>t.size())
502 offset_min = 0;
503 if (offset_max>t.size())
504 offset_max = 0;
505
506 min = copy[offset_min];
507 max = copy[copy.size()-1-offset_max];
508 avg = accumulate (t.begin(), t.end(), 0.)/t.size();
509
510 const size_t p = t.size()/2;
511
512 med = copy[p];
513 }
514 };
515
516 void HandleControlMessageImp(const EventImp &d)
517 {
518 if (d.GetSize()==0)
519 return;
520
521 const string time = d.GetTimeAsStr("%H:%M:%S ");
522
523 string str = " ";
524 for (auto it=fControlMessageHist.rbegin(); it!=fControlMessageHist.rend(); it++)
525 {
526 str = it->substr(0, time.length());
527 if (str!="--:--:-- ")
528 break;
529 }
530
531 ostringstream tst;
532 tst << d.GetQoS();
533
534 string msg;
535 msg += str==time ? "--:--:-- " : time;
536 msg += "<->"+string(d.Ptr<char>())+"</->";
537
538 fControlMessageHist.push_back(msg);
539
540 ostringstream out;
541 out << setprecision(3);
542 out << d.GetJavaDate() << '\n';
543 out << HTML::kWhite << '\t';
544
545 for (auto it=fControlMessageHist.begin(); it!=fControlMessageHist.end(); it++)
546 out << *it << "<br/>";
547
548 out << '\n';
549
550 ofstream(fPath+"/scriptlog.data") << out.str();
551 }
552
553 int HandleDimControlMessage(const EventImp &d)
554 {
555 if (d.GetSize()==0)
556 return GetCurrentState();
557
558 if (d.GetQoS()==90)
559 HandleControlMessageImp(d);
560
561 return GetCurrentState();
562 }
563
564 void HandleControlStateChange(const EventImp &d)
565 {
566 if (d.GetSize()==0)
567 return;
568
569 if (d.GetQoS()==-2 && fDimControl.scriptdepth==0)
570 fControlMessageHist.clear();
571
572 if (d.GetQoS()>=0)
573 return;
574
575#if BOOST_VERSION < 104600
576 const string file = boost::filesystem::path(fDimControl.file).filename();
577#else
578 const string file = boost::filesystem::path(fDimControl.file).filename().string();
579#endif
580
581 HandleControlMessageImp(Event(d, fDimControl.shortmsg.data(), fDimControl.shortmsg.length()+1));
582 if (!file.empty())
583 HandleControlMessageImp(Event(d, file.data(), file.length()+1));
584 }
585
586 int HandleMcpConfiguration(const EventImp &d)
587 {
588 if (!CheckDataSize(d, "Mcp:Configuration", 16, true))
589 {
590 fMcpConfigurationState = 0;
591 fMcpConfigurationMaxTime = 0;
592 fMcpConfigurationMaxEvents = 0;
593 fMcpConfigurationName = "";
594 fMcpConfigurationRunStart = Time(Time::none);
595 return GetCurrentState();
596 }
597
598 fMcpConfigurationState = d.GetQoS();
599 fMcpConfigurationMaxTime = d.Get<uint64_t>();
600 fMcpConfigurationMaxEvents = d.Get<uint64_t>(8);
601 fMcpConfigurationName = d.Ptr<char>(16);
602
603 if (d.GetQoS()==12)
604 fMcpConfigurationRunStart = Time();
605
606 return GetCurrentState();
607 }
608
609 void WriteWeather(const EventImp &d, const string &name, int i, float min, float max)
610 {
611 const Statistics stat(fMagicWeatherHist[i]);
612
613 ostringstream out;
614 out << setprecision(3);
615 out << d.GetJavaDate() << '\n';
616
617 out << HTML::kWhite << '\t' << fMagicWeatherHist[i].back() << '\n';
618 out << HTML::kWhite << '\t' << stat.min << '\n';
619 out << HTML::kWhite << '\t' << stat.avg << '\n';
620 out << HTML::kWhite << '\t' << stat.max << '\n';
621
622 ofstream(fPath+"/"+name+".data") << out.str();
623
624 WriteBinary(d, "magicweather-"+name+"-hist", fMagicWeatherHist[i], max-min, min);
625 }
626
627 int HandleMagicWeatherData(const EventImp &d)
628 {
629 if (!CheckDataSize(d, "MagicWeather:Data", 7*4+2))
630 return GetCurrentState();
631
632 // Store a history of the last 300 entries
633 for (int i=kWeatherBegin; i<kWeatherEnd; i++)
634 {
635 fMagicWeatherHist[i].push_back(d.Ptr<float>(2)[i]);
636 if (fMagicWeatherHist[i].size()>300)
637 fMagicWeatherHist[i].pop_front();
638 }
639
640 static const char *dir[] =
641 {
642 "N", "NNE", "NE", "ENE",
643 "E", "ESE", "SE", "SSE",
644 "S", "SSW", "SW", "WSW",
645 "W", "WNW", "NW", "NNW"
646 };
647
648
649 const uint16_t idx = uint16_t(floor(fMagicWeatherHist[kDir].back()/22.5+16.5))%16;
650 //const uint16_t idx = uint16_t(floor(fmod(fMagicWeatherHist[kDir].back()/22.5+360+11.25, 360)/22.5))%16;
651
652 Astro astro(-(17.+53./60+26.525/3600), 28.+45./60+42.462/3600);
653 Moon moon (-(17.+53./60+26.525/3600), 28.+45./60+42.462/3600);
654
655 ostringstream out;
656 out << d.GetJavaDate() << '\n';
657 out << astro.color << '\t' << astro.description << '\n';
658 out << setprecision(2);
659 out << (astro.isday?HTML::kWhite:moon.color) << '\t' << moon.description << '\n';
660 out << setprecision(3);
661 for (int i=0; i<6; i++)
662 out << HTML::kWhite << '\t' << fMagicWeatherHist[i].back() << '\n';
663 out << HTML::kWhite << '\t' << dir[idx] << '\n';
664 out << HTML::kWhite << '\t';
665 if (fTngWeatherDustHist.size()>0)
666 out << fTngWeatherDustHist.back() << '\t' << fTngWeatherDustTime.GetAsStr("%H:%M") << '\n';
667 else
668 out << "\t\n";
669
670 ofstream(fPath+"/weather.data") << out.str();
671
672 out.str("");
673 out << astro.time.JavaDate() << '\n';
674 out << HTML::kWhite << '\t' << astro.fSunRiseDarkTime.GetAsStr("%H:%M") << '\n';
675 out << HTML::kWhite << '\t' << astro.fSunRiseAstronomical.GetAsStr("%H:%M") << '\n';
676 out << HTML::kWhite << '\t' << astro.fSunRiseCivil.GetAsStr("%H:%M") << '\n';
677 out << HTML::kWhite << '\t' << astro.fSunRiseDayTime.GetAsStr("%H:%M") << '\n';
678
679 out << HTML::kWhite << '\t' << astro.fSunSetDayTime.GetAsStr("%H:%M") << '\n';
680 out << HTML::kWhite << '\t' << astro.fSunSetCivil.GetAsStr("%H:%M") << '\n';
681 out << HTML::kWhite << '\t' << astro.fSunSetAstronomical.GetAsStr("%H:%M") << '\n';
682 out << HTML::kWhite << '\t' << astro.fSunSetDarkTime.GetAsStr("%H:%M") << '\n';
683
684 out << HTML::kWhite << '\t' << moon.fMoonRise.GetAsStr("%H:%M") << '\n';
685 out << HTML::kWhite << '\t' << moon.fMoonTransit.GetAsStr("%H:%M") << '\n';
686 out << HTML::kWhite << '\t' << moon.fMoonSet.GetAsStr("%H:%M") << '\n';
687 out << HTML::kWhite << '\t';
688
689 ofstream(fPath+"/astro.data") << out.str();
690
691 WriteWeather(d, "temp", kTemp, -5, 35);
692 WriteWeather(d, "dew", kDew, -5, 35);
693 WriteWeather(d, "hum", kHum, 0, 100);
694 WriteWeather(d, "wind", kWind, 0, 100);
695 WriteWeather(d, "gusts", kGusts, 0, 100);
696 WriteWeather(d, "press", kPress, 700, 1000);
697
698 return GetCurrentState();
699 }
700
701 int HandleTngWeatherDust(const EventImp &d)
702 {
703 if (!CheckDataSize(d, "TngWeather:Dust", 4))
704 return GetCurrentState();
705
706 fTngWeatherDustTime = d.GetTime();
707
708 fTngWeatherDustHist.push_back(d.GetFloat());
709 if (fTngWeatherDustHist.size()>300)
710 fTngWeatherDustHist.pop_front();
711
712 const Statistics stat(fTngWeatherDustHist);
713
714 const double scale = stat.max>0 ? pow(10, ceil(log10(stat.max))) : 0;
715
716 WriteBinary(d, "tng-dust-hist", fTngWeatherDustHist, scale);
717
718 ostringstream out;
719 out << d.GetJavaDate() << '\n';
720
721 ofstream(fPath+"/tngdust.data") << out.str();
722
723 return GetCurrentState();
724 }
725
726 int HandleDrivePointing(const EventImp &d)
727 {
728 if (!CheckDataSize(d, "DriveControl:Pointing", 16))
729 return GetCurrentState();
730
731 fDriveControlPointingZd = d.Get<double>();
732
733 const double az = d.Get<double>(8);
734
735 static const char *dir[] =
736 {
737 "N", "NNE", "NE", "ENE",
738 "E", "ESE", "SE", "SSE",
739 "S", "SSW", "SW", "WSW",
740 "W", "WNW", "NW", "NNW"
741 };
742
743 const uint16_t idx = uint16_t(floor(az/22.5+16.5))%16;
744 fDriveControlPointingAz = dir[idx];
745
746 ostringstream out;
747 out << d.GetJavaDate() << '\n';
748
749 out << setprecision(5);
750 out << fDriveControlPointingZd << '\n';
751 out << az << '\n';
752
753 ofstream(fPath+"/drive-pointing.data") << out.str();
754
755 return GetCurrentState();
756 }
757
758 int HandleDriveTracking(const EventImp &d)
759 {
760 if (!CheckDataSize(d, "DriveControl:Tracking", 56))
761 return GetCurrentState();
762
763 const double Ra = d.Get<double>(0*8);
764 const double Dec = d.Get<double>(1*8);
765 const double Zd = d.Get<double>(3*8);
766 const double Az = d.Get<double>(4*8);
767
768 const double zd = Zd * M_PI / 180;
769 const double dzd = d.Get<double>(5*8) * M_PI / 180;
770 const double daz = d.Get<double>(6*8) * M_PI / 180;
771
772 // Correct:
773 // const double d = cos(del) - sin(zd+dzd)*sin(zd)*(1.-cos(daz));
774
775 // Simplified:
776 double dev = cos(dzd) - sin(zd+dzd)*sin(zd)*(1.-cos(daz));
777 dev = acos(dev) * 180 / M_PI * 3600;
778
779 fDriveControlTrackingDevHist.push_back(dev);
780 if (fDriveControlTrackingDevHist.size()>300)
781 fDriveControlTrackingDevHist.pop_front();
782
783 WriteBinary(d, "control-deviation-hist", fDriveControlTrackingDevHist, 120);
784
785 ostringstream out;
786 out << d.GetJavaDate() << '\n';
787
788 out << HTML::kWhite << '\t' << fDriveControlSourceName << '\n';
789 out << setprecision(5);
790 out << HTML::kWhite << '\t' << Ra << '\n';
791 out << HTML::kWhite << '\t' << Dec << '\n';
792 out << setprecision(3);
793 out << HTML::kWhite << '\t' << Zd << '\n';
794 out << HTML::kWhite << '\t' << Az << '\n';
795 out << HTML::kWhite << '\t' << dev << '\n';
796
797 fDriveControlMoonDist = -1;
798
799 Moon moon(-(17.+53./60+26.525/3600), 28.+45./60+42.462/3600);
800 if (moon.visible)
801 {
802 const double angle = moon.Angle(Ra, Dec);
803
804 string col = HTML::kGreen;
805 if (angle<20 || angle>140)
806 col = HTML::kYellow;
807 if (angle<10 || angle>150)
808 col = HTML::kRed;
809 out << col << '\t' << setprecision(3) << angle << '\n';
810
811 fDriveControlMoonDist = angle;
812 }
813 else
814 out << HTML::kWhite << "\t&mdash; \n";
815
816 ofstream(fPath+"/tracking.data") << out.str();
817
818 return GetCurrentState();
819 }
820
821 int HandleDriveSource(const EventImp &d)
822 {
823 if (!CheckDataSize(d, "DriveControl:Source", 7*4+2, true))
824 return GetCurrentState();
825
826 const double *ptr = d.Ptr<double>();
827
828 const double ra = ptr[0]; // Ra[h]
829 const double dec = ptr[1]; // Dec[deg]
830 const double woff = ptr[4]; // Wobble offset [deg]
831 const double wang = ptr[5]; // Wobble angle [deg]
832
833 fDriveControlSourceName = d.Ptr<char>(6*8);
834
835 ostringstream out;
836 out << d.GetJavaDate() << '\n';
837
838 out << HTML::kWhite << '\t' << fDriveControlSourceName << '\n';
839 out << setprecision(5);
840 out << HTML::kWhite << '\t' << ra << '\n';
841 out << HTML::kWhite << '\t' << dec << '\n';
842 out << setprecision(3);
843 out << HTML::kWhite << '\t' << woff << '\n';
844 out << HTML::kWhite << '\t' << wang << '\n';
845
846 ofstream(fPath+"/source.data") << out.str();
847
848 return GetCurrentState();
849 }
850
851 int HandleFeedbackCalibration(const EventImp &d)
852 {
853 if (!CheckDataSize(d, "Feedback:Calibration", 3*4*416))
854 {
855 fFeedbackCalibration.clear();
856 return GetCurrentState();
857 }
858
859 const float *ptr = d.Ptr<float>();
860 fFeedbackCalibration.assign(ptr+2*416, ptr+3*416);
861
862 return GetCurrentState();
863 }
864
865 int HandleFeedbackDeviation(const EventImp &d)
866 {
867 if (!CheckDataSize(d, "Feedback:Deviation", (2*416+2)*4))
868 return GetCurrentState();
869
870 const float *ptr = d.Ptr<float>();
871 vector<float> dev(ptr+416, ptr+416+320);
872
873 fFeedbackTempOffset = ptr[2*416];
874 fFeedbackUserOffset = ptr[2*416+1];
875
876 for (int i=0; i<320; i++)
877 dev[i] -= fFeedbackTempOffset+fFeedbackUserOffset;
878
879 // Write the 160 patch values to a file
880 WriteBinary(d, "feedback-deviation", dev, 1);
881
882 const Statistics stat(dev, 3);
883
884 ostringstream out;
885 out << d.GetJavaDate() << '\n';
886 out << HTML::kWhite << '\t' << fFeedbackUserOffset << '\n';
887 out << setprecision(3);
888 out << HTML::kWhite << '\t' << fFeedbackTempOffset << '\n';
889 out << HTML::kWhite << '\t' << stat.min << '\n';
890 out << HTML::kWhite << '\t' << stat.med << '\n';
891 out << HTML::kWhite << '\t' << stat.avg << '\n';
892 out << HTML::kWhite << '\t' << stat.max << '\n';
893 ofstream(fPath+"/feedback.data") << out.str();
894
895 return GetCurrentState();
896 }
897
898 int HandleBiasVoltage(const EventImp &d)
899 {
900 if (!CheckDataSize(d, "BiasControl:Voltage", 1664))
901 {
902 fBiasControlVoltageVec.clear();
903 return GetCurrentState();
904 }
905
906 fBiasControlVoltageVec.assign(d.Ptr<float>(), d.Ptr<float>()+320);
907
908 const Statistics stat(fBiasControlVoltageVec);
909
910 fBiasControlVoltageMed = stat.med;
911
912 vector<float> val(320, 0);
913 for (int i=0; i<320; i++)
914 {
915 const int idx = (fPixelMap.hv(i).hw()/9)*2+fPixelMap.hv(i).group();
916 val[idx] = fBiasControlVoltageVec[i];
917 }
918
919 if (fDimBiasControl.state()==BIAS::State::kVoltageOn)
920 WriteBinary(d, "biascontrol-voltage", val, 10, 65);
921 else
922 WriteBinary(d, "biascontrol-voltage", val, 75);
923
924 ostringstream out;
925 out << setprecision(3);
926 out << d.GetJavaDate() << '\n';
927 out << HTML::kWhite << '\t' << stat.min << '\n';
928 out << HTML::kWhite << '\t' << stat.med << '\n';
929 out << HTML::kWhite << '\t' << stat.avg << '\n';
930 out << HTML::kWhite << '\t' << stat.max << '\n';
931 ofstream(fPath+"/voltage.data") << out.str();
932
933 return GetCurrentState();
934 }
935
936 int HandleBiasCurrent(const EventImp &d)
937 {
938 if (!CheckDataSize(d, "BiasControl:Current", 832))
939 return GetCurrentState();
940
941 // Convert dac counts to uA
942 vector<float> v(320);
943 for (int i=0; i<320; i++)
944 v[i] = d.Ptr<uint16_t>()[i] * 5000./4096;
945
946 const bool cal = fFeedbackCalibration.size()>0 && fBiasControlVoltageVec.size()>0;
947
948 double power_tot = 0;
949 double power_apd = 0;
950
951 // 3900 Ohm/n + 1000 Ohm + 1100 Ohm (with n=4 or n=5)
952 const double R[2] = { 3075, 2870 };
953
954 // Calibrate the data (subtract offset)
955 if (cal)
956 for (int i=0; i<320; i++)
957 {
958 // Measued current minus leakage current (bias crate calibration)
959 v[i] -= fBiasControlVoltageVec[i]/fFeedbackCalibration[i]*1e6;
960
961 // Total power participated in the camera at the G-APD
962 // and the serial resistors (total voltage minus voltage
963 // drop at resistors in bias crate)
964 power_tot += v[i]*(fBiasControlVoltageVec[i] - 1100e-6*v[i])*1e-6;
965
966 // Group index (0 or 1) of the of the pixel (4 or 5 pixel patch)
967 const int g = fPixelMap.hv(i).group();
968
969 // Current per G-APD
970 v[i] /= g ? 5 : 4;
971
972 // Power consumption per G-APD
973 if (i!=66 && i!=191 && i!=193)
974 power_apd += v[i]*(fBiasControlVoltageVec[i]-R[g]*v[i]*1e-6)*1e-6;
975 }
976
977 // Divide by number of summed channels, convert to mW
978 power_apd /= 317e-3; // [mW]
979
980 if (power_tot<1e-3)
981 power_tot = 0;
982 if (power_apd<1e-3)
983 power_apd = 0;
984
985 fBiasControlPowerTot = power_tot;
986
987 // Get the maximum of each patch
988 vector<float> val(320, 0);
989 for (int i=0; i<320; i++)
990 {
991 const int idx = (fPixelMap.hv(i).hw()/9)*2+fPixelMap.hv(i).group();
992 val[idx] = v[i];
993 }
994
995 // Write the 160 patch values to a file
996 WriteBinary(d, "biascontrol-current", val, 100);
997
998 const Statistics stat(v, 0, 3);
999
1000 // Exclude the three crazy channels
1001 fBiasControlCurrentMed = stat.med;
1002 fBiasControlCurrentMax = stat.max;
1003
1004 // Store a history of the last 60 entries
1005 fBiasControlCurrentHist.push_back(fBiasControlCurrentMed);
1006 if (fBiasControlCurrentHist.size()>360)
1007 fBiasControlCurrentHist.pop_front();
1008
1009 // write the history to a file
1010 WriteBinary(d, "biascontrol-current-hist", fBiasControlCurrentHist, 100);
1011
1012 const string col0 = cal ? HTML::kGreen : HTML::kWhite;
1013
1014 string col1 = col0;
1015 string col2 = col0;
1016 string col3 = col0;
1017 string col4 = col0;
1018
1019 if (cal && stat.min>65)
1020 col1 = kYellow;
1021 if (cal && stat.min>80)
1022 col1 = kRed;
1023
1024 if (cal && stat.med>65)
1025 col2 = kYellow;
1026 if (cal && stat.med>80)
1027 col2 = kRed;
1028
1029 if (cal && stat.avg>65)
1030 col3 = kYellow;
1031 if (cal && stat.avg>80)
1032 col3 = kRed;
1033
1034 if (cal && stat.max>65)
1035 col4 = kYellow;
1036 if (cal && stat.max>80)
1037 col4 = kRed;
1038
1039 ostringstream out;
1040 out << setprecision(2);
1041 out << d.GetJavaDate() << '\n';
1042 out << col0 << '\t' << (cal?"yes":"no") << '\n';
1043 out << col1 << '\t' << stat.min << '\n';
1044 out << col2 << '\t' << stat.med << '\n';
1045 out << col3 << '\t' << stat.avg << '\n';
1046 out << col4 << '\t' << stat.max << '\n';
1047 out << HTML::kWhite << '\t' << power_tot << "W [" << power_apd << "mW]\n";
1048 ofstream(fPath+"/current.data") << out.str();
1049
1050 return GetCurrentState();
1051 }
1052
1053 int HandleFadEvents(const EventImp &d)
1054 {
1055 if (!CheckDataSize(d, "FadControl:Events", 4*4))
1056 {
1057 fFadControlNumEvents = -1;
1058 return GetCurrentState();
1059 }
1060
1061 fFadControlNumEvents = d.Get<uint32_t>();
1062
1063 return GetCurrentState();
1064 }
1065
1066 int HandleFadDrsRuns(const EventImp &d)
1067 {
1068 if (!CheckDataSize(d, "FadControl:DrsRuns", 4*4))
1069 {
1070 fFadControlDrsStep = -1;
1071 return GetCurrentState();
1072 }
1073
1074 const uint32_t *ptr = d.Ptr<uint32_t>();
1075 fFadControlDrsStep = ptr[0];
1076 fFadControlDrsRuns[0] = ptr[1];
1077 fFadControlDrsRuns[1] = ptr[2];
1078 fFadControlDrsRuns[2] = ptr[3];
1079
1080 return GetCurrentState();
1081 }
1082
1083 int HandleFadConnections(const EventImp &d)
1084 {
1085 if (!CheckDataSize(d, "FadControl:Connections", 41))
1086 {
1087 //fStatusEventBuilderLabel->setText("Offline");
1088 return GetCurrentState();
1089 }
1090
1091 string rc(40, '-'); // orange/red [45]
1092
1093 const uint8_t *ptr = d.Ptr<uint8_t>();
1094
1095 int c[4] = { '.', '.', '.', '.' };
1096
1097 for (int i=0; i<40; i++)
1098 {
1099 const uint8_t stat1 = ptr[i]&3;
1100 const uint8_t stat2 = ptr[i]>>3;
1101
1102 if (stat1==0 && stat2==0)
1103 rc[i] = '.'; // gray [46]
1104 else
1105 if (stat1>=2 && stat2==8)
1106 rc[i] = stat1==2?'+':'*'; // green [43] : check [42]
1107
1108 if (rc[i]<c[i/10])
1109 c[i/10] = rc[i];
1110 }
1111
1112 string col[4];
1113 for (int i=0; i<4; i++)
1114 switch (c[i])
1115 {
1116 case '.': col[i]=HTML::kWhite; break;
1117 case '-': col[i]=HTML::kRed; break;
1118 case '+': col[i]=HTML::kYellow; break;
1119 case '*': col[i]=HTML::kGreen; break;
1120 }
1121
1122 ostringstream out;
1123 out << setprecision(3);
1124 out << d.GetJavaDate() << '\n';
1125 out << col[0] << '\t' << rc.substr( 0, 10) << '\n';
1126 out << col[1] << '\t' << rc.substr(10, 10) << '\n';
1127 out << col[2] << '\t' << rc.substr(20, 10) << '\n';
1128 out << col[3] << '\t' << rc.substr(30, 10) << '\n';
1129 ofstream(fPath+"/fad.data") << out.str();
1130
1131 return GetCurrentState();
1132 }
1133
1134 int HandleFtmTriggerRates(const EventImp &d)
1135 {
1136 if (!CheckDataSize(d, "FtmControl:TriggerRates", 24+160+640+8))
1137 return GetCurrentState();
1138
1139 // New run started
1140 if (d.Get<float>(20)<0)
1141 return GetCurrentState();
1142
1143 fFtmControlTriggerRateCam = d.Get<float>(20);
1144
1145 const float *brates = d.Ptr<float>(24); // Board rate
1146 const float *prates = d.Ptr<float>(24+160); // Patch rate
1147
1148 // Store a history of the last 60 entries
1149 fFtmControlTriggerRateHist.push_back(fFtmControlTriggerRateCam);
1150 if (fFtmControlTriggerRateHist.size()>60)
1151 fFtmControlTriggerRateHist.pop_front();
1152
1153 // FIXME: Add statistics for all kind of rates
1154
1155 WriteBinary(d, "ftmcontrol-triggerrate-hist",
1156 fFtmControlTriggerRateHist, 100);
1157 WriteBinary(d, "ftmcontrol-boardrates",
1158 vector<float>(brates, brates+40), 10);
1159 WriteBinary(d, "ftmcontrol-patchrates",
1160 vector<float>(prates, prates+160), 10);
1161
1162 ostringstream out;
1163 out << setprecision(3);
1164 out << d.GetJavaDate() << '\n';
1165 out << HTML::kWhite << '\t' << fFtmControlTriggerRateCam << '\n';
1166
1167 ofstream(fPath+"/trigger.data") << out.str();
1168
1169 const Statistics bstat(vector<float>(brates, brates+40));
1170 const Statistics pstat(vector<float>(prates, prates+160));
1171
1172 out.str("");
1173 out << d.GetJavaDate() << '\n';
1174 out << HTML::kWhite << '\t' << bstat.min << '\n';
1175 out << HTML::kWhite << '\t' << bstat.med << '\n';
1176 out << HTML::kWhite << '\t' << bstat.avg << '\n';
1177 out << HTML::kWhite << '\t' << bstat.max << '\n';
1178 ofstream(fPath+"/boardrates.data") << out.str();
1179
1180 out.str("");
1181 out << d.GetJavaDate() << '\n';
1182 out << HTML::kWhite << '\t' << pstat.min << '\n';
1183 out << HTML::kWhite << '\t' << pstat.med << '\n';
1184 out << HTML::kWhite << '\t' << pstat.avg << '\n';
1185 out << HTML::kWhite << '\t' << pstat.max << '\n';
1186 ofstream(fPath+"/patchrates.data") << out.str();
1187
1188 return GetCurrentState();
1189 }
1190
1191 int HandleFtmStaticData(const EventImp &d)
1192 {
1193 if (!CheckDataSize(d, "FtmControl:StaticData", sizeof(FTM::DimStaticData)))
1194 return GetCurrentState();
1195
1196 const FTM::DimStaticData &dat = d.Ref<FTM::DimStaticData>();
1197
1198 vector<uint16_t> vecp(dat.fThreshold, dat.fThreshold+160);
1199 vector<uint16_t> vecb(dat.fMultiplicity, dat.fMultiplicity+40);
1200
1201 WriteBinary(d, "ftmcontrol-thresholds-patch", vecp, 1000);
1202 WriteBinary(d, "ftmcontrol-thresholds-board", vecb, 1000);
1203
1204 const Statistics statp(vecp);
1205 const Statistics statb(vecb);
1206
1207 fFtmPatchThresholdMed = statp.med;
1208 fFtmBoardThresholdMed = statb.med;
1209
1210 ostringstream out;
1211 out << d.GetJavaDate() << '\n';
1212 out << HTML::kWhite << '\t' << statb.min << '\n';
1213 out << HTML::kWhite << '\t' << statb.med << '\n';
1214 //out << HTML::kWhite << '\t' << statb.avg << '\n';
1215 out << HTML::kWhite << '\t' << statb.max << '\n';
1216 out << HTML::kWhite << '\t' << statp.min << '\n';
1217 out << HTML::kWhite << '\t' << statp.med << '\n';
1218 //out << HTML::kWhite << '\t' << statp.avg << '\n';
1219 out << HTML::kWhite << '\t' << statp.max << '\n';
1220 ofstream(fPath+"/thresholds.data") << out.str();
1221
1222 out.str("");
1223 out << d.GetJavaDate() << '\n';
1224 out << HTML::kWhite << '\t' << dat.fTriggerInterval << '\n';
1225 out << HTML::kWhite << '\t';
1226 if (dat.HasPedestal())
1227 out << dat.fTriggerSeqPed;
1228 else
1229 out << "&ndash;";
1230 out << ':';
1231 if (dat.HasLPext())
1232 out << dat.fTriggerSeqLPext;
1233 else
1234 out << "&ndash;";
1235 out << ':';
1236 if (dat.HasLPint())
1237 out << dat.fTriggerSeqLPint;
1238 else
1239 out << "&ndash;";
1240 out << '\n';
1241
1242 out << HTML::kWhite << '\t' << (dat.HasTrigger()?"on":"off") << " / " << (dat.HasExt1()?"on":"off") << " / " << (dat.HasExt2()?"on":"off") << '\n';
1243 out << HTML::kWhite << '\t' << (dat.HasVeto()?"on":"off") << " / " << (dat.HasClockConditioner()?"time cal":"marker") << '\n';
1244 out << HTML::kWhite << '\t' << dat.fMultiplicityPhysics << " / " << dat.fMultiplicityCalib << '\n';
1245 out << HTML::kWhite << '\t' << dat.fWindowPhysics << '\t' << dat.fWindowCalib << '\n';
1246 out << HTML::kWhite << '\t' << dat.fDelayTrigger << '\t' << dat.fDelayTimeMarker << '\n';
1247 out << HTML::kWhite << '\t' << dat.fDeadTime << '\n';
1248
1249 int64_t vp = dat.fPrescaling[0];
1250 for (int i=1; i<40; i++)
1251 if (vp!=dat.fPrescaling[i])
1252 vp = -1;
1253
1254 if (vp<0)
1255 out << HTML::kYellow << "\tdifferent\n";
1256 else
1257 out << HTML::kWhite << '\t' << 0.5*vp << "\n";
1258
1259 ofstream(fPath+"/ftm.data") << out.str();
1260
1261 // Active FTUs: IsActive(i)
1262 // Enabled Pix: IsEnabled(i)
1263
1264 return GetCurrentState();
1265 }
1266
1267 int HandleFtmFtuList(const EventImp &d)
1268 {
1269 if (!CheckDataSize(d, "FtmControl:FtuList", sizeof(FTM::DimFtuList)))
1270 return GetCurrentState();
1271
1272 const FTM::DimFtuList &sdata = d.Ref<FTM::DimFtuList>();
1273
1274 ostringstream out;
1275 out << d.GetJavaDate() << '\n';
1276
1277 int cnt = 0;
1278 for (int i=0; i<4; i++)
1279 {
1280 out << HTML::kWhite << '\t';
1281 for (int j=0; j<10; j++)
1282 if (sdata.IsActive(i*10+j))
1283 {
1284 if (sdata.fPing[i*10+j]==1)
1285 {
1286 out << '*';
1287 cnt++;
1288 }
1289 else
1290 out << sdata.fPing[i*10+j];
1291 }
1292 else
1293 out << '-';
1294 out << '\n';
1295 }
1296
1297 fFtmControlFtuOk = cnt==40;
1298
1299 ofstream(fPath+"/ftu.data") << out.str();
1300
1301 return GetCurrentState();
1302 }
1303
1304 int HandleFadEventData(const EventImp &d)
1305 {
1306 if (!CheckDataSize(d, "FadControl:EventData", 23040))
1307 return GetCurrentState();
1308
1309 //const float *avg = d.Ptr<float>();
1310 //const float *rms = d.Ptr<float>(1440*sizeof(float));
1311 const float *dat = d.Ptr<float>(1440*sizeof(float)*2);
1312 //const float *pos = d.Ptr<float>(1440*sizeof(float)*3);
1313
1314 vector<float> max(320, -2);
1315 for (int i=0; i<1440; i++)
1316 {
1317 if (i%9==8)
1318 continue;
1319
1320 const int idx = (fPixelMap.hw(i).hw()/9)*2+fPixelMap.hw(i).group();
1321 const double v = dat[i]/1000;
1322 if (v>max[idx])
1323 max[idx]=v;
1324 }
1325
1326 switch (d.GetQoS())
1327 {
1328 case 0: WriteBinary(d, "fadcontrol-eventdata", max, 2, -1); break;
1329 case 1: WriteBinary(d, "fadcontrol-eventdata", max, 2, 0); break;
1330 default: WriteBinary(d, "fadcontrol-eventdata", max, 0.25, 0); break;
1331 }
1332
1333 return GetCurrentState();
1334 }
1335
1336 int HandleFscTemperature(const EventImp &d)
1337 {
1338 if (!CheckDataSize(d, "FscControl:Temperature", 240))
1339 return GetCurrentState();
1340
1341 const float *ptr = d.Ptr<float>(4);
1342
1343 double avg = 0;
1344 double rms = 0;
1345 double min = 99;
1346 double max = -99;
1347
1348 int num = 0;
1349 for (const float *t=ptr; t<ptr+31; t++)
1350 {
1351 if (*t==0)
1352 continue;
1353
1354 if (*t>max)
1355 max = *t;
1356
1357 if (*t<min)
1358 min = *t;
1359
1360 avg += *t;
1361 rms += *t * *t;
1362
1363 num++;
1364 }
1365
1366 avg /= num;
1367 rms = sqrt(rms/num-avg*avg);
1368
1369 if (fMagicWeatherHist[kTemp].size()>0)
1370 {
1371 fFscControlTemperatureHist.push_back(avg-fMagicWeatherHist[kTemp].back());
1372 if (fFscControlTemperatureHist.size()>300)
1373 fFscControlTemperatureHist.pop_front();
1374 }
1375
1376 const Statistics stat(fFscControlTemperatureHist);
1377
1378 ostringstream out;
1379 out << setprecision(3);
1380 out << d.GetJavaDate() << '\n';
1381 out << HTML::kWhite << '\t' << fFscControlHumidityAvg << '\n';
1382 out << HTML::kWhite << '\t' << min << '\n';
1383 out << HTML::kWhite << '\t' << avg << '\n';
1384 out << HTML::kWhite << '\t' << max << '\n';
1385 out << HTML::kWhite << '\t' << stat.min << '\n';
1386 out << HTML::kWhite << '\t' << stat.avg << '\n';
1387 out << HTML::kWhite << '\t' << stat.max << '\n';
1388
1389 ofstream(fPath+"/fsc.data") << out.str();
1390
1391 WriteBinary(d, "fsccontrol-temperature-hist",
1392 fFscControlTemperatureHist, 10);
1393
1394 return GetCurrentState();
1395 }
1396
1397 int HandleFscHumidity(const EventImp &d)
1398 {
1399 if (!CheckDataSize(d, "FscControl:Humidity", 5*4))
1400 return GetCurrentState();
1401
1402 const float *ptr = d.Ptr<float>(4);
1403
1404 double avg = 0;
1405 int num = 0;
1406
1407 for (const float *t=ptr; t<ptr+4; t++)
1408 if (*t>0)
1409 {
1410 avg += *t;
1411 num++;
1412 }
1413
1414 fFscControlHumidityAvg = avg/num;
1415
1416 return GetCurrentState();
1417 }
1418
1419 int HandleRateScanData(const EventImp &d)
1420 {
1421 if (!CheckDataSize(d, "RateScan:Data", 824))
1422 return GetCurrentState();
1423
1424 const uint64_t id = d.Get<uint64_t>();
1425 const float *rate = d.Ptr<float>(20);
1426
1427 if (fRateScanDataId!=id)
1428 {
1429 for (int i=0; i<41; i++)
1430 fRateScanDataHist[i].clear();
1431 fRateScanDataId = id;
1432 }
1433 fRateScanDataHist[0].push_back(log10(rate[0]));
1434
1435 double max = 0;
1436 for (int i=1; i<41; i++)
1437 {
1438 fRateScanDataHist[i].push_back(log10(rate[i]));
1439 if (rate[i]>max)
1440 max = rate[i];
1441 }
1442
1443 // Cycle by time!
1444 fRateScanBoard ++;
1445 fRateScanBoard %= 40;
1446
1447 WriteBinary(d, "ratescan-hist", fRateScanDataHist[0], 10, -2);
1448 WriteBinary(d, "ratescan-board", fRateScanDataHist[fRateScanBoard+1], 10, -4);
1449
1450 ostringstream out;
1451 out << setprecision(3);
1452 out << d.GetJavaDate() << '\n';
1453 out << HTML::kWhite << '\t' << fFtmBoardThresholdMed << '\n';
1454 out << HTML::kWhite << '\t' << fFtmPatchThresholdMed << '\n';
1455 out << HTML::kWhite << '\t' << pow(10, fRateScanDataHist[0].back()) << '\n';
1456 out << HTML::kWhite << '\t' << max << '\n';
1457
1458 ofstream(fPath+"/ratescan.data") << out.str();
1459
1460 out.str("");
1461 out << d.GetJavaDate() << '\n';
1462 out << HTML::kWhite << '\t' << int(fRateScanBoard) << '\n';
1463 out << HTML::kWhite << '\t' << pow(10, fRateScanDataHist[fRateScanBoard+1].back()) << '\n';
1464
1465 ofstream(fPath+"/ratescan_board.data") << out.str();
1466
1467 return GetCurrentState();
1468 }
1469
1470 // -------------------------------------------------------------------
1471
1472 void HandleDoTest(const EventImp &d)
1473 {
1474 ostringstream out;
1475 out << d.GetJavaDate() << '\n';
1476
1477 switch (d.GetQoS())
1478 {
1479 case -3: out << HTML::kWhite << "\tNot running\n"; break;
1480 case -2: out << HTML::kBlue << "\tLoading\n"; break;
1481 case -1: out << HTML::kBlue << "\tStarted\n"; break;
1482 default: out << HTML::kGreen << "\tRunning [" << d.GetQoS() << "]\n"; break;
1483 }
1484
1485 ofstream(fPath+"/dotest.data") << out.str();
1486 }
1487
1488 // -------------------------------------------------------------------
1489
1490 /*
1491 bool CheckEventSize(size_t has, const char *name, size_t size)
1492 {
1493 if (has==size)
1494 return true;
1495
1496 ostringstream msg;
1497 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
1498 Fatal(msg);
1499 return false;
1500 }*/
1501
1502 int Print() const
1503 {
1504 Out() << fDimDNS << endl;
1505 Out() << fDimMcp << endl;
1506 Out() << fDimControl << endl;
1507 Out() << fDimDataLogger << endl;
1508 Out() << fDimDriveControl << endl;
1509 Out() << fDimFadControl << endl;
1510 Out() << fDimFtmControl << endl;
1511 Out() << fDimBiasControl << endl;
1512 Out() << fDimFeedback << endl;
1513 Out() << fDimRateControl << endl;
1514 Out() << fDimFscControl << endl;
1515 Out() << fDimMagicWeather << endl;
1516 Out() << fDimTngWeather << endl;
1517 Out() << fDimRateScan << endl;
1518 Out() << fDimChatServer << endl;
1519
1520 return GetCurrentState();
1521 }
1522
1523 string GetStateHtml(const DimState &state, int green) const
1524 {
1525 if (!state.online())
1526 return HTML::kWhite+"\t&mdash;\n";
1527
1528 if (&state==&fDimControl)
1529 return HTML::kGreen +'\t'+(state.state()<-2?"Idle":fDimControl.shortmsg)+'\n';
1530
1531 const State rc = state.description();
1532
1533 // Sate not found in list, server online (-3: offline; -2: not found)
1534 if (rc.index==-2)
1535 {
1536 ostringstream out;
1537 out << HTML::kWhite << '\t' << state.state() << '\n';
1538 return out.str();
1539 }
1540
1541 //ostringstream msg;
1542 //msg << HTML::kWhite << '\t' << rc.name << " [" << rc.index << "]\n";
1543 //return msg.str();
1544
1545 if (rc.index<1)
1546 return HTML::kWhite + "\t&mdash;\n";
1547
1548
1549 return (rc.index<green?HTML::kYellow:HTML::kGreen) + '\t' + rc.name + '\n';
1550 }
1551
1552 int Execute()
1553 {
1554 // Dispatch (execute) at most one handler from the queue. In contrary
1555 // to run_one(), it doesn't wait until a handler is available
1556 // which can be dispatched, so poll_one() might return with 0
1557 // handlers dispatched. The handlers are always dispatched/executed
1558 // synchronously, i.e. within the call to poll_one()
1559 //poll_one();
1560
1561 Time now;
1562 if (now-fLastUpdate<boost::posix_time::seconds(1))
1563 return kStateRunning;
1564
1565 fLastUpdate=now;
1566
1567 // ==============================================================
1568
1569 ostringstream msg;
1570
1571 if (fHasError==2)
1572 msg << "SmartFACT backend initializing." << endl;
1573 if (!fDimDNS.online())
1574 msg << "DIM network not available.<br/>";
1575 if (fDimDriveControl.state()>0xff)
1576 msg << "Drive in ERROR state<br/>";
1577 if (fDimBiasControl.state()<BIAS::State::kRamping && (fDimMcp.state()==MCP::State::kTriggerOn || fDimMcp.state()==MCP::State::kTakingData))
1578 msg << "BIAS not operating during data-taking<br/>";
1579 if (fDimBiasControl.state()==BIAS::State::kOverCurrent)
1580 msg << "BIAS channels in OverCurrent<br/>";
1581 if (fDimBiasControl.state()==BIAS::State::kNotReferenced)
1582 msg << "BIAS voltage not at reference<br/>";
1583 if (fFeedbackCalibration.size()>0)
1584 {
1585 if (fBiasControlCurrentMed>75)
1586 msg << "Median current exceeds 75&micro;A/pix<br/>";
1587 if (fBiasControlCurrentMax>90)
1588 msg << "Maximum current exceeds 90&micro;A/pix<br/>";
1589 }
1590 if (fMagicWeatherHist[kHum].size()>0 && fMagicWeatherHist[kHum].back()>98 && (fDimMcp.state()==MCP::State::kTriggerOn || fDimMcp.state()==MCP::State::kTakingData))
1591 msg << "Outside humidity exceeds 98% during data-taking<br/>";
1592 if (fMagicWeatherHist[kGusts].size()>0 && fMagicWeatherHist[kGusts].back()>98 && fDimDriveControl.state()==Drive::State::kTracking)
1593 msg << "Wind gusts exceed 50km/h during tracking<br/>";
1594 if (fFscControlTemperatureHist.size()>0 && fFscControlTemperatureHist.back()>7)
1595 msg << "Sensor temperature exceeds outside temperature by more than 7&deg;C<br/>";
1596 if (fFtmControlTriggerRateCam<0.01 && (fDimMcp.state()==MCP::State::kTriggerOn || fDimMcp.state()==MCP::State::kTakingData))
1597 msg << "Trigger rate below 10mHz during data taking<br/>";
1598 if (fFscControlHumidityAvg>60)
1599 msg << "Average camera humidity exceed 60%<br/>";
1600 if (!fDimControl.online())
1601 msg << "dimctrl offline<br/>";
1602
1603 if (fDriveControlMoonDist>155)
1604 msg << "Moon within the field-of-view of the cones<br/>";
1605 if (fDriveControlMoonDist>=0 && fDriveControlMoonDist<3)
1606 msg << "Moon within the field-of-view of the camera<br/>";
1607
1608
1609 if (!fDimFeedback.state()==Feedback::State::kCalibrating &&
1610 fDimBiasControl.state()==BIAS::State::kVoltageOn &&
1611 fBiasControlVoltageMed>3 &&
1612 fFeedbackCalibration.size()==0)
1613 msg << "bias voltage switched on, but bias crate not calibrated.";
1614
1615 // FTM in Connected instead of Idle --> power cyclen
1616
1617 /* // Check offline and disconnected status?
1618 Out() << fDimMcp << endl;
1619 Out() << fDimControl << endl;
1620 Out() << fDimDataLogger << endl;
1621 Out() << fDimDriveControl << endl;
1622 Out() << fDimFadControl << endl;
1623 Out() << fDimFtmControl << endl;
1624 Out() << fDimBiasControl << endl;
1625 Out() << fDimFeedback << endl;
1626 Out() << fDimRateControl << endl;
1627 Out() << fDimFscControl << endl;
1628 Out() << fDimMagicWeather << endl;
1629 Out() << fDimRateScan << endl;
1630 Out() << fDimChatServer << endl;
1631 */
1632
1633 // FTU in error
1634 // FAD lost
1635
1636 // --------------------------------------------------------------
1637
1638 const bool haserror = msg.str().size()>0;
1639
1640 ostringstream out;
1641 out << now.JavaDate() << '\t' << haserror << '\t' << (fDimControl.state()>-3) << '\n';
1642 out << setprecision(3);
1643 out << HTML::kWhite << '\t' << msg.str() << '\n';
1644
1645 if (haserror || fHasError)
1646 ofstream(fPath+"/error.data") << out.str();
1647
1648 fHasError = haserror;
1649
1650 if (!fDimDNS.online())
1651 return kStateDimNetworkNA;
1652
1653 // ==============================================================
1654
1655 out.str("");
1656 out << now.JavaDate() << '\t' << fHasError << '\t' << (fDimControl.state()>-3) << '\n';
1657 out << setprecision(3);
1658
1659 // -------------- System status --------------
1660 if (fDimMcp.state()>=MCP::State::kIdle) // Idle
1661 {
1662 string col = HTML::kBlue;
1663 if (fMcpConfigurationState!=MCP::State::kIdle && // Idle
1664 fMcpConfigurationState!=MCP::State::kTriggerOn && // Trigger On
1665 fMcpConfigurationState!=MCP::State::kTakingData) // Taking Data
1666 col = HTML::kYellow;
1667 else
1668 if (fDimFadControl.state()==FAD::State::kWritingData)
1669 col = HTML::kGreen;
1670
1671 out << col << '\t';
1672
1673 if (fDimRateControl.state()!=RateControl::State::kSettingGlobalThreshold &&
1674 fDimRateScan.state()!=RateScan::State::kInProgress)
1675 {
1676 switch (fMcpConfigurationState)
1677 {
1678 case MCP::State::kIdle:
1679 out << "Idle [" << fMcpConfigurationName << "]";
1680 break;
1681 case MCP::State::kConfiguring1:
1682 case MCP::State::kConfiguring2:
1683 case MCP::State::kConfiguring3:
1684 out << "Configuring [" << fMcpConfigurationName << "]";
1685 break;
1686 case MCP::State::kConfigured:
1687 out << "Configured [" << fMcpConfigurationName << "]";
1688 break;
1689 case MCP::State::kTriggerOn:
1690 case MCP::State::kTakingData:
1691 out << fMcpConfigurationName;
1692 if (fFadControlDrsRuns[2]>0)
1693 out << "(" << fFadControlDrsRuns[2] << ")";
1694 break;
1695 }
1696 }
1697 else
1698 if (fDimRateControl.state()==RateControl::State::kSettingGlobalThreshold)
1699 out << "Calibrating threshold";
1700 else
1701 if (fDimRateScan.state()==RateScan::State::kInProgress)
1702 out << "Rate scan in progress";
1703
1704 if (fMcpConfigurationState>MCP::State::kConfigured &&
1705 fDimRateControl.state()!=RateControl::State::kSettingGlobalThreshold)
1706 {
1707 ostringstream evt;
1708 if (fMcpConfigurationMaxEvents>0)
1709 {
1710 const int64_t de = int64_t(fMcpConfigurationMaxEvents) - int64_t(fFadControlNumEvents);
1711 if (de>=0 && fMcpConfigurationState==MCP::State::kTakingData)
1712 evt << de;
1713 else
1714 evt << fMcpConfigurationMaxEvents;
1715 }
1716 else
1717 {
1718 if (fMcpConfigurationState==MCP::State::kTakingData)
1719 {
1720 if (fFadControlNumEvents>2999)
1721 evt << floor(fFadControlNumEvents/1000) << 'k';
1722 else
1723 evt << fFadControlNumEvents;
1724 }
1725 }
1726
1727 ostringstream tim;
1728 if (fMcpConfigurationMaxTime>0)
1729 {
1730 const uint32_t dt = (Time()-fMcpConfigurationRunStart).total_seconds();
1731 if (dt<=fMcpConfigurationMaxTime && fMcpConfigurationState==MCP::State::kTakingData)
1732 tim << fMcpConfigurationMaxTime-dt << 's';
1733 else
1734 tim << fMcpConfigurationMaxTime << 's';
1735 }
1736 else
1737 {
1738 if (fMcpConfigurationState==MCP::State::kTakingData)
1739 {
1740 ostringstream d;
1741 d << Time()-fMcpConfigurationRunStart;
1742 tim << d.str().substr(3, 5);
1743 }
1744 }
1745
1746 const bool has_evt = !evt.str().empty();
1747 const bool has_tim = !tim.str().empty();
1748
1749 if (has_evt || has_tim)
1750 out << " [";
1751 out << evt.str();
1752 if (has_evt && has_tim)
1753 out << '/';
1754 out << tim.str();
1755 if (has_evt || has_tim)
1756 out << ']';
1757 }
1758 }
1759 else
1760 out << HTML::kWhite;
1761 out << '\n';
1762
1763 // ------------------ Drive -----------------
1764 if (fDimDriveControl.state()>=Drive::State::kArmed) // Armed, Moving, Tracking
1765 {
1766 const double dev = fDriveControlTrackingDevHist.size()>0 ? fDriveControlTrackingDevHist.back() : 0;
1767 const State rc = fDimDriveControl.description();
1768 string col = HTML::kGreen;
1769 if (rc.index==6) // Moving
1770 col = HTML::kBlue;
1771 if (rc.index==5) // Armed
1772 col = HTML::kWhite;
1773 if (rc.index==7) // Tracking
1774 {
1775 if (dev>60) // ~1.5mm
1776 col = HTML::kYellow;
1777 if (dev>100) // ~1/4 of a pixel ~ 2.5mm
1778 col = HTML::kRed;
1779 }
1780 out << col << '\t';
1781
1782 //out << rc.name << '\t';
1783 out << fDriveControlPointingZd << '\t';
1784 out << setprecision(2);
1785 out << fDriveControlPointingAz << '\t';
1786 if (fDimDriveControl.state()==7)
1787 {
1788 out << fDriveControlSourceName << '\t';
1789 out << dev << '\n';
1790 }
1791 else
1792 out << "\t\n";
1793 out << setprecision(3);
1794 }
1795 else
1796 out << HTML::kWhite << '\n';
1797
1798 // ------------------- FSC ------------------
1799 if (fDimFscControl.state()>FSC::State::kDisconnected && fFscControlTemperatureHist.size()>0)
1800 {
1801 out << HTML::kGreen << '\t' << fFscControlTemperatureHist.back() << '\n';
1802 }
1803 else
1804 out << HTML::kWhite << '\n';
1805
1806 // --------------- MagicWeather -------------
1807 if (fDimMagicWeather.state()==MagicWeather::State::kReceiving && fMagicWeatherHist[kWeatherBegin].size()>0)
1808 {
1809 /*
1810 const float diff = fMagicWeatherHist[kTemp].back()-fMagicWeatherHist[kDew].back();
1811 string col1 = HTML::kRed;
1812 if (diff>0.3)
1813 col1 = HTML::kYellow;
1814 if (diff>0.7)
1815 col1 = HTML::kGreen;
1816 */
1817
1818 const float wind = fMagicWeatherHist[kGusts].back();
1819 const float hum = fMagicWeatherHist[kHum].back();
1820 string col = HTML::kGreen;
1821 if (wind>35 || hum>95)
1822 col = HTML::kYellow;
1823 if (wind>50 || hum>98)
1824 col = HTML::kRed;
1825
1826 out << col << '\t';
1827 out << fMagicWeatherHist[kHum].back() << '\t';
1828 out << setprecision(2);
1829 out << fMagicWeatherHist[kGusts].back() << '\n';
1830 out << setprecision(3);
1831 }
1832 else
1833 out << HTML::kWhite << "\n";
1834
1835 // --------------- FtmControl -------------
1836 if (fDimFtmControl.state()==FTM::State::kTriggerOn)
1837 {
1838 string col = HTML::kGreen;
1839 if (fFtmControlTriggerRateCam<15)
1840 col = HTML::kYellow;
1841 if (fFtmControlTriggerRateCam>100)
1842 col = HTML::kRed;
1843
1844 out << col << '\t' << fFtmControlTriggerRateCam << '\t';
1845 out << fFtmPatchThresholdMed << '\n';
1846 }
1847 else
1848 out << HTML::kWhite << '\n';
1849
1850 // --------------- BiasControl -------------
1851 if (fDimBiasControl.state()==BIAS::State::kRamping ||
1852 fDimBiasControl.state()==BIAS::State::kOverCurrent ||
1853 fDimBiasControl.state()==BIAS::State::kVoltageOn ||
1854 fDimBiasControl.state()==BIAS::State::kVoltageOff)
1855 {
1856 const bool off = fDimBiasControl.state()==BIAS::State::kVoltageOff;
1857 const bool oc = fDimBiasControl.state()==BIAS::State::kOverCurrent;
1858
1859 string col = fBiasControlVoltageMed>3?HTML::kGreen:HTML::kWhite;
1860 if (fBiasControlCurrentMax>65)
1861 col = HTML::kYellow;
1862 if (fBiasControlCurrentMax>80)
1863 col = HTML::kRed;
1864
1865 // Bias in overcurrent => Red
1866 if (fDimBiasControl.state()==BIAS::State::kOverCurrent)
1867 col = HTML::kRed;
1868
1869 // MCP in ReadyForDatataking/Configuring/Configured/TriggerOn/TakingData
1870 // and Bias not in "data-taking state' => Red
1871 if (fMcpConfigurationState>MCP::State::kIdle &&
1872 fDimBiasControl.state()!=BIAS::State::kVoltageOn &&
1873 fDimBiasControl.state()!=BIAS::State::kVoltageOff)
1874 col = HTML::kRed;
1875
1876 const bool cal = fFeedbackCalibration.size();
1877
1878 // Feedback is currently calibrating => Blue
1879 if (fDimFeedback.state()==13)
1880 {
1881 out << HTML::kBlue << '\t';
1882 out << "***\t";
1883 out << "***\t";
1884 }
1885 else
1886 {
1887 out << setprecision(2);
1888 out << col << '\t';
1889 out << (off ? 0 : fBiasControlCurrentMed) << '\t';
1890 if (oc)
1891 out << "(OC) ";
1892 else
1893 {
1894 if (cal)
1895 out << (off ? 0 : fBiasControlCurrentMax);
1896 else
1897 out << "&mdash; ";
1898 }
1899 out << '\t';
1900 out << setprecision(3);
1901 }
1902 if (cal && fDimFeedback.state()!=Feedback::State::kCalibrating)
1903 out << setprecision(2) << fBiasControlPowerTot << " W" << setprecision(3);
1904 else
1905 out << (off ? 0 : fBiasControlVoltageMed);
1906 out << '\n';
1907 }
1908 else
1909 out << HTML::kWhite << '\n';
1910
1911 ofstream(fPath+"/fact.data") << out.str();
1912
1913 // ==============================================================
1914
1915 out.str("");
1916 out << now.JavaDate() << '\t' << fHasError << '\t' << (fDimControl.state()>-3) << '\n';
1917
1918 if (!fDimDNS.online())
1919 out << HTML::kWhite << "\tOffline\n\n\n\n\n\n\n\n\n\n\n\n\n";
1920 else
1921 {
1922 ostringstream dt;
1923 dt << (Time()-fRunTime);
1924
1925 out << HTML::kGreen << '\t' << fDimDNS.version() << '\n';
1926
1927 out << GetStateHtml(fDimControl, 0);
1928 out << GetStateHtml(fDimMcp, 4);
1929 out << GetStateHtml(fDimDataLogger, 1);
1930 out << GetStateHtml(fDimDriveControl, 2);
1931 out << GetStateHtml(fDimFadControl, FAD::State::kConnected);
1932 out << GetStateHtml(fDimFtmControl, FTM::State::kConnected);
1933 out << GetStateHtml(fDimBiasControl, BIAS::State::kConnected);
1934 out << GetStateHtml(fDimFeedback, 4);
1935 out << GetStateHtml(fDimRateControl, 4);
1936 out << GetStateHtml(fDimFscControl, 2);
1937 out << GetStateHtml(fDimMagicWeather, 2);
1938 out << GetStateHtml(fDimTngWeather, 2);
1939 out << GetStateHtml(fDimRateScan, 4);
1940 out << GetStateHtml(fDimChatServer, 1);
1941
1942 out << HTML::kGreen << '\t' << dt.str().substr(0, dt.str().length()-7) << '\n';
1943 }
1944
1945 ofstream(fPath+"/status.data") << out.str();
1946
1947 return kStateRunning;
1948 }
1949
1950
1951public:
1952 StateMachineSmartFACT(ostream &out=cout) : StateMachineDim(out, "SMART_FACT"),
1953 fPath("www/smartfact/data"),
1954 fControlScriptDepth(0),
1955 fMcpConfigurationState(-256),
1956 fMcpConfigurationMaxTime(0),
1957 fMcpConfigurationMaxEvents(0),
1958 fTngWeatherDustTime(Time::none),
1959 fBiasControlVoltageMed(0),
1960 fBiasControlCurrentMed(0),
1961 fBiasControlCurrentMax(0),
1962 fFscControlHumidityAvg(0),
1963 fFtmControlTriggerRateCam(0),
1964 fRateScanDataId(0),
1965 fRateScanBoard(0),
1966 fHasError(2),
1967 // ---
1968 fDimMcp ("MCP"),
1969 fDimDataLogger ("DATA_LOGGER"),
1970 fDimDriveControl("DRIVE_CONTROL"),
1971 fDimMagicWeather("MAGIC_WEATHER"),
1972 fDimTngWeather ("TNG_WEATHER"),
1973 fDimFeedback ("FEEDBACK"),
1974 fDimBiasControl ("BIAS_CONTROL"),
1975 fDimFtmControl ("FTM_CONTROL"),
1976 fDimFadControl ("FAD_CONTROL"),
1977 fDimFscControl ("FSC_CONTROL"),
1978 fDimRateControl ("RATE_CONTROL"),
1979 fDimRateScan ("RATE_SCAN"),
1980 fDimChatServer ("CHAT_SERVER")
1981 {
1982 fDimDNS.Subscribe(*this);
1983 fDimControl.Subscribe(*this);
1984 fDimMcp.Subscribe(*this);
1985 fDimDataLogger.Subscribe(*this);
1986 fDimDriveControl.Subscribe(*this);
1987 fDimMagicWeather.Subscribe(*this);
1988 fDimTngWeather.Subscribe(*this);
1989 fDimFeedback.Subscribe(*this);
1990 fDimBiasControl.Subscribe(*this);
1991 fDimFtmControl.Subscribe(*this);
1992 fDimFadControl.Subscribe(*this);
1993 fDimFscControl.Subscribe(*this);
1994 fDimRateControl.Subscribe(*this);
1995 fDimRateScan.Subscribe(*this);
1996 fDimChatServer.Subscribe(*this);
1997
1998 fDimControl.SetCallback(bind(&StateMachineSmartFACT::HandleControlStateChange, this, placeholders::_1));
1999 fDimControl.AddCallback("dotest.dim", bind(&StateMachineSmartFACT::HandleDoTest, this, placeholders::_1));
2000
2001 Subscribe("DIM_CONTROL/MESSAGE")
2002 (bind(&StateMachineSmartFACT::HandleDimControlMessage, this, placeholders::_1));
2003
2004 Subscribe("MCP/CONFIGURATION")
2005 (bind(&StateMachineSmartFACT::HandleMcpConfiguration, this, placeholders::_1));
2006
2007 Subscribe("DRIVE_CONTROL/POINTING_POSITION")
2008 (bind(&StateMachineSmartFACT::HandleDrivePointing, this, placeholders::_1));
2009 Subscribe("DRIVE_CONTROL/TRACKING_POSITION")
2010 (bind(&StateMachineSmartFACT::HandleDriveTracking, this, placeholders::_1));
2011 Subscribe("DRIVE_CONTROL/SOURCE_POSITION")
2012 (bind(&StateMachineSmartFACT::HandleDriveSource, this, placeholders::_1));
2013
2014 Subscribe("FSC_CONTROL/TEMPERATURE")
2015 (bind(&StateMachineSmartFACT::HandleFscTemperature, this, placeholders::_1));
2016 Subscribe("FSC_CONTROL/HUMIDITY")
2017 (bind(&StateMachineSmartFACT::HandleFscHumidity, this, placeholders::_1));
2018
2019 Subscribe("MAGIC_WEATHER/DATA")
2020 (bind(&StateMachineSmartFACT::HandleMagicWeatherData, this, placeholders::_1));
2021 Subscribe("TNG_WEATHER/DUST")
2022 (bind(&StateMachineSmartFACT::HandleTngWeatherDust, this, placeholders::_1));
2023
2024 Subscribe("FEEDBACK/DEVIATION")
2025 (bind(&StateMachineSmartFACT::HandleFeedbackDeviation, this, placeholders::_1));
2026 Subscribe("FEEDBACK/CALIBRATION")
2027 (bind(&StateMachineSmartFACT::HandleFeedbackCalibration, this, placeholders::_1));
2028
2029 Subscribe("BIAS_CONTROL/VOLTAGE")
2030 (bind(&StateMachineSmartFACT::HandleBiasVoltage, this, placeholders::_1));
2031 Subscribe("BIAS_CONTROL/CURRENT")
2032 (bind(&StateMachineSmartFACT::HandleBiasCurrent, this, placeholders::_1));
2033
2034 Subscribe("FAD_CONTROL/CONNECTIONS")
2035 (bind(&StateMachineSmartFACT::HandleFadConnections, this, placeholders::_1));
2036 Subscribe("FAD_CONTROL/EVENTS")
2037 (bind(&StateMachineSmartFACT::HandleFadEvents, this, placeholders::_1));
2038 Subscribe("FAD_CONTROL/DRS_RUNS")
2039 (bind(&StateMachineSmartFACT::HandleFadDrsRuns, this, placeholders::_1));
2040
2041 Subscribe("FTM_CONTROL/TRIGGER_RATES")
2042 (bind(&StateMachineSmartFACT::HandleFtmTriggerRates, this, placeholders::_1));
2043 Subscribe("FTM_CONTROL/STATIC_DATA")
2044 (bind(&StateMachineSmartFACT::HandleFtmStaticData, this, placeholders::_1));
2045 Subscribe("FTM_CONTROL/FTU_LIST")
2046 (bind(&StateMachineSmartFACT::HandleFtmFtuList, this, placeholders::_1));
2047
2048 Subscribe("RATE_SCAN/DATA")
2049 (bind(&StateMachineSmartFACT::HandleRateScanData, this, placeholders::_1));
2050
2051 Subscribe("FAD_CONTROL/EVENT_DATA")
2052 (bind(&StateMachineSmartFACT::HandleFadEventData, this, placeholders::_1));
2053
2054 // =================================================================
2055
2056 // State names
2057 AddStateName(kStateDimNetworkNA, "DimNetworkNotAvailable",
2058 "The Dim DNS is not reachable.");
2059
2060 AddStateName(kStateRunning, "Running", "");
2061
2062 // =================================================================
2063
2064 AddEvent("PRINT")
2065 (bind(&StateMachineSmartFACT::Print, this))
2066 ("Print a list of the states of all connected servers.");
2067
2068 }
2069 int EvalOptions(Configuration &conf)
2070 {
2071 if (!fPixelMap.Read(conf.Get<string>("pixel-map-file")))
2072 {
2073 Error("Reading mapping table from "+conf.Get<string>("pixel-map-file")+" failed.");
2074 return 1;
2075 }
2076
2077 fPath = conf.Get<string>("path");
2078
2079 return -1;
2080 }
2081};
2082
2083// ------------------------------------------------------------------------
2084
2085#include "Main.h"
2086
2087template<class T>
2088int RunShell(Configuration &conf)
2089{
2090 return Main::execute<T, StateMachineSmartFACT>(conf);
2091}
2092
2093void SetupConfiguration(Configuration &conf)
2094{
2095 po::options_description control("Smart FACT");
2096 control.add_options()
2097 ("pixel-map-file", var<string>("FACTmapV5a.txt"), "Pixel mapping file. Used here to get the default reference voltage")
2098 ("path", var<string>("www/smartfact/data"), "Output path for the data-files")
2099 ;
2100
2101 conf.AddOptions(control);
2102}
2103
2104/*
2105 Extract usage clause(s) [if any] for SYNOPSIS.
2106 Translators: "Usage" and "or" here are patterns (regular expressions) which
2107 are used to match the usage synopsis in program output. An example from cp
2108 (GNU coreutils) which contains both strings:
2109 Usage: cp [OPTION]... [-T] SOURCE DEST
2110 or: cp [OPTION]... SOURCE... DIRECTORY
2111 or: cp [OPTION]... -t DIRECTORY SOURCE...
2112 */
2113void PrintUsage()
2114{
2115 cout <<
2116 "SmartFACT is a tool writing the files needed for the SmartFACT web interface.\n"
2117 "\n"
2118 "The default is that the program is started without user intercation. "
2119 "All actions are supposed to arrive as DimCommands. Using the -c "
2120 "option, a local shell can be initialized. With h or help a short "
2121 "help message about the usuage can be brought to the screen.\n"
2122 "\n"
2123 "Usage: smartfact [-c type] [OPTIONS]\n"
2124 " or: smartfact [OPTIONS]\n";
2125 cout << endl;
2126}
2127
2128void PrintHelp()
2129{
2130 Main::PrintHelp<StateMachineSmartFACT>();
2131
2132 /* Additional help text which is printed after the configuration
2133 options goes here */
2134
2135 /*
2136 cout << "bla bla bla" << endl << endl;
2137 cout << endl;
2138 cout << "Environment:" << endl;
2139 cout << "environment" << endl;
2140 cout << endl;
2141 cout << "Examples:" << endl;
2142 cout << "test exam" << endl;
2143 cout << endl;
2144 cout << "Files:" << endl;
2145 cout << "files" << endl;
2146 cout << endl;
2147 */
2148}
2149
2150int main(int argc, const char* argv[])
2151{
2152 Configuration conf(argv[0]);
2153 conf.SetPrintUsage(PrintUsage);
2154 Main::SetupConfiguration(conf);
2155 SetupConfiguration(conf);
2156
2157 if (!conf.DoParse(argc, argv, PrintHelp))
2158 return -1;
2159
2160 if (!conf.Has("console"))
2161 return RunShell<LocalStream>(conf);
2162
2163 if (conf.Get<int>("console")==0)
2164 return RunShell<LocalShell>(conf);
2165 else
2166 return RunShell<LocalConsole>(conf);
2167
2168 return 0;
2169}
Note: See TracBrowser for help on using the repository browser.