source: trunk/FACT++/src/ratecontrol.cc@ 16448

Last change on this file since 16448 was 16445, checked in by tbretz, 13 years ago
Added time to output; Require the physics trigger be enables and switched on to go to InProgress; leave InProgress if one of the two conditions is not fullfilled anymore; print a message when stop was received.
File size: 30.1 KB
Line 
1#include <valarray>
2
3#include "Dim.h"
4#include "Event.h"
5#include "Shell.h"
6#include "StateMachineDim.h"
7#include "Connection.h"
8#include "Configuration.h"
9#include "Console.h"
10#include "externals/PixelMap.h"
11
12#include "tools.h"
13
14#include "LocalControl.h"
15
16#include "HeadersFTM.h"
17#include "HeadersDrive.h"
18#include "HeadersRateScan.h"
19#include "HeadersRateControl.h"
20
21namespace ba = boost::asio;
22namespace bs = boost::system;
23namespace dummy = ba::placeholders;
24
25using namespace std;
26
27// ------------------------------------------------------------------------
28
29#include "DimDescriptionService.h"
30#include "DimState.h"
31
32// ------------------------------------------------------------------------
33
34class StateMachineRateControl : public StateMachineDim//, public DimInfoHandler
35{
36private:
37 struct config
38 {
39 uint16_t fCalibrationType;
40 uint16_t fTargetRate;
41 uint16_t fMinThreshold;
42 uint16_t fAverageTime;
43 uint16_t fRequiredEvents;
44 };
45
46 map<string, config> fRunTypes;
47
48 PixelMap fMap;
49
50 bool fPhysTriggerEnabled;
51 bool fTriggerOn;
52
53 vector<bool> fBlock;
54
55 DimVersion fDim;
56 DimDescribedState fDimFTM;
57 DimDescribedState fDimRS;
58 DimDescribedState fDimDrive;
59
60 DimDescribedService fDimThreshold;
61
62 float fTargetRate;
63 float fTriggerRate;
64
65 uint16_t fThresholdMin;
66 uint16_t fThresholdReference;
67
68 uint16_t fAverageTime;
69 uint16_t fRequiredEvents;
70
71 list<pair<Time,float>> fCurrentsMed;
72 list<pair<Time,float>> fCurrentsDev;
73 list<pair<Time,vector<float>>> fCurrentsVec;
74
75 bool fVerbose;
76 bool fCalibrateByCurrent;
77
78 uint64_t fCounter;
79
80 Time fCalibrationTimeStart;
81
82 bool CheckEventSize(const EventImp &evt, size_t size)
83 {
84 if (size_t(evt.GetSize())==size)
85 return true;
86
87 if (evt.GetSize()==0)
88 return false;
89
90 ostringstream msg;
91 msg << evt.GetName() << " - Received event has " << evt.GetSize() << " bytes, but expected " << size << ".";
92 Fatal(msg);
93 return false;
94 }
95
96 vector<uint16_t> fThresholds;
97
98 void PrintThresholds(const FTM::DimStaticData &sdata)
99 {
100 //if (!fVerbose)
101 // return;
102
103 if (fThresholds.empty())
104 return;
105
106 Out() << "Min. DAC=" << fThresholdMin << endl;
107
108 int t=0;
109 for (t=0; t<160; t++)
110 if (sdata.fThreshold[t]!=fThresholds[t])
111 break;
112
113 if (t==160)
114 return;
115
116 for (int j=0; j<10; j++)
117 {
118 for (int k=0; k<4; k++)
119 {
120 for (int i=0; i<4; i++)
121 if (fThresholds[i+k*4+j*16]!=fThresholdMin)
122 Out() << setw(3) << fThresholds[i+k*4+j*16] << " ";
123 else
124 Out() << " - ";
125 Out() << " ";
126 }
127 Out() << endl;
128 }
129 Out() << endl;
130 }
131
132 void Step(int idx, float step)
133 {
134 uint16_t diff = fThresholds[idx]+int16_t(truncf(step));
135 if (diff<fThresholdMin)
136 diff=fThresholdMin;
137
138 if (diff==fThresholds[idx])
139 return;
140
141 if (fVerbose)
142 {
143 Out() << idx/40 << "|" << (idx/4)%10 << "|" << idx%4;
144 Out() << (step>0 ? " += " : " -= ");
145 Out() << fabs(step) << " (" << diff << ")" << endl;
146 }
147
148 const uint32_t val[2] = { idx, diff };
149 DimClient::sendCommandNB("FTM_CONTROL/SET_THRESHOLD", (void*)val, 8);
150
151 fBlock[idx/4] = true;
152 }
153
154 void ProcessPatches(const FTM::DimTriggerRates &sdata)
155 {
156
157 // Caluclate Median and deviation
158 vector<float> medb(sdata.fBoardRate, sdata.fBoardRate+40);
159 vector<float> medp(sdata.fPatchRate, sdata.fPatchRate+160);
160
161 sort(medb.begin(), medb.end());
162 sort(medp.begin(), medp.end());
163
164 vector<float> devb(40);
165 for (int i=0; i<40; i++)
166 devb[i] = fabs(sdata.fBoardRate[i]-medb[i]);
167
168 vector<float> devp(160);
169 for (int i=0; i<160; i++)
170 devp[i] = fabs(sdata.fPatchRate[i]-medp[i]);
171
172 sort(devb.begin(), devb.end());
173 sort(devp.begin(), devp.end());
174
175 double mb = (medb[19]+medb[20])/2;
176 double mp = (medp[79]+medp[80])/2;
177
178 double db = devb[27];
179 double dp = devp[109];
180
181 // If any is zero there is something wrong
182 if (mb==0 || mp==0 || db==0 || dp==0)
183 return;
184
185 if (fVerbose)
186 Out() << Tools::Form("Board: Med=%3.1f +- %3.1f Patch: Med=%3.1f +- %3.1f", mb, db, mp, dp) << endl;
187
188 for (int i=0; i<40; i++)
189 {
190 if (fBlock[i])
191 {
192 fBlock[i] = false;
193 continue;
194 }
195
196 int maxi = -1;
197
198 const float dif = fabs(sdata.fBoardRate[i]-mb)/db;
199 if (dif>3)
200 {
201 if (fVerbose)
202 Out() << "B" << i << ": " << dif << endl;
203
204 float max = sdata.fPatchRate[i*4];
205 maxi = 0;
206
207 for (int j=1; j<4; j++)
208 if (sdata.fPatchRate[i*4+j]>max)
209 {
210 max = sdata.fPatchRate[i*4+j];
211 maxi = j;
212 }
213 }
214
215 for (int j=0; j<4; j++)
216 {
217 // For the noise pixel correct down to median+3*deviation
218 if (maxi==j)
219 {
220 // This is the step which has to be performed to go from
221 // a NSB rate of sdata.fPatchRate[i*4+j]
222
223
224 const float step = (log10(sdata.fPatchRate[i*4+j])-log10(mp+3.5*dp))/0.039;
225 // * (dif-5)/dif
226 Step(i*4+j, step);
227 continue;
228 }
229
230 // For pixels below the median correct also back to median+3*deviation
231 if (sdata.fPatchRate[i*4+j]<mp)
232 {
233 const float step = (log10(sdata.fPatchRate[i*4+j])-log10(mp+3.5*dp))/0.039;
234 Step(i*4+j, step);
235 continue;
236 }
237
238 const float step = -1.5*(log10(mp+dp)-log10(mp))/0.039;
239 Step(i*4+j, step);
240 }
241 }
242 }
243
244 int ProcessCamera(const FTM::DimTriggerRates &sdata)
245 {
246 if (fCounter++==0)
247 return GetCurrentState();
248
249 // Caluclate Median and deviation
250 vector<float> medb(sdata.fBoardRate, sdata.fBoardRate+40);
251
252 sort(medb.begin(), medb.end());
253
254 vector<float> devb(40);
255 for (int i=0; i<40; i++)
256 devb[i] = fabs(sdata.fBoardRate[i]-medb[i]);
257
258 sort(devb.begin(), devb.end());
259
260 double mb = (medb[19]+medb[20])/2;
261 double db = devb[27];
262
263 // If any is zero there is something wrong
264 if (mb==0 || db==0)
265 {
266 Warn("The median or the deviation of all board rates is zero... cannot calibrate.");
267 return GetCurrentState();
268 }
269
270 double avg = 0;
271 int num = 0;
272
273 for (int i=0; i<40; i++)
274 {
275 if ( fabs(sdata.fBoardRate[i]-mb)<2.5*db)
276 {
277 avg += sdata.fBoardRate[i];
278 num++;
279 }
280 }
281
282 fTriggerRate = avg/num * 40;
283
284 if (fVerbose)
285 {
286 Out() << "Board: Median=" << mb << " Dev=" << db << endl;
287 Out() << "Camera: " << fTriggerRate << " (" << sdata.fTriggerRate << ", n=" << num << ")" << endl;
288 Out() << "Target: " << fTargetRate << endl;
289 }
290
291 if (sdata.fTriggerRate<fTriggerRate)
292 fTriggerRate = sdata.fTriggerRate;
293
294 // ----------------------
295
296 /*
297 if (avg>0 && avg<fTargetRate)
298 {
299 // I am assuming here (and at other places) the the answer from the FTM when setting
300 // the new threshold always arrives faster than the next rate update.
301 fThresholdMin = fThresholds[0];
302 Out() << "Setting fThresholdMin to " << fThresholds[0] << endl;
303 }
304 */
305
306 if (fTriggerRate>0 && fTriggerRate<fTargetRate)
307 {
308 fThresholds.assign(160, fThresholdMin);
309
310 const RateControl::DimThreshold data = { fThresholdMin, fCalibrationTimeStart.Mjd(), Time().Mjd() };
311 fDimThreshold.setQuality(0);
312 fDimThreshold.Update(data);
313
314 ostringstream out;
315 out << setprecision(3);
316 out << "Measured rate " << fTriggerRate << "Hz below target rate " << fTargetRate << "... mininum threshold set to " << fThresholdMin;
317 Info(out);
318
319 return RateControl::State::kGlobalThresholdSet;
320 }
321
322 // This is a step towards a threshold at which the NSB rate is equal the target rate
323 // +1 to avoid getting a step of 0
324 const float step = (log10(fTriggerRate)-log10(fTargetRate))/0.039 + 1;
325
326 const uint16_t diff = fThresholdMin+int16_t(truncf(step));
327 if (diff<=fThresholdMin)
328 {
329 const RateControl::DimThreshold data = { fThresholdMin, fCalibrationTimeStart.Mjd(), Time().Mjd() };
330 fDimThreshold.setQuality(1);
331 fDimThreshold.Update(data);
332
333 ostringstream out;
334 out << setprecision(3);
335 out << "Next step would be 0... mininum threshold set to " << fThresholdMin;
336 Info(out);
337
338 return RateControl::State::kGlobalThresholdSet;
339 }
340
341 if (fVerbose)
342 {
343 //Out() << idx/40 << "|" << (idx/4)%10 << "|" << idx%4;
344 Out() << fThresholdMin;
345 Out() << (step>0 ? " += " : " -= ");
346 Out() << step << " (" << diff << ")" << endl;
347 }
348
349 const uint32_t val[2] = { -1, diff };
350 DimClient::sendCommandNB("FTM_CONTROL/SET_THRESHOLD", (void*)val, 8);
351
352 fThresholdMin = diff;
353
354 return GetCurrentState();
355 }
356
357 int HandleStaticData(const EventImp &evt)
358 {
359 if (!CheckEventSize(evt, sizeof(FTM::DimStaticData)))
360 return GetCurrentState();
361
362 const FTM::DimStaticData &sdata = *static_cast<const FTM::DimStaticData*>(evt.GetData());
363 fPhysTriggerEnabled = sdata.HasTrigger();
364 fTriggerOn = (evt.GetQoS()&FTM::kFtmStates)==FTM::kFtmRunning;
365
366 Out() << "\n" << evt.GetTime() << ": " << (bool)fTriggerOn << " " << (bool)fPhysTriggerEnabled << endl;
367 PrintThresholds(sdata);
368
369 fThresholds.assign(sdata.fThreshold, sdata.fThreshold+160);
370
371 return GetCurrentState();
372 }
373
374 int HandleTriggerRates(const EventImp &evt)
375 {
376 fTriggerOn = (evt.GetQoS()&FTM::kFtmStates)==FTM::kFtmRunning;
377
378 if (fThresholds.empty())
379 return GetCurrentState();
380
381 if (GetCurrentState()<=RateControl::State::kConnected ||
382 GetCurrentState()==RateControl::State::kGlobalThresholdSet)
383 return GetCurrentState();
384
385 if (!CheckEventSize(evt, sizeof(FTM::DimTriggerRates)))
386 return GetCurrentState();
387
388 const FTM::DimTriggerRates &sdata = *static_cast<const FTM::DimTriggerRates*>(evt.GetData());
389
390 if (GetCurrentState()==RateControl::State::kSettingGlobalThreshold && !fCalibrateByCurrent)
391 return ProcessCamera(sdata);
392
393 if (GetCurrentState()==RateControl::State::kInProgress)
394 ProcessPatches(sdata);
395
396 return GetCurrentState();
397 }
398
399 int HandleCalibratedCurrents(const EventImp &evt)
400 {
401 // Check if received event is valid
402 if (!CheckEventSize(evt, (416+6)*4))
403 return GetCurrentState();
404
405 // Record only currents when the drive is tracking to avoid
406 // bias from the movement
407 if (fDimDrive.state()<Drive::State::kTracking)
408 return GetCurrentState();
409
410 // Get time and median current (FIXME: check N?)
411 const Time &time = evt.GetTime();
412 const float med = evt.Get<float>(416*4+4+4);
413 const float dev = evt.Get<float>(416*4+4+4+4);
414 const float *cur = evt.Ptr<float>();
415
416 // Keep all median currents of the past 10 seconds
417 fCurrentsMed.emplace_back(time, med);
418 fCurrentsDev.emplace_back(time, dev);
419 fCurrentsVec.emplace_back(time, vector<float>(cur, cur+320));
420 while (!fCurrentsMed.empty())
421 {
422 if (time-fCurrentsMed.front().first<boost::posix_time::seconds(fAverageTime))
423 break;
424
425 fCurrentsMed.pop_front();
426 fCurrentsDev.pop_front();
427 fCurrentsVec.pop_front();
428 }
429
430 // If we are not doing a calibration no further action necessary
431 if (!fCalibrateByCurrent)
432 return GetCurrentState();
433
434 if (GetCurrentState()!=RateControl::State::kSettingGlobalThreshold)
435 return GetCurrentState();
436
437 // We want at least 8 values for averaging
438 if (fCurrentsMed.size()<fRequiredEvents)
439 return GetCurrentState();
440
441 // Calculate avera and rms of median
442 double avg = 0;
443 double rms = 0;
444 for (auto it=fCurrentsMed.begin(); it!=fCurrentsMed.end(); it++)
445 {
446 avg += it->second;
447 rms += it->second*it->second;
448 }
449 avg /= fCurrentsMed.size();
450 rms /= fCurrentsMed.size();
451 rms = sqrt(rms-avg*avg);
452
453 double avg_dev = 0;
454 for (auto it=fCurrentsDev.begin(); it!=fCurrentsDev.end(); it++)
455 avg_dev += it->second;
456 avg_dev /= fCurrentsMed.size();
457
458 // One could recalculate the median of all pixels incluing the
459 // correction for the three crazy pixels, but that is three out
460 // of 320. The effect on the median should be negligible anyhow.
461 vector<double> vec(160);
462 for (auto it=fCurrentsVec.begin(); it!=fCurrentsVec.end(); it++)
463 for (int i=0; i<320; i++)
464 {
465 const PixelMapEntry &hv = fMap.hv(i);
466 if (!hv)
467 continue;
468
469 // The current is proportional to the rate. To calculate
470 // a measure for the rate, the average current per pixel
471 // is caluclated for the trigger patch.
472 int weight = hv.group() ? 5 : 4;
473
474 // Use only the current in the pixels with the correct
475 // resistor as a reference, ignore the crazy ones.
476 // Effects of these should be corrected by the
477 // rate control later, not the initial setup.
478 if (i==66)
479 weight = 4./(3+10);
480 if (i==191 || i==193)
481 weight = 5./(4+10);
482
483 vec[hv.hw()/9] += it->second[i] * weight;
484 }
485
486 //fThresholdMin = max(uint16_t(36.0833*pow(avg, 0.638393)+184.037), fThresholdReference);
487 //fThresholdMin = max(uint16_t(42.4*pow(avg, 0.642)+182), fThresholdReference);
488 //fThresholdMin = max(uint16_t(41.6*pow(avg+1, 0.642)+175), fThresholdReference);
489 //fThresholdMin = max(uint16_t(42.3*pow(avg, 0.655)+190), fThresholdReference);
490 fThresholdMin = max(uint16_t(46.6*pow(avg, 0.627)+187), fThresholdReference);
491 //fThresholdMin = max(uint16_t(41.6*pow(avg, 0.642)+175), fThresholdReference);
492 fThresholds.assign(160, fThresholdMin);
493
494 const int32_t val[2] = { -1, fThresholdMin };
495 Dim::SendCommand("FTM_CONTROL/SET_THRESHOLD", val);
496
497 double avg2 = 0;
498 for (int i=0; i<160; i++)
499 {
500 vec[i] /= fCurrentsVec.size()*9;
501 avg2 += vec[i];
502
503 if (vec[i]-avg>3.5*avg_dev)
504 {
505 fThresholds[i] = max(uint16_t(40.5*pow(vec[i], 0.642)+164), fThresholdReference);
506
507 const int32_t dat[2] = { i, fThresholds[i] };
508 Dim::SendCommand("FTM_CONTROL/SET_THRESHOLD", dat);
509
510 fBlock[i/4] = true;
511 }
512 }
513
514 avg2 /= 160;
515
516 const RateControl::DimThreshold data = { fThresholdMin, fCalibrationTimeStart.Mjd(), Time().Mjd() };
517 fDimThreshold.setQuality(2);
518 fDimThreshold.Update(data);
519
520 ostringstream out;
521 out << setprecision(3);
522 out << "Measured average current " << avg << "uA +- " << rms << "uA [N=" << fCurrentsMed.size() << "]... mininum threshold set to " << fThresholdMin;
523 Info(out);
524
525 return RateControl::State::kGlobalThresholdSet;
526 }
527
528 int Calibrate()
529 {
530 if (!fPhysTriggerEnabled)
531 {
532 Info("Physics trigger not enabled... CALIBRATE command ignored.");
533 return RateControl::State::kGlobalThresholdSet;
534 }
535
536 const int32_t val[2] = { -1, fThresholdReference };
537 Dim::SendCommand("FTM_CONTROL/SET_THRESHOLD", val);
538
539 fThresholds.assign(160, fThresholdReference);
540
541 fThresholdMin = fThresholdReference;
542 fTriggerRate = -1;
543 fCounter = 0;
544 fBlock.assign(160, false);
545
546 fCalibrateByCurrent = false;
547 fCalibrationTimeStart = Time();
548
549 ostringstream out;
550 out << "Rate calibration started at a threshold of " << fThresholdReference << " with a target rate of " << fTargetRate << " Hz";
551 Info(out);
552
553 return RateControl::State::kSettingGlobalThreshold;
554 }
555
556 int CalibrateByCurrent()
557 {
558 if (!fPhysTriggerEnabled)
559 {
560 Info("Physics trigger not enabled... CALIBRATE command ignored.");
561 return RateControl::State::kGlobalThresholdSet;
562 }
563
564 if (fDimDrive.state()<Drive::State::kMoving)
565 Warn("Drive not even moving...");
566
567 fCounter = 0;
568 fCalibrateByCurrent = true;
569 fCalibrationTimeStart = Time();
570 fBlock.assign(160, false);
571
572 ostringstream out;
573 out << "Rate calibration by current with min. threshold of " << fThresholdReference << ".";
574 Info(out);
575
576 return RateControl::State::kSettingGlobalThreshold;
577 }
578
579 int CalibrateRun(const EventImp &evt)
580 {
581 const string name = evt.GetText();
582
583 auto it = fRunTypes.find(name);
584 if (it==fRunTypes.end())
585 {
586 Info("CalibrateRun - Run-type '"+name+"' not found... trying 'default'.");
587
588 it = fRunTypes.find("default");
589 if (it==fRunTypes.end())
590 {
591 Error("CalibrateRun - Run-type 'default' not found.");
592 return GetCurrentState();
593 }
594 }
595
596 const config &conf = it->second;
597
598 switch (conf.fCalibrationType)
599 {
600 case 0:
601 Info("No calibration requested.");
602 return RateControl::State::kGlobalThresholdSet;
603 break;
604
605 case 1:
606 fThresholdReference = conf.fMinThreshold;
607 fTargetRate = conf.fTargetRate;
608 return Calibrate();
609
610 case 2:
611 fThresholdReference = conf.fMinThreshold;
612 fAverageTime = conf.fAverageTime;
613 fRequiredEvents = conf.fRequiredEvents;
614 return CalibrateByCurrent();
615 }
616
617 Error("CalibrateRun - Calibration type "+to_string(conf.fCalibrationType)+" unknown.");
618 return GetCurrentState();
619 }
620
621 int StopRC()
622 {
623 Info("Stop received.");
624 return RateControl::State::kConnected;
625 }
626
627 int SetMinThreshold(const EventImp &evt)
628 {
629 if (!CheckEventSize(evt, 4))
630 return kSM_FatalError;
631
632 // FIXME: Check missing
633
634 fThresholdReference = evt.GetUShort();
635
636 return GetCurrentState();
637 }
638
639 int SetTargetRate(const EventImp &evt)
640 {
641 if (!CheckEventSize(evt, 4))
642 return kSM_FatalError;
643
644 fTargetRate = evt.GetFloat();
645
646 return GetCurrentState();
647 }
648
649 int Print() const
650 {
651 Out() << fDim << endl;
652 Out() << fDimFTM << endl;
653 Out() << fDimRS << endl;
654 Out() << fDimDrive << endl;
655
656 return GetCurrentState();
657 }
658
659 int SetVerbosity(const EventImp &evt)
660 {
661 if (!CheckEventSize(evt, 1))
662 return kSM_FatalError;
663
664 fVerbose = evt.GetBool();
665
666 return GetCurrentState();
667 }
668
669 int Execute()
670 {
671 if (!fDim.online())
672 return RateControl::State::kDimNetworkNA;
673
674 // All subsystems are not connected
675 if (fDimFTM.state()<FTM::State::kConnected || fDimDrive.state()<Drive::State::kConnected)
676 return RateControl::State::kDisconnected;
677
678 // Do not allow any action while a ratescan is configured or in progress
679 if (fDimRS.state()>=RateScan::State::kConfiguring)
680 return RateControl::State::kConnected;
681
682 switch (GetCurrentState())
683 {
684 case RateControl::State::kSettingGlobalThreshold:
685 return RateControl::State::kSettingGlobalThreshold;
686
687 case RateControl::State::kGlobalThresholdSet:
688
689 // Wait for the trigger to get switched on before starting control loop
690 if (fTriggerOn && fPhysTriggerEnabled)
691 return RateControl::State::kInProgress;
692
693 return RateControl::State::kGlobalThresholdSet;
694
695 case RateControl::State::kInProgress:
696
697 // Go back to connected when the trigger has been switched off
698 if (!fTriggerOn || !fPhysTriggerEnabled)
699 return RateControl::State::kConnected;
700
701 return RateControl::State::kInProgress;
702 }
703
704 return RateControl::State::kConnected;
705 }
706
707public:
708 StateMachineRateControl(ostream &out=cout) : StateMachineDim(out, "RATE_CONTROL"),
709 fPhysTriggerEnabled(false), fTriggerOn(false), fBlock(40),
710 fDimFTM("FTM_CONTROL"),
711 fDimRS("RATE_SCAN"),
712 fDimDrive("DRIVE_CONTROL"),
713 fDimThreshold("RATE_CONTROL/THRESHOLD", "S:1;D:1;D:1",
714 "Resulting threshold after calibration"
715 "|threshold[dac]:Resulting threshold from calibration"
716 "|begin[mjd]:Start time of calibration"
717 "|end[mjd]:End time of calibration")
718 {
719 // ba::io_service::work is a kind of keep_alive for the loop.
720 // It prevents the io_service to go to stopped state, which
721 // would prevent any consecutive calls to run()
722 // or poll() to do nothing. reset() could also revoke to the
723 // previous state but this might introduce some overhead of
724 // deletion and creation of threads and more.
725
726 fDim.Subscribe(*this);
727 fDimFTM.Subscribe(*this);
728 fDimRS.Subscribe(*this);
729 fDimDrive.Subscribe(*this);
730
731 Subscribe("FTM_CONTROL/TRIGGER_RATES")
732 (bind(&StateMachineRateControl::HandleTriggerRates, this, placeholders::_1));
733 Subscribe("FTM_CONTROL/STATIC_DATA")
734 (bind(&StateMachineRateControl::HandleStaticData, this, placeholders::_1));
735 Subscribe("FEEDBACK/CALIBRATED_CURRENTS")
736 (bind(&StateMachineRateControl::HandleCalibratedCurrents, this, placeholders::_1));
737
738 // State names
739 AddStateName(RateControl::State::kDimNetworkNA, "DimNetworkNotAvailable",
740 "The Dim DNS is not reachable.");
741
742 AddStateName(RateControl::State::kDisconnected, "Disconnected",
743 "The Dim DNS is reachable, but the required subsystems are not available.");
744
745 AddStateName(RateControl::State::kConnected, "Connected",
746 "All needed subsystems are connected to their hardware, no action is performed.");
747
748 AddStateName(RateControl::State::kSettingGlobalThreshold, "Calibrating",
749 "A global minimum thrshold is currently determined.");
750
751 AddStateName(RateControl::State::kGlobalThresholdSet, "GlobalThresholdSet",
752 "A global threshold has ben set, waiting for the trigger to be switched on.");
753
754 AddStateName(RateControl::State::kInProgress, "InProgress",
755 "Rate control in progress.");
756
757 AddEvent("CALIBRATE")
758 (bind(&StateMachineRateControl::Calibrate, this))
759 ("Start a search for a reasonable minimum global threshold");
760
761 AddEvent("CALIBRATE_BY_CURRENT")
762 (bind(&StateMachineRateControl::CalibrateByCurrent, this))
763 ("Set the global threshold from the median current");
764
765 AddEvent("CALIBRATE_RUN", "C")
766 (bind(&StateMachineRateControl::CalibrateRun, this, placeholders::_1))
767 ("Start a threshold calibration as defined in the setup for this run-type, state change to InProgress is delayed until trigger enabled");
768
769 AddEvent("STOP", RateControl::State::kSettingGlobalThreshold, RateControl::State::kGlobalThresholdSet, RateControl::State::kInProgress)
770 (bind(&StateMachineRateControl::StopRC, this))
771 ("Stop a calibration or ratescan in progress");
772
773 AddEvent("SET_MIN_THRESHOLD", "I:1")
774 (bind(&StateMachineRateControl::SetMinThreshold, this, placeholders::_1))
775 ("Set a minimum threshold at which th rate control starts calibrating");
776
777 AddEvent("SET_TARGET_RATE", "F:1")
778 (bind(&StateMachineRateControl::SetTargetRate, this, placeholders::_1))
779 ("Set a target trigger rate for the calibration");
780
781 AddEvent("PRINT")
782 (bind(&StateMachineRateControl::Print, this))
783 ("Print current status");
784
785 AddEvent("SET_VERBOSE", "B")
786 (bind(&StateMachineRateControl::SetVerbosity, this, placeholders::_1))
787 ("set verbosity state"
788 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
789
790 }
791
792 bool GetConfig(Configuration &conf, const string &name, const string &sub, uint16_t &rc)
793 {
794 if (conf.HasDef(name, sub))
795 {
796 rc = conf.GetDef<uint16_t>(name, sub);
797 return true;
798 }
799
800 Error("Neither "+name+"default nor "+name+sub+" found.");
801 return false;
802 }
803
804 int EvalOptions(Configuration &conf)
805 {
806 fVerbose = !conf.Get<bool>("quiet");
807
808 if (!fMap.Read(conf.Get<string>("pixel-map-file")))
809 {
810 Error("Reading mapping table from "+conf.Get<string>("pixel-map-file")+" failed.");
811 return 1;
812 }
813
814 fThresholdReference = 300;
815 fThresholdMin = 300;
816 fTargetRate = 75;
817
818 fAverageTime = 10;
819 fRequiredEvents = 8;
820
821 // ---------- Setup run types ---------
822 const vector<string> types = conf.Vec<string>("run-type");
823 if (types.empty())
824 Warn("No run-types defined.");
825 else
826 Message("Defining run-types");
827
828 for (auto it=types.begin(); it!=types.end(); it++)
829 {
830 Message(" -> "+ *it);
831
832 if (fRunTypes.count(*it)>0)
833 {
834 Error("Run-type "+*it+" defined twice.");
835 return 1;
836 }
837
838 config &c = fRunTypes[*it];
839 if (!GetConfig(conf, "calibration-type.", *it, c.fCalibrationType) ||
840 !GetConfig(conf, "target-rate.", *it, c.fTargetRate) ||
841 !GetConfig(conf, "min-threshold.", *it, c.fMinThreshold) ||
842 !GetConfig(conf, "average-time.", *it, c.fAverageTime) ||
843 !GetConfig(conf, "required-events.", *it, c.fRequiredEvents))
844 return 2;
845 }
846
847 return -1;
848 }
849};
850
851// ------------------------------------------------------------------------
852
853#include "Main.h"
854
855template<class T>
856int RunShell(Configuration &conf)
857{
858 return Main::execute<T, StateMachineRateControl>(conf);
859}
860
861void SetupConfiguration(Configuration &conf)
862{
863 po::options_description control("Rate control options");
864 control.add_options()
865 ("quiet,q", po_bool(), "Disable printing more informations during rate control.")
866 ("pixel-map-file", var<string>()->required(), "Pixel mapping file. Used here to get the default reference voltage.")
867 //("max-wait", var<uint16_t>(150), "The maximum number of seconds to wait to get the anticipated resolution for a point.")
868 // ("resolution", var<double>(0.05) , "The minimum resolution required for a single data point.")
869 ;
870
871 conf.AddOptions(control);
872
873 po::options_description runtype("Run type configuration");
874 runtype.add_options()
875 ("run-type", vars<string>(), "Name of run-types (replace the * in the following configuration by the case-sensitive names defined here)")
876 ("calibration-type.*", var<uint16_t>(), "Calibration type (0: none, 1: by rate, 2: by current)")
877 ("target-rate.*", var<uint16_t>(), "Target rate for calibration by rate")
878 ("min-threshold.*", var<uint16_t>(), "Minimum threshold which can be applied in a calibration")
879 ("average-time.*", var<uint16_t>(), "Time in seconds to average the currents for a calibration by current.")
880 ("required-events.*", var<uint16_t>(), "Number of required current events to start a calibration by current.");
881 ;
882
883 conf.AddOptions(runtype);
884}
885
886/*
887 Extract usage clause(s) [if any] for SYNOPSIS.
888 Translators: "Usage" and "or" here are patterns (regular expressions) which
889 are used to match the usage synopsis in program output. An example from cp
890 (GNU coreutils) which contains both strings:
891 Usage: cp [OPTION]... [-T] SOURCE DEST
892 or: cp [OPTION]... SOURCE... DIRECTORY
893 or: cp [OPTION]... -t DIRECTORY SOURCE...
894 */
895void PrintUsage()
896{
897 cout <<
898 "The ratecontrol program is a keep the rate reasonable low.\n"
899 "\n"
900 "Usage: ratecontrol [-c type] [OPTIONS]\n"
901 " or: ratecontrol [OPTIONS]\n";
902 cout << endl;
903}
904
905void PrintHelp()
906{
907 Main::PrintHelp<StateMachineRateControl>();
908
909 /* Additional help text which is printed after the configuration
910 options goes here */
911
912 /*
913 cout << "bla bla bla" << endl << endl;
914 cout << endl;
915 cout << "Environment:" << endl;
916 cout << "environment" << endl;
917 cout << endl;
918 cout << "Examples:" << endl;
919 cout << "test exam" << endl;
920 cout << endl;
921 cout << "Files:" << endl;
922 cout << "files" << endl;
923 cout << endl;
924 */
925}
926
927int main(int argc, const char* argv[])
928{
929 Configuration conf(argv[0]);
930 conf.SetPrintUsage(PrintUsage);
931 Main::SetupConfiguration(conf);
932 SetupConfiguration(conf);
933
934 if (!conf.DoParse(argc, argv, PrintHelp))
935 return 127;
936
937 if (!conf.Has("console"))
938 return RunShell<LocalStream>(conf);
939
940 if (conf.Get<int>("console")==0)
941 return RunShell<LocalShell>(conf);
942 else
943 return RunShell<LocalConsole>(conf);
944
945 return 0;
946}
Note: See TracBrowser for help on using the repository browser.