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

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