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

Last change on this file since 16542 was 16450, checked in by tbretz, 11 years ago
Fixed a typo and replaced another DImClient by Dim
File size: 30.2 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 Dim::SendCommandNB("FTM_CONTROL/SET_THRESHOLD", val);
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 Dim::SendCommandNB("FTM_CONTROL/SET_THRESHOLD", val);
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 int counter = 1;
495
496 const int32_t val[2] = { -1, fThresholdMin };
497 Dim::SendCommandNB("FTM_CONTROL/SET_THRESHOLD", val);
498
499 double avg2 = 0;
500 for (int i=0; i<160; i++)
501 {
502 vec[i] /= fCurrentsVec.size()*9;
503 avg2 += vec[i];
504
505 if (vec[i]-avg>3.5*avg_dev)
506 {
507 fThresholds[i] = max(uint16_t(40.5*pow(vec[i], 0.642)+164), fThresholdReference);
508
509 const int32_t dat[2] = { i, fThresholds[i] };
510 Dim::SendCommandNB("FTM_CONTROL/SET_THRESHOLD", dat);
511
512 fBlock[i/4] = true;
513
514 counter++;
515 }
516 }
517
518 avg2 /= 160;
519
520 const RateControl::DimThreshold data = { fThresholdMin, fCalibrationTimeStart.Mjd(), Time().Mjd() };
521 fDimThreshold.setQuality(2);
522 fDimThreshold.Update(data);
523
524 Info("Sent a total of "+to_string(counter)+" commands for threshold setting");
525
526 ostringstream out;
527 out << setprecision(3);
528 out << "Measured average current " << avg << "uA +- " << rms << "uA [N=" << fCurrentsMed.size() << "]... mininum threshold set to " << fThresholdMin;
529 Info(out);
530
531 return RateControl::State::kGlobalThresholdSet;
532 }
533
534 int Calibrate()
535 {
536 if (!fPhysTriggerEnabled)
537 {
538 Info("Physics trigger not enabled... CALIBRATE command ignored.");
539 return RateControl::State::kGlobalThresholdSet;
540 }
541
542 const int32_t val[2] = { -1, fThresholdReference };
543 Dim::SendCommandNB("FTM_CONTROL/SET_THRESHOLD", val);
544
545 fThresholds.assign(160, fThresholdReference);
546
547 fThresholdMin = fThresholdReference;
548 fTriggerRate = -1;
549 fCounter = 0;
550 fBlock.assign(160, false);
551
552 fCalibrateByCurrent = false;
553 fCalibrationTimeStart = Time();
554
555 ostringstream out;
556 out << "Rate calibration started at a threshold of " << fThresholdReference << " with a target rate of " << fTargetRate << " Hz";
557 Info(out);
558
559 return RateControl::State::kSettingGlobalThreshold;
560 }
561
562 int CalibrateByCurrent()
563 {
564 if (!fPhysTriggerEnabled)
565 {
566 Info("Physics trigger not enabled... CALIBRATE command ignored.");
567 return RateControl::State::kGlobalThresholdSet;
568 }
569
570 if (fDimDrive.state()<Drive::State::kMoving)
571 Warn("Drive not even moving...");
572
573 fCounter = 0;
574 fCalibrateByCurrent = true;
575 fCalibrationTimeStart = Time();
576 fBlock.assign(160, false);
577
578 ostringstream out;
579 out << "Rate calibration by current with min. threshold of " << fThresholdReference << ".";
580 Info(out);
581
582 return RateControl::State::kSettingGlobalThreshold;
583 }
584
585 int CalibrateRun(const EventImp &evt)
586 {
587 const string name = evt.GetText();
588
589 auto it = fRunTypes.find(name);
590 if (it==fRunTypes.end())
591 {
592 Info("CalibrateRun - Run-type '"+name+"' not found... trying 'default'.");
593
594 it = fRunTypes.find("default");
595 if (it==fRunTypes.end())
596 {
597 Error("CalibrateRun - Run-type 'default' not found.");
598 return GetCurrentState();
599 }
600 }
601
602 const config &conf = it->second;
603
604 switch (conf.fCalibrationType)
605 {
606 case 0:
607 Info("No calibration requested.");
608 return RateControl::State::kGlobalThresholdSet;
609 break;
610
611 case 1:
612 fThresholdReference = conf.fMinThreshold;
613 fTargetRate = conf.fTargetRate;
614 return Calibrate();
615
616 case 2:
617 fThresholdReference = conf.fMinThreshold;
618 fAverageTime = conf.fAverageTime;
619 fRequiredEvents = conf.fRequiredEvents;
620 return CalibrateByCurrent();
621 }
622
623 Error("CalibrateRun - Calibration type "+to_string(conf.fCalibrationType)+" unknown.");
624 return GetCurrentState();
625 }
626
627 int StopRC()
628 {
629 Info("Stop received.");
630 return RateControl::State::kConnected;
631 }
632
633 int SetMinThreshold(const EventImp &evt)
634 {
635 if (!CheckEventSize(evt, 4))
636 return kSM_FatalError;
637
638 // FIXME: Check missing
639
640 fThresholdReference = evt.GetUShort();
641
642 return GetCurrentState();
643 }
644
645 int SetTargetRate(const EventImp &evt)
646 {
647 if (!CheckEventSize(evt, 4))
648 return kSM_FatalError;
649
650 fTargetRate = evt.GetFloat();
651
652 return GetCurrentState();
653 }
654
655 int Print() const
656 {
657 Out() << fDim << endl;
658 Out() << fDimFTM << endl;
659 Out() << fDimRS << endl;
660 Out() << fDimDrive << endl;
661
662 return GetCurrentState();
663 }
664
665 int SetVerbosity(const EventImp &evt)
666 {
667 if (!CheckEventSize(evt, 1))
668 return kSM_FatalError;
669
670 fVerbose = evt.GetBool();
671
672 return GetCurrentState();
673 }
674
675 int Execute()
676 {
677 if (!fDim.online())
678 return RateControl::State::kDimNetworkNA;
679
680 // All subsystems are not connected
681 if (fDimFTM.state()<FTM::State::kConnected || fDimDrive.state()<Drive::State::kConnected)
682 return RateControl::State::kDisconnected;
683
684 // Do not allow any action while a ratescan is configured or in progress
685 if (fDimRS.state()>=RateScan::State::kConfiguring)
686 return RateControl::State::kConnected;
687
688 switch (GetCurrentState())
689 {
690 case RateControl::State::kSettingGlobalThreshold:
691 return RateControl::State::kSettingGlobalThreshold;
692
693 case RateControl::State::kGlobalThresholdSet:
694
695 // Wait for the trigger to get switched on before starting control loop
696 if (fTriggerOn && fPhysTriggerEnabled)
697 return RateControl::State::kInProgress;
698
699 return RateControl::State::kGlobalThresholdSet;
700
701 case RateControl::State::kInProgress:
702
703 // Go back to connected when the trigger has been switched off
704 if (!fTriggerOn || !fPhysTriggerEnabled)
705 return RateControl::State::kConnected;
706
707 return RateControl::State::kInProgress;
708 }
709
710 return RateControl::State::kConnected;
711 }
712
713public:
714 StateMachineRateControl(ostream &out=cout) : StateMachineDim(out, "RATE_CONTROL"),
715 fPhysTriggerEnabled(false), fTriggerOn(false), fBlock(40),
716 fDimFTM("FTM_CONTROL"),
717 fDimRS("RATE_SCAN"),
718 fDimDrive("DRIVE_CONTROL"),
719 fDimThreshold("RATE_CONTROL/THRESHOLD", "S:1;D:1;D:1",
720 "Resulting threshold after calibration"
721 "|threshold[dac]:Resulting threshold from calibration"
722 "|begin[mjd]:Start time of calibration"
723 "|end[mjd]:End time of calibration")
724 {
725 // ba::io_service::work is a kind of keep_alive for the loop.
726 // It prevents the io_service to go to stopped state, which
727 // would prevent any consecutive calls to run()
728 // or poll() to do nothing. reset() could also revoke to the
729 // previous state but this might introduce some overhead of
730 // deletion and creation of threads and more.
731
732 fDim.Subscribe(*this);
733 fDimFTM.Subscribe(*this);
734 fDimRS.Subscribe(*this);
735 fDimDrive.Subscribe(*this);
736
737 Subscribe("FTM_CONTROL/TRIGGER_RATES")
738 (bind(&StateMachineRateControl::HandleTriggerRates, this, placeholders::_1));
739 Subscribe("FTM_CONTROL/STATIC_DATA")
740 (bind(&StateMachineRateControl::HandleStaticData, this, placeholders::_1));
741 Subscribe("FEEDBACK/CALIBRATED_CURRENTS")
742 (bind(&StateMachineRateControl::HandleCalibratedCurrents, this, placeholders::_1));
743
744 // State names
745 AddStateName(RateControl::State::kDimNetworkNA, "DimNetworkNotAvailable",
746 "The Dim DNS is not reachable.");
747
748 AddStateName(RateControl::State::kDisconnected, "Disconnected",
749 "The Dim DNS is reachable, but the required subsystems are not available.");
750
751 AddStateName(RateControl::State::kConnected, "Connected",
752 "All needed subsystems are connected to their hardware, no action is performed.");
753
754 AddStateName(RateControl::State::kSettingGlobalThreshold, "Calibrating",
755 "A global minimum thrshold is currently determined.");
756
757 AddStateName(RateControl::State::kGlobalThresholdSet, "GlobalThresholdSet",
758 "A global threshold has ben set, waiting for the trigger to be switched on.");
759
760 AddStateName(RateControl::State::kInProgress, "InProgress",
761 "Rate control in progress.");
762
763 AddEvent("CALIBRATE")
764 (bind(&StateMachineRateControl::Calibrate, this))
765 ("Start a search for a reasonable minimum global threshold");
766
767 AddEvent("CALIBRATE_BY_CURRENT")
768 (bind(&StateMachineRateControl::CalibrateByCurrent, this))
769 ("Set the global threshold from the median current");
770
771 AddEvent("CALIBRATE_RUN", "C")
772 (bind(&StateMachineRateControl::CalibrateRun, this, placeholders::_1))
773 ("Start a threshold calibration as defined in the setup for this run-type, state change to InProgress is delayed until trigger enabled");
774
775 AddEvent("STOP", RateControl::State::kSettingGlobalThreshold, RateControl::State::kGlobalThresholdSet, RateControl::State::kInProgress)
776 (bind(&StateMachineRateControl::StopRC, this))
777 ("Stop a calibration or ratescan in progress");
778
779 AddEvent("SET_MIN_THRESHOLD", "I:1")
780 (bind(&StateMachineRateControl::SetMinThreshold, this, placeholders::_1))
781 ("Set a minimum threshold at which th rate control starts calibrating");
782
783 AddEvent("SET_TARGET_RATE", "F:1")
784 (bind(&StateMachineRateControl::SetTargetRate, this, placeholders::_1))
785 ("Set a target trigger rate for the calibration");
786
787 AddEvent("PRINT")
788 (bind(&StateMachineRateControl::Print, this))
789 ("Print current status");
790
791 AddEvent("SET_VERBOSE", "B")
792 (bind(&StateMachineRateControl::SetVerbosity, this, placeholders::_1))
793 ("set verbosity state"
794 "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
795
796 }
797
798 bool GetConfig(Configuration &conf, const string &name, const string &sub, uint16_t &rc)
799 {
800 if (conf.HasDef(name, sub))
801 {
802 rc = conf.GetDef<uint16_t>(name, sub);
803 return true;
804 }
805
806 Error("Neither "+name+"default nor "+name+sub+" found.");
807 return false;
808 }
809
810 int EvalOptions(Configuration &conf)
811 {
812 fVerbose = !conf.Get<bool>("quiet");
813
814 if (!fMap.Read(conf.Get<string>("pixel-map-file")))
815 {
816 Error("Reading mapping table from "+conf.Get<string>("pixel-map-file")+" failed.");
817 return 1;
818 }
819
820 fThresholdReference = 300;
821 fThresholdMin = 300;
822 fTargetRate = 75;
823
824 fAverageTime = 10;
825 fRequiredEvents = 8;
826
827 // ---------- Setup run types ---------
828 const vector<string> types = conf.Vec<string>("run-type");
829 if (types.empty())
830 Warn("No run-types defined.");
831 else
832 Message("Defining run-types");
833
834 for (auto it=types.begin(); it!=types.end(); it++)
835 {
836 Message(" -> "+ *it);
837
838 if (fRunTypes.count(*it)>0)
839 {
840 Error("Run-type "+*it+" defined twice.");
841 return 1;
842 }
843
844 config &c = fRunTypes[*it];
845 if (!GetConfig(conf, "calibration-type.", *it, c.fCalibrationType) ||
846 !GetConfig(conf, "target-rate.", *it, c.fTargetRate) ||
847 !GetConfig(conf, "min-threshold.", *it, c.fMinThreshold) ||
848 !GetConfig(conf, "average-time.", *it, c.fAverageTime) ||
849 !GetConfig(conf, "required-events.", *it, c.fRequiredEvents))
850 return 2;
851 }
852
853 return -1;
854 }
855};
856
857// ------------------------------------------------------------------------
858
859#include "Main.h"
860
861template<class T>
862int RunShell(Configuration &conf)
863{
864 return Main::execute<T, StateMachineRateControl>(conf);
865}
866
867void SetupConfiguration(Configuration &conf)
868{
869 po::options_description control("Rate control options");
870 control.add_options()
871 ("quiet,q", po_bool(), "Disable printing more informations during rate control.")
872 ("pixel-map-file", var<string>()->required(), "Pixel mapping file. Used here to get the default reference voltage.")
873 //("max-wait", var<uint16_t>(150), "The maximum number of seconds to wait to get the anticipated resolution for a point.")
874 // ("resolution", var<double>(0.05) , "The minimum resolution required for a single data point.")
875 ;
876
877 conf.AddOptions(control);
878
879 po::options_description runtype("Run type configuration");
880 runtype.add_options()
881 ("run-type", vars<string>(), "Name of run-types (replace the * in the following configuration by the case-sensitive names defined here)")
882 ("calibration-type.*", var<uint16_t>(), "Calibration type (0: none, 1: by rate, 2: by current)")
883 ("target-rate.*", var<uint16_t>(), "Target rate for calibration by rate")
884 ("min-threshold.*", var<uint16_t>(), "Minimum threshold which can be applied in a calibration")
885 ("average-time.*", var<uint16_t>(), "Time in seconds to average the currents for a calibration by current.")
886 ("required-events.*", var<uint16_t>(), "Number of required current events to start a calibration by current.");
887 ;
888
889 conf.AddOptions(runtype);
890}
891
892/*
893 Extract usage clause(s) [if any] for SYNOPSIS.
894 Translators: "Usage" and "or" here are patterns (regular expressions) which
895 are used to match the usage synopsis in program output. An example from cp
896 (GNU coreutils) which contains both strings:
897 Usage: cp [OPTION]... [-T] SOURCE DEST
898 or: cp [OPTION]... SOURCE... DIRECTORY
899 or: cp [OPTION]... -t DIRECTORY SOURCE...
900 */
901void PrintUsage()
902{
903 cout <<
904 "The ratecontrol program is a keep the rate reasonable low.\n"
905 "\n"
906 "Usage: ratecontrol [-c type] [OPTIONS]\n"
907 " or: ratecontrol [OPTIONS]\n";
908 cout << endl;
909}
910
911void PrintHelp()
912{
913 Main::PrintHelp<StateMachineRateControl>();
914
915 /* Additional help text which is printed after the configuration
916 options goes here */
917
918 /*
919 cout << "bla bla bla" << endl << endl;
920 cout << endl;
921 cout << "Environment:" << endl;
922 cout << "environment" << endl;
923 cout << endl;
924 cout << "Examples:" << endl;
925 cout << "test exam" << endl;
926 cout << endl;
927 cout << "Files:" << endl;
928 cout << "files" << endl;
929 cout << endl;
930 */
931}
932
933int main(int argc, const char* argv[])
934{
935 Configuration conf(argv[0]);
936 conf.SetPrintUsage(PrintUsage);
937 Main::SetupConfiguration(conf);
938 SetupConfiguration(conf);
939
940 if (!conf.DoParse(argc, argv, PrintHelp))
941 return 127;
942
943 if (!conf.Has("console"))
944 return RunShell<LocalStream>(conf);
945
946 if (conf.Get<int>("console")==0)
947 return RunShell<LocalShell>(conf);
948 else
949 return RunShell<LocalConsole>(conf);
950
951 return 0;
952}
Note: See TracBrowser for help on using the repository browser.