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