source: trunk/FACT++/src/feedback.cc@ 13981

Last change on this file since 13981 was 13974, checked in by tbretz, 13 years ago
Added a faster procedure when the current control is anables to get to the nominal volatge
File size: 46.6 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 "Converter.h"
11#include "PixelMap.h"
12
13#include "tools.h"
14
15#include "LocalControl.h"
16
17#include "HeadersFAD.h"
18#include "HeadersFSC.h"
19#include "HeadersBIAS.h"
20#include "HeadersFeedback.h"
21
22#include "DimState.h"
23#include "DimDescriptionService.h"
24
25using namespace std;
26
27// ------------------------------------------------------------------------
28
29class StateMachineFeedback : public StateMachineDim
30{
31private:
32 enum control_t
33 {
34 kIdle,
35 kTemp,
36 kFeedback,
37 kFeedbackGlobal,
38 kCurrents,
39 };
40
41 control_t fControlType;
42
43 PixelMap fMap;
44
45 DimVersion fDim;
46 DimDescribedState fDimFAD;
47 DimDescribedState fDimFSC;
48 DimDescribedState fDimBias;
49
50 DimDescribedService fDimReference;
51 DimDescribedService fDimDeviation;
52 DimDescribedService fDimCalibration;
53
54 vector<int64_t> fCurrentsAvg;
55 vector<int64_t> fCurrentsRms;
56
57 vector<float> fCalibration;
58 vector<float> fVoltGapd;
59
60 vector<vector<float>> fData;
61
62 int64_t fCursorCur;
63 uint64_t fCursorAmpl;
64 uint64_t fCursorTemp;
65
66 Time fBiasLast;
67 Time fStartTime;
68
69 valarray<double> fPV[3]; // Process variable (intgerated/averaged amplitudes)
70 valarray<double> fSP; // Set point (target amplitudes)
71
72 double fKp; // Proportional constant
73 double fKi; // Integral constant
74 double fKd; // Derivative constant
75 double fT; // Time constant (cycle time)
76 double fGain; // Gain (conversion from a DRS voltage deviation into a BIAS voltage change at G-APD reference voltage)
77
78 double fT21;
79
80 double fBiasOffset;
81 double fTempOffset;
82 double fCalibrationOffset;
83 double fAppliedOffset;
84
85 uint16_t fCurrentRequestInterval;
86 uint16_t fNumCalibIgnore;
87 uint16_t fNumCalibRequests;
88
89 bool fOutputEnabled;
90
91 int HandleCameraTemp(const EventImp &evt)
92 {
93 if (fControlType!=kTemp && fControlType!=kCurrents)
94 return GetCurrentState();
95
96 if (evt.GetSize()!=60*sizeof(float))
97 return GetCurrentState();
98
99 const float *ptr = evt.Ptr<float>();
100
101 double avgt = 0;
102 int numt = 0;
103 for (int i=1; i<32; i++)
104 if (ptr[i]!=0)
105 {
106 avgt += ptr[i];
107 numt++;
108 }
109
110 if (numt==0)
111 {
112 Warn("Received sensor temperatures all invalid.");
113 return GetCurrentState();
114 }
115
116 avgt /= numt; // [deg C]
117
118 fTempOffset = (avgt-25)*4./70; // [V]
119
120 return HandleCurrentControl();
121 }
122
123 int HandleCurrentControl()
124 {
125 const double dUt = fTempOffset; // [V]
126
127 if (GetCurrentState()==Feedback::State::kCalibrating && fBiasOffset>dUt-1.2)
128 {
129 ostringstream msg;
130 msg << " (applied calibration offset " << fBiasOffset << "V exceeds temperature correction " << fTempOffset << "V - 1.2V.";
131 Warn("Trying to calibrate above G-APD breakdown volatge!");
132 Warn(msg);
133 return GetCurrentState();
134 }
135
136 // FIXME: If calibrating do not wait for the temperature!
137 fAppliedOffset = fBiasOffset;
138 if (GetCurrentState()!=Feedback::State::kCalibrating)
139 fAppliedOffset += dUt;
140
141 vector<float> vec(2*BIAS::kNumChannels+2);
142 for (int i=0; i<BIAS::kNumChannels; i++)
143 vec[i+BIAS::kNumChannels] = fAppliedOffset;
144
145 vec[BIAS::kNumChannels*2] = dUt;
146 vec[BIAS::kNumChannels*2+1] = fBiasOffset;
147
148 double avg[2] = { 0, 0 };
149 double min[2] = { 90, 90 };
150 double max[2] = { -90, -90 };
151 int num[2] = { 0, 0 };
152
153 vector<double> med[2];
154 med[0].resize(416);
155 med[1].resize(416);
156
157 if (fControlType==kCurrents)
158 {
159 if (fCursorCur==0)
160 {
161 //DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
162 return GetCurrentState();
163 }
164
165 // Pixel 583: 5 31 == 191 (5) C2 B3 P3
166 // Pixel 830: 2 2 == 66 (4) C0 B8 P1
167 // Pixel 1401: 6 1 == 193 (5) C2 B4 P0
168
169 // Convert from DAC counts to uA
170 const double conv = 5000./4096;
171
172 // 3900 Ohm/n + 1000 Ohm + 1100 Ohm (with n=4 or n=5)
173 const double R[2] = { 3075, 2870 };
174
175 const float *Iavg = fCalibration.data(); // Offset at U=fCalibrationOffset
176 const float *Ravg = fCalibration.data()+BIAS::kNumChannels*2; // Measured resistance
177
178 // U0 = fCalibrationOffset
179 // dT = fAppliedVoltage
180
181 // Ifeedback = Im[i] - (U[i]-U0)/Ravg[i] - Iavg[i];
182 // dUapplied[i] + dUneu[i] = R[g] * (Im[i] - (dUapplied[i]+dUneu[i]-U0+dT)/Ravg[i] - Iavg[i])
183
184 // The assumption here is that the offset calculated from the temperature
185 // does not significanly change within a single step
186
187 // dU[i] := dUtotal[i] = dUapplied[i] + dUneu[i]
188 // dU[i] / R[g] = Im[i] - (dU[i]+dT-U0)/Ravg[i] - Iavg[i]
189 // dU[i]/R[g] + dU[i]/Ravg[i] = Im[i] + U0/Ravg[i] - dT/Ravg[i] - Iavg[i]
190 // dU[i]*(1/R[g]+1/Ravg[i]) = Im[i] - Iavg[i] + U0/Ravg[i] - dT/Ravg[i]
191 // dU[i] = (Im[i] - Iavg[i] + U0/Ravg[i] - dT/Ravg[i]) / (1/R[g]+1/Ravg[i])
192 // dU[i] = { Im[i] - Iavg[i] + (U0-dT)/Ravg[i] } * r with r := 1 / (1/R[g]+1/Ravg[i])
193
194 const double U0 = fAppliedOffset-fCalibrationOffset;
195
196 for (int i=0; i<BIAS::kNumChannels; i++)
197 {
198 const PixelMapEntry &hv = fMap.hv(i);
199 if (!hv)
200 continue;
201
202 // Average measured current
203 const double Im = double(fCurrentsAvg[i])/fCursorCur * conv; // [uA]
204
205 // Group index (0 or 1) of the of the pixel (4 or 5 pixel patch)
206 const int g = hv.group();
207
208 // Serial resistors in front of the G-APD
209 double Rg = R[g];
210
211 // This is assuming that the broken pixels have a 390 Ohm instead of 3900 Ohm serial resistor
212 if (i==66) // Pixel 830(66)
213 Rg = 2400; // 2400 = (3/3900 + 1/390) + 1000 + 1100
214 if (i==191 || i==193) // Pixel 583(191) / Pixel 1401(193)
215 Rg = 2379; // 2379 = (4/3900 + 1/390) + 1000 + 1100
216
217 const double r = 1./(1./Rg + 1./Ravg[i]); // [Ohm]
218
219 // Offset induced by the voltage above the calibration point
220 const double dI = U0/Ravg[i]; // [V/Ohm]
221
222 // Offset at the calibration point (make sure that the calibration is
223 // valid (Im[i]>Iavg[i]) and we operate above the calibration point)
224 const double I = Im>Iavg[i] ? Im - Iavg[i] : 0; // [A]
225
226 // Make sure that the averaged resistor is valid
227 const double dU = Ravg[i]>10000 ? r*(I*1e-6 - dI) : 0;
228
229 vec[i+BIAS::kNumChannels] += dU;
230
231 // Angelegte Spannung: U0+dU
232 // Gemessener Strom: Im - Iavg
233 // Strom offset: (U0+dU) / Ravg
234 // Fliessender Strom: Im-Iavg - (U0+dU)/Ravg
235 // Korrektur: [ Im-Iavg - (U0+dU)/Ravg ] * Rg
236
237 // Aufgeloest nach dU: dU = ( Im-Iavg - dU/Ravg ) / ( 1/Rg + 1/Ravg )
238 // Equivalent zu: dU = ( I*Ravg - U0 ) / ( Ravg/Rg+1 )
239
240 // Calculate statistics only for channels with a valid calibration
241 if (Iavg[i]>0)
242 {
243 med[g][num[g]] = dU;
244 avg[g] += dU;
245 num[g]++;
246
247 if (dU<min[g])
248 min[g] = dU;
249 if (dU>max[g])
250 max[g] = dU;
251 }
252 }
253
254 sort(med[0].begin(), med[0].begin()+num[0]);
255 sort(med[1].begin(), med[1].begin()+num[1]);
256
257 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
258 fCursorCur = 0;
259 }
260
261 fDimDeviation.setQuality(fControlType);
262 fDimDeviation.Update(vec);
263
264 if (!fOutputEnabled || fDimBias.state()!=BIAS::State::kVoltageOn)
265 return GetCurrentState();
266
267 // Trigger calibration
268 if (GetCurrentState()==Feedback::State::kCalibrating && fCursorTemp==1)
269 {
270 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
271 return GetCurrentState();
272 }
273
274 ostringstream msg;
275 msg << setprecision(4) << "Sending new absolute offset (" << fAppliedOffset << "V+" << (num[0]+num[1]>0?(avg[0]+avg[1])/(num[0]+num[1]):0) << "V) to biasctrl.";
276 Info(msg);
277
278 if (fControlType==kCurrents && num[0]>0 && num[1]>0)
279 {
280 msg.str("");
281 msg << " Avg0=" << setw(7) << avg[0]/num[0] << " | Avg1=" << setw(7) << avg[1]/num[1];
282 Debug(msg);
283
284 msg.str("");
285 msg << " Med0=" << setw(7) << med[0][num[0]/2] << " | Med1=" << setw(7) << med[1][num[1]/2];
286 Debug(msg);
287
288 msg.str("");
289 msg << " Min0=" << setw(7) << min[0] << " | Min1=" << setw(7) << min[1];
290 Debug(msg);
291
292 msg.str("");
293 msg << " Max0=" << setw(7) << max[0] << " | Max1=" << setw(7) << max[1];
294 Debug(msg);
295 }
296
297 DimClient::sendCommandNB("BIAS_CONTROL/SET_ALL_CHANNELS_OFFSET",
298 vec.data()+BIAS::kNumChannels, BIAS::kNumChannels*sizeof(float));
299
300 fCursorTemp++;
301
302 return GetCurrentState();
303 }
304
305 int AverageCurrents(const EventImp &evt)
306 {
307 if (evt.GetSize()!=BIAS::kNumChannels*sizeof(int16_t))
308 return -1;
309
310 if (fDimBias.state()!=BIAS::State::kVoltageOn)
311 return false;
312
313 if (fCursorCur++<0)
314 return true;
315
316 const int16_t *ptr = evt.Ptr<int16_t>();
317
318 for (int i=0; i<BIAS::kNumChannels; i++)
319 {
320 fCurrentsAvg[i] += ptr[i];
321 fCurrentsRms[i] += ptr[i]*ptr[i];
322 }
323
324 return true;
325 }
326
327
328 void HandleCalibration(const EventImp &evt)
329 {
330 const int rc = AverageCurrents(evt);
331 if (rc<0)
332 return;
333
334 if (fCursorCur<fNumCalibRequests)
335 {
336 if (fDimBias.state()==BIAS::State::kVoltageOn)
337 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
338 return;
339 }
340
341 if (rc==0)
342 return;
343
344 fCalibration.resize(BIAS::kNumChannels*3);
345
346 float *avg = fCalibration.data();
347 float *rms = fCalibration.data()+BIAS::kNumChannels;
348 float *res = fCalibration.data()+BIAS::kNumChannels*2;
349
350 const double conv = 5000./4096;
351
352 for (int i=0; i<BIAS::kNumChannels; i++)
353 {
354 const double I = double(fCurrentsAvg[i])/fCursorCur;
355
356 res[i] = (fVoltGapd[i]+fCalibrationOffset)/I / conv * 1e6;
357 avg[i] = conv * I;
358 rms[i] = conv * sqrt(double(fCurrentsRms[i])/fCursorCur-I*I);
359 }
360
361 fDimCalibration.Update(fCalibration);
362
363 fOutputEnabled = false;
364 fControlType = kIdle;
365
366 Info("Calibration successfully done.");
367
368 if (fDimBias.state()==BIAS::State::kVoltageOn)
369 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
370 }
371
372 void HandleFeedback(const EventImp &evt)
373 {
374 if (evt.GetSize()!=1440*sizeof(float))
375 return;
376
377 // -------- Check age of last stored event --------
378
379 const Time tm(evt.GetTime());
380
381 if (Time()-fBiasLast>boost::posix_time::seconds(30))
382 {
383 Warn("Last received event data older than 30s... resetting average calculation.");
384 ResetData();
385 }
386 fBiasLast = tm;
387
388 // -------- Store new event --------
389
390 fData[fCursorAmpl%fData.size()].assign(evt.Ptr<float>(), evt.Ptr<float>()+1440);
391 if (++fCursorAmpl<fData.size())
392 return;
393
394 // -------- Calculate statistics --------
395
396 valarray<double> med(1440);
397
398 for (int ch=0; ch<1440; ch++)
399 {
400 vector<float> arr(fData.size());
401 for (size_t i=0; i<fData.size(); i++)
402 arr[i] = fData[i][ch];
403
404 sort(arr.begin(), arr.end());
405
406 med[ch] = arr[arr.size()/2];
407 }
408
409 /*
410 vector<float> med(1440);
411 vector<float> rms(1440);
412 for (size_t i=0; i<fData.size(); i++)
413 {
414 if (fData[i].size()==0)
415 return;
416
417 for (int j=0; j<1440; j++)
418 {
419 med[j] += fData[i][j];
420 rms[j] += fData[i][j]*fData[i][j];
421 }
422 }
423 */
424
425 vector<double> avg(BIAS::kNumChannels);
426 vector<int> num(BIAS::kNumChannels);
427 for (int i=0; i<1440; i++)
428 {
429 const PixelMapEntry &ch = fMap.hw(i);
430
431 // FIXME: Add a consistency check if the median makes sense...
432 // FIXME: Add a consistency check to remove pixels with bright stars (median?)
433
434 avg[ch.hv()] += med[i];
435 num[ch.hv()]++;
436 }
437
438 for (int i=0; i<BIAS::kNumChannels; i++)
439 {
440 if (num[i])
441 avg[i] /= num[i];
442
443 }
444
445 // -------- Calculate correction --------
446
447 // http://bestune.50megs.com/typeABC.htm
448
449 // CO: Controller output
450 // PV: Process variable
451 // SP: Set point
452 // T: Sampling period (loop update period)
453 // e = SP - PV
454 //
455 // Kp : No units
456 // Ki : per seconds
457 // Kd : seconds
458
459 // CO(k)-CO(k-1) = - Kp[ PV(k) - PV(k-1) ] + Ki * T * (SP(k)-PV(k)) - Kd/T [ PV(k) - 2PV(k-1) + PV(k-2) ]
460
461 if (fCursorAmpl%fData.size()>0)
462 return;
463
464 // FIXME: Take out broken / dead boards.
465
466 const Time tm0 = Time();
467
468 /*const*/ double T21 = fT>0 ? fT : (tm0-fStartTime).total_microseconds()/1000000.;
469 const double T10 = fT21;
470 fT21 = T21;
471
472 fStartTime = tm0;
473
474 ostringstream out;
475 out << "New " << fData.size() << " event received: " << fCursorAmpl << " / " << setprecision(3) << T21 << "s";
476 Info(out);
477
478 if (fPV[0].size()==0)
479 {
480 fPV[0].resize(avg.size());
481 fPV[0] = valarray<double>(avg.data(), avg.size());
482 return;
483 }
484
485 if (fPV[1].size()==0)
486 {
487 fPV[1].resize(avg.size());
488 fPV[1] = valarray<double>(avg.data(), avg.size());
489 return;
490 }
491
492 if (fPV[2].size()==0)
493 {
494 fPV[2].resize(avg.size());
495 fPV[2] = valarray<double>(avg.data(), avg.size());
496 return;
497 }
498
499 fPV[0] = fPV[1];
500 fPV[1] = fPV[2];
501
502 fPV[2].resize(avg.size());
503 fPV[2] = valarray<double>(avg.data(), avg.size());
504
505 if (T10<=0 || T21<=0)
506 return;
507
508 //cout << "Calculating (" << fCursor << ":" << T21 << ")... " << endl;
509
510 // fKi[j] = response[j]*gain;
511 // Kp = 0;
512 // Kd = 0;
513
514 // => Kp = 0.01 * gain = 0.00005
515 // => Ki = 0.8 * gain/20s = 0.00025
516 // => Kd = 0.1 * gain/20s = 0.00003
517
518 /*
519 fKp = 0;
520 fKd = 0;
521 fKi = 0.00003*20;
522 T21 = 1;
523 */
524
525 //valarray<double> correction = - Kp*(PV[2] - PV[1]) + Ki * dT * (SP-PV[2]) - Kd/dT * (PV[2] - 2*PV[1] + PV[0]);
526 //valarray<double> correction =
527 // - Kp * (PV[2] - PV[1])
528 // + dT * Ki * (SP - PV[2])
529 // - Kd / dT * (PV[2] - 2*PV[1] + PV[0]);
530 //
531 // - (Kp+Kd/dT1) * (PV[2] - PV[1])
532 // + dT2 * Ki * (SP - PV[2])
533 // + Kd / dT1 * (PV[1] - PV[0]);
534 //
535 // - Kp * (PV[2] - PV[1])
536 // + Ki * (SP - PV[2])*dT
537 // - Kd * (PV[2] - PV[1])/dT
538 // + Kd * (PV[1] - PV[0])/dT;
539 //
540 //valarray<double> correction =
541 // - Kp*(PV[2] - PV[1]) + Ki * T21 * (SP-PV[2]) - Kd*(PV[2]-PV[1])/T21 - Kd*(PV[0]-PV[1])/T01;
542 const valarray<double> correction = 1./fGain/1000*
543 (
544 - (fKp+fKd/T21)*(fPV[2] - fPV[1])
545 + fKi*T21*(fSP-fPV[2])
546 + fKd/T10*(fPV[1]-fPV[0])
547 );
548
549 /*
550 integral = 0
551 start:
552 integral += (fSP - fPV[2])*dt
553
554 output = Kp*(fSP - fPV[2]) + Ki*integral - Kd*(fPV[2] - fPV[1])/dt
555
556 wait(dt)
557
558 goto start
559 */
560
561 vector<float> vec(2*BIAS::kNumChannels+2);
562 for (int i=0; i<BIAS::kNumChannels; i++)
563 vec[i] = fPV[2][i]-fSP[i];
564
565 for (int i=0; i<BIAS::kNumChannels; i++)
566 vec[i+BIAS::kNumChannels] = avg[i]<5*2.5 ? 0 : correction[i];
567
568 fDimDeviation.setQuality(fControlType);
569 fDimDeviation.Update(vec);
570
571 if (!fOutputEnabled || fDimBias.state()!=BIAS::State::kVoltageOn)
572 return;
573
574 Info("Sending new relative offset to biasctrl.");
575
576 DimClient::sendCommandNB("BIAS_CONTROL/INCREASE_ALL_CHANNELS_VOLTAGE",
577 vec.data()+BIAS::kNumChannels, BIAS::kNumChannels*sizeof(float));
578 }
579
580 void HandleGlobalFeedback(const EventImp &evt)
581 {
582 if (evt.GetSize()!=1440*sizeof(float))
583 return;
584
585 // -------- Store new event --------
586
587 vector<float> arr(evt.Ptr<float>(), evt.Ptr<float>()+1440);
588
589 sort(arr.begin(), arr.end());
590
591 const float med = arr[arr.size()/2];
592
593 fData[fCursorAmpl%fData.size()].resize(1); //assign(&med, &med);
594 fData[fCursorAmpl%fData.size()][0] = med; //assign(&med, &med);
595
596 if (++fCursorAmpl<fData.size())
597 return;
598
599 // -------- Calculate statistics --------
600
601 double avg=0;
602 double rms=0;
603 for (size_t i=0; i<fData.size(); i++)
604 {
605 avg += fData[i][0];
606 rms += fData[i][0]*fData[i][0];
607 }
608
609 avg /= fData.size();
610 rms /= fData.size();
611
612 rms = sqrt(rms-avg*avg);
613
614 // -------- Calculate correction --------
615
616 if (fCursorAmpl%fData.size()!=0)
617 return;
618
619 Out() << "Amplitude: " << avg << " +- " << rms << endl;
620
621 // FIXME: Take out broken / dead boards.
622
623 /*
624 ostringstream out;
625 out << "New " << fData.size() << " event received: " << fCursor << " / " << setprecision(3) << T21 << "s";
626 Info(out);
627 */
628
629 if (fPV[0].size()==0)
630 {
631 fPV[0].resize(1);
632 fPV[0] = valarray<double>(&avg, 1);
633 return;
634 }
635
636 if (fPV[1].size()==0)
637 {
638 fPV[1].resize(1);
639 fPV[1] = valarray<double>(&avg, 1);
640 return;
641 }
642
643 if (fPV[2].size()==0)
644 {
645 fPV[2].resize(1);
646 fPV[2] = valarray<double>(&avg, 1);
647 return;
648 }
649
650 fPV[0] = fPV[1];
651 fPV[1] = fPV[2];
652
653 fPV[2].resize(1);
654 fPV[2] = valarray<double>(&avg, 1);
655
656 // ----- Calculate average currents -----
657
658 vector<float> A(BIAS::kNumChannels);
659 for (int i=0; i<BIAS::kNumChannels; i++)
660 A[i] = double(fCurrentsAvg[i]) / fCursorCur;
661
662 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
663 fCursorCur = 0;
664
665 // -------- Calculate correction --------
666
667 // correction = (fSP[0]-fPV[2])*fKi
668 /*
669 const double T21 = 1; // feedback is 1s
670 const double T10 = 1; // feedback is 20s
671
672 const valarray<double> correction = 1./fGain/1000*
673 (
674 - (fKp+fKd/T21)*(fPV[2] - fPV[1])
675 + fKi*T21*(fSP[0]-fPV[2])
676 + fKd/T10*(fPV[1]-fPV[0])
677 );
678 */
679
680 // pow of 1.6 comes from the non-linearity of the
681 // amplitude vs bias voltage
682 const valarray<double> correction = 1./fGain/1000*
683 (
684 //fKi*(pow(fSP[0], 1./1.6)-pow(fPV[2], 1./1.6))
685 fKi*(fSP[0]-fPV[2])
686 );
687
688 Out() << "Correction: " << correction[0] << "V (" << fSP[0] << ")" << endl;
689
690 const int nch = BIAS::kNumChannels;
691
692 // FIXME: Sanity check!
693
694 vector<float> vec;
695 vec.reserve(2*nch+2);
696 vec.insert(vec.begin(), nch, fPV[2][0]-fSP[0]);
697 vec.insert(vec.begin()+nch, nch, correction[0]);
698 vec.push_back(0);
699 vec.push_back(0);
700
701 fDimDeviation.setQuality(fControlType);
702 fDimDeviation.Update(vec);
703
704 if (!fOutputEnabled || fDimBias.state()!=BIAS::State::kVoltageOn)
705 return;
706
707 Info("Sending new global relative offset to biasctrl.");
708
709 DimClient::sendCommandNB("BIAS_CONTROL/INCREASE_ALL_CHANNELS_VOLTAGE",
710 vec.data()+BIAS::kNumChannels, BIAS::kNumChannels*sizeof(float));
711 }
712
713 int HandleBiasCurrent(const EventImp &evt)
714 {
715 if (fControlType==kTemp && GetCurrentState()==Feedback::State::kCalibrating)
716 HandleCalibration(evt);
717
718 if (fControlType==kFeedbackGlobal || fControlType==kCurrents)
719 AverageCurrents(evt);
720
721 if (fControlType==kCurrents && fTempOffset>-2 && fCursorTemp && fCursorCur%3==0)
722 HandleCurrentControl();
723
724 return GetCurrentState();
725 }
726
727 int HandleBiasData(const EventImp &evt)
728 {
729 if (fControlType==kFeedback)
730 HandleFeedback(evt);
731
732 if (fControlType==kFeedbackGlobal)
733 HandleGlobalFeedback(evt);
734
735 return GetCurrentState();
736 }
737
738 int HandleBiasNom(const EventImp &evt)
739 {
740 fVoltGapd.assign(evt.Ptr<float>(), evt.Ptr<float>()+416);
741
742 Info("Nominal bias voltages received.");
743
744 return GetCurrentState();
745 }
746
747 bool CheckEventSize(size_t has, const char *name, size_t size)
748 {
749 if (has==size)
750 return true;
751
752 ostringstream msg;
753 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
754 Fatal(msg);
755 return false;
756 }
757
758 int Print() const
759 {
760 Out() << fDim << endl;
761 Out() << fDimFAD << endl;
762 Out() << fDimFSC << endl;
763 Out() << fDimBias << endl;
764
765 return GetCurrentState();
766 }
767
768 int PrintCalibration()
769 {
770 if (fCalibration.size()==0)
771 {
772 Out() << "No calibration performed so far." << endl;
773 return GetCurrentState();
774 }
775
776 const float *avg = fCalibration.data();
777 const float *rms = fCalibration.data()+BIAS::kNumChannels;
778 const float *res = fCalibration.data()+BIAS::kNumChannels*2;
779
780 Out() << "Average current at " << fCalibrationOffset << "V below G-APD operation voltage:\n";
781
782 for (int k=0; k<13; k++)
783 for (int j=0; j<8; j++)
784 {
785 Out() << setw(2) << k << "|" << setw(2) << j*4 << "|";
786 for (int i=0; i<4; i++)
787 Out() << Tools::Form(" %6.1f+-%4.1f", avg[k*32+j*4+i], rms[k*32+j*4+i]);
788 Out() << '\n';
789 }
790 Out() << '\n';
791
792 Out() << "Measured calibration resistor:\n";
793 for (int k=0; k<13; k++)
794 for (int j=0; j<4; j++)
795 {
796 Out() << setw(2) << k << "|" << setw(2) << j*8 << "|";
797 for (int i=0; i<8; i++)
798 Out() << Tools::Form(" %5.0f", res[k*32+j*8+i]);
799 Out() << '\n';
800 }
801
802 Out() << flush;
803
804 return GetCurrentState();
805 }
806
807 void WarnState(bool needfsc, bool needfad)
808 {
809 const bool bias = fDimBias.state() >= BIAS::State::kConnecting;
810 const bool fsc = fDimFSC.state() >= FSC::State::kConnected;
811 const bool fad = fDimFAD.state() >= FAD::State::kConnected;
812
813 if (!bias)
814 Warn("Bias control not yet ready.");
815 if (needfsc && !fsc)
816 Warn("FSC control not yet ready.");
817 if (needfad && !fad)
818 Warn("FAD control not yet ready.");
819 }
820
821 int SetConstant(const EventImp &evt, int constant)
822 {
823 if (!CheckEventSize(evt.GetSize(), "SetConstant", 8))
824 return kSM_FatalError;
825
826 switch (constant)
827 {
828 case 0: fKi = evt.GetDouble(); break;
829 case 1: fKp = evt.GetDouble(); break;
830 case 2: fKd = evt.GetDouble(); break;
831 case 3: fT = evt.GetDouble(); break;
832 case 4: fGain = evt.GetDouble(); break;
833 default:
834 Fatal("SetConstant got an unexpected constant id -- this is a program bug!");
835 return kSM_FatalError;
836 }
837
838 return GetCurrentState();
839 }
840
841 int EnableOutput(const EventImp &evt)
842 {
843 if (!CheckEventSize(evt.GetSize(), "EnableOutput", 1))
844 return kSM_FatalError;
845
846 fOutputEnabled = evt.GetBool();
847
848 return GetCurrentState();
849 }
850
851 void ResetData(int16_t n=-1)
852 {
853 fData.assign(n>0 ? n : fData.size(), vector<float>(0));
854
855 fCursorAmpl = 0;
856 fCursorCur = 0;
857 fCursorTemp = 0;
858
859 fStartTime = Time();
860
861 fSP = valarray<double>(0., BIAS::kNumChannels);
862
863 vector<float> vec(2*BIAS::kNumChannels+2, fBiasOffset);
864 vec[2*BIAS::kNumChannels] = 0;
865 fDimDeviation.setQuality(kIdle);
866 fDimDeviation.Update(vec);
867
868 fPV[0].resize(0);
869 fPV[1].resize(0);
870 fPV[2].resize(0);
871
872 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
873 fCurrentsRms.assign(BIAS::kNumChannels, 0);
874
875 if (fKp==0 && fKi==0 && fKd==0)
876 Warn("Control loop parameters are all set to zero.");
877 }
878
879 int StartFeedback(const EventImp &evt)
880 {
881 if (!CheckEventSize(evt.GetSize(), "StartFeedback", 2))
882 return kSM_FatalError;
883
884 WarnState(false, true);
885
886 fBiasOffset = 0;
887 ResetData(evt.GetShort());
888
889 fControlType = kFeedback;
890
891 return GetCurrentState();
892 }
893
894 int StartFeedbackGlobal(const EventImp &evt)
895 {
896 if (!CheckEventSize(evt.GetSize(), "StartFeedbackGlobal", 2))
897 return kSM_FatalError;
898
899 WarnState(false, true);
900
901 fBiasOffset = 0;
902 ResetData(evt.GetShort());
903
904 fControlType = kFeedbackGlobal;
905
906 return GetCurrentState();
907 }
908
909 int StartTempCtrl(const EventImp &evt)
910 {
911 if (!CheckEventSize(evt.GetSize(), "StartTempCtrl", 4))
912 return kSM_FatalError;
913
914 WarnState(true, false);
915
916 fBiasOffset = evt.GetFloat();
917 fControlType = kTemp;
918
919 ostringstream out;
920 out << "Starting temperature feedback with an offset of " << fBiasOffset << "V";
921 Message(out);
922
923 if (fDimBias.state()==BIAS::State::kVoltageOn)
924 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
925
926 return GetCurrentState();
927 }
928
929 int StartCurrentCtrl(const EventImp &evt)
930 {
931 if (!CheckEventSize(evt.GetSize(), "StartCurrentCtrl", 4))
932 return kSM_FatalError;
933
934 if (fCalibration.size()==0)
935 {
936 Warn("Current control needs a bias crate calibration first... command ignored.");
937 return GetCurrentState();
938 }
939
940 WarnState(true, false);
941
942 fBiasOffset = evt.GetFloat();
943 fTempOffset = -3;
944 ResetData(0);
945 fControlType = kCurrents;
946
947 ostringstream out;
948 out << "Starting current/temp feedback with an offset of " << fBiasOffset << "V";
949 Message(out);
950
951 return GetCurrentState();
952 }
953
954 int StopFeedback()
955 {
956 fControlType = kIdle;
957
958 return GetCurrentState();
959 }
960
961 int StoreReference()
962 {
963 if (!fPV[0].size() && !fPV[1].size() && !fPV[2].size())
964 {
965 Warn("No values in memory. Take enough events first!");
966 return GetCurrentState();
967 }
968
969 // FIXME: Check age
970
971 if (!fPV[1].size() && !fPV[2].size())
972 fSP = fPV[0];
973
974 if (!fPV[2].size())
975 fSP = fPV[1];
976 else
977 fSP = fPV[2];
978
979 vector<float> vec(BIAS::kNumChannels);
980 for (int i=0; i<BIAS::kNumChannels; i++)
981 vec[i] = fSP[i];
982 fDimReference.Update(vec);
983
984 return GetCurrentState();
985 }
986
987 int SetReference(const EventImp &evt)
988 {
989 if (!CheckEventSize(evt.GetSize(), "SetReference", 4))
990 return kSM_FatalError;
991
992 const float val = evt.GetFloat();
993 /*
994 if (!fPV[0].size() && !fPV[1].size() && !fPV[2].size())
995 {
996 Warn("No values in memory. Take enough events first!");
997 return GetCurrentState();
998 }*/
999
1000 vector<float> vec(BIAS::kNumChannels);
1001 for (int i=0; i<BIAS::kNumChannels; i++)
1002 vec[i] = fSP[i] = val;
1003 fDimReference.Update(vec);
1004
1005 Out() << "New global reference value: " << val << "mV" << endl;
1006
1007 return GetCurrentState();
1008 }
1009
1010 int CalibrateCurrents()
1011 {
1012// if (!CheckEventSize(evt.GetSize(), "StartTempCtrl", 4))
1013// return kSM_FatalError;
1014
1015 if (fDimBias.state()==BIAS::State::kRamping)
1016 {
1017 Warn("Calibration cannot be started when biasctrl is in state Ramping.");
1018 return GetCurrentState();
1019 }
1020
1021 if (fVoltGapd.size()==0)
1022 {
1023 Error("No G-APD reference voltages received yet (BIAS_CONTROL/NOMINAL).");
1024 return GetCurrentState();
1025 }
1026
1027 WarnState(true, false);
1028
1029 ostringstream out;
1030 out << "Starting temperature feedback for calibration with an offset of " << fCalibrationOffset << "V";
1031 Message(out);
1032
1033 fBiasOffset = fCalibrationOffset;
1034 fControlType = kTemp;
1035 fCursorCur = -fNumCalibIgnore;
1036 fCursorTemp = 0;
1037 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
1038 fCurrentsRms.assign(BIAS::kNumChannels, 0);
1039 fCalibration.resize(0);
1040 fStartTime = Time();
1041 fOutputEnabled = true;
1042
1043 return Feedback::State::kCalibrating;
1044 }
1045
1046 int SetCurrentRequestInterval(const EventImp &evt)
1047 {
1048 if (!CheckEventSize(evt.GetSize(), "SetCurrentRequestInterval", 2))
1049 return kSM_FatalError;
1050
1051 fCurrentRequestInterval = evt.GetUShort();
1052
1053 Out() << "New current request interval: " << fCurrentRequestInterval << "ms" << endl;
1054
1055 return GetCurrentState();
1056 }
1057
1058 int Execute()
1059 {
1060 // Dispatch (execute) at most one handler from the queue. In contrary
1061 // to run_one(), it doesn't wait until a handler is available
1062 // which can be dispatched, so poll_one() might return with 0
1063 // handlers dispatched. The handlers are always dispatched/executed
1064 // synchronously, i.e. within the call to poll_one()
1065 //poll_one();
1066
1067 if (!fDim.online())
1068 return Feedback::State::kDimNetworkNA;
1069
1070 const bool bias = fDimBias.state() >= BIAS::State::kConnecting;
1071 const bool fad = fDimFAD.state() >= FAD::State::kConnected;
1072 const bool fsc = fDimFSC.state() >= FSC::State::kConnected;
1073
1074 // All subsystems are not connected
1075 if (!bias && !fad && !fsc)
1076 return Feedback::State::kDisconnected;
1077
1078 // At least one subsystem apart from bias is connected
1079 if (bias && !fad && !fsc)
1080 return Feedback::State::kConnecting;
1081
1082/*
1083 // All subsystems are connected
1084 if (GetCurrentStatus()==Feedback::State::kConfiguringStep1)
1085 {
1086 if (fCursor<1)
1087 return Feedback::State::kConfiguringStep1;
1088
1089 if (fCursor==1)
1090 {
1091 fStartTime = Time();
1092 return Feedback::State::kConfiguringStep2;
1093 }
1094 }
1095 if (GetCurrentStatus()==Feedback::State::kConfiguringStep2)
1096 {
1097 if (fCursor==1)
1098 {
1099 if ((Time()-fStartTime).total_microseconds()/1000000.<1.5)
1100 return Feedback::State::kConfiguringStep2;
1101
1102 Dim::SendCommand("BIAS_CONTROL/REQUEST_STATUS");
1103 }
1104 if (fCursor==2)
1105 {
1106
1107 int n=0;
1108 double avg = 0;
1109 for (size_t i=0; i<fCurrents.size(); i++)
1110 if (fCurrents[i]>=0)
1111 {
1112 avg += fCurrents[i];
1113 n++;
1114 }
1115
1116 cout << avg/n << endl;
1117 }
1118 return Feedback::State::kConnected;
1119 }
1120 */
1121
1122 // Needs connection of FAD and BIAS
1123 if (bias && fad)
1124 {
1125 if (fControlType==kFeedback || fControlType==kFeedbackGlobal)
1126 return fOutputEnabled ? Feedback::State::kFeedbackCtrlRunning : Feedback::State::kFeedbackCtrlIdle;
1127 }
1128
1129 // Needs connection of FSC and BIAS
1130 if (bias && fsc)
1131 {
1132 if (fControlType==kTemp)
1133 {
1134 if (GetCurrentState()==Feedback::State::kCalibrating && fCursorCur<fNumCalibRequests)
1135 return GetCurrentState();
1136
1137 return fOutputEnabled ? Feedback::State::kTempCtrlRunning : Feedback::State::kTempCtrlIdle;
1138 }
1139 if (fControlType==kCurrents)
1140 {
1141 static Time past;
1142 if (fCurrentRequestInterval>0 && Time()-past>boost::posix_time::milliseconds(fCurrentRequestInterval))
1143 {
1144 if (fDimBias.state()==BIAS::State::kVoltageOn)
1145 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
1146 past = Time();
1147 }
1148
1149 return fOutputEnabled && fCursorTemp>0 ? Feedback::State::kCurrentCtrlRunning : Feedback::State::kCurrentCtrlIdle;
1150 }
1151 }
1152
1153 if (bias && fad && !fsc)
1154 return Feedback::State::kConnectedFAD;
1155
1156 if (bias && fsc && !fad)
1157 return Feedback::State::kConnectedFSC;
1158
1159 return Feedback::State::kConnected;
1160 }
1161
1162public:
1163 StateMachineFeedback(ostream &out=cout) : StateMachineDim(out, "FEEDBACK"),
1164 //---
1165 fDimFAD("FAD_CONTROL"),
1166 fDimFSC("FSC_CONTROL"),
1167 fDimBias("BIAS_CONTROL"),
1168 //---
1169 fDimReference("FEEDBACK/REFERENCE", "F:416",
1170 "Amplitude reference value(s)"
1171 "Vref[mV]:Amplitude reference"),
1172 fDimDeviation("FEEDBACK/DEVIATION", "F:416;F:416;F:1;F:1",
1173 "Control loop information"
1174 "|DeltaAmpl[mV]:Amplitude offset measures"
1175 "|DeltaBias[mV]:Correction value calculated"
1176 "|DeltaTemp[mV]:Correction calculated from temperature"
1177 "|DeltaUser[mV]:Additional offset specified by user"),
1178 fDimCalibration("FEEDBACK/CALIBRATION", "F:416;F:416;F:416",
1179 "Current offsets"
1180 "|Avg[uA]:Average offset"
1181 "|Rms[uA]:Rms of offset"
1182 "|R[Ohm]:Measured calibration resistor"),
1183 fSP(BIAS::kNumChannels),
1184 fKp(0), fKi(0), fKd(0), fT(-1),
1185 fCalibrationOffset(-3),
1186 fCurrentRequestInterval(0),
1187 fNumCalibIgnore(30),
1188 fNumCalibRequests(300),
1189 fOutputEnabled(false)
1190 {
1191 // ba::io_service::work is a kind of keep_alive for the loop.
1192 // It prevents the io_service to go to stopped state, which
1193 // would prevent any consecutive calls to run()
1194 // or poll() to do nothing. reset() could also revoke to the
1195 // previous state but this might introduce some overhead of
1196 // deletion and creation of threads and more.
1197
1198 fDim.Subscribe(*this);
1199 fDimFAD.Subscribe(*this);
1200 fDimFSC.Subscribe(*this);
1201 fDimBias.Subscribe(*this);
1202
1203 Subscribe("BIAS_CONTROL/CURRENT")
1204 (bind(&StateMachineFeedback::HandleBiasCurrent, this, placeholders::_1));
1205 Subscribe("BIAS_CONTROL/FEEDBACK_DATA")
1206 (bind(&StateMachineFeedback::HandleBiasData, this, placeholders::_1));
1207 Subscribe("FSC_CONTROL/TEMPERATURE")
1208 (bind(&StateMachineFeedback::HandleCameraTemp, this, placeholders::_1));
1209
1210 // State names
1211 AddStateName(Feedback::State::kDimNetworkNA, "DimNetworkNotAvailable",
1212 "The Dim DNS is not reachable.");
1213
1214 AddStateName(Feedback::State::kDisconnected, "Disconnected",
1215 "The Dim DNS is reachable, but the required subsystems are not available.");
1216
1217 AddStateName(Feedback::State::kConnecting, "Connecting",
1218 "Only biasctrl is available and connected with its hardware.");
1219
1220 AddStateName(Feedback::State::kConnectedFSC, "ConnectedFSC",
1221 "biasctrl and fscctrl are available and connected with their hardware.");
1222 AddStateName(Feedback::State::kConnectedFAD, "ConnectedFAD",
1223 "biasctrl and fadctrl are available and connected with their hardware.");
1224 AddStateName(Feedback::State::kConnected, "Connected",
1225 "biasctrl, fadctrl and fscctrl are available and connected with their hardware.");
1226
1227 AddStateName(Feedback::State::kFeedbackCtrlIdle, "FeedbackIdle",
1228 "Feedback control activated, but voltage output disabled.");
1229 AddStateName(Feedback::State::kTempCtrlIdle, "TempCtrlIdle",
1230 "Temperature control activated, but voltage output disabled.");
1231 AddStateName(Feedback::State::kCurrentCtrlIdle, "CurrentCtrlIdle",
1232 "Current control activated, but voltage output disabled.");
1233
1234 AddStateName(Feedback::State::kFeedbackCtrlRunning, "FeedbackControl",
1235 "Feedback control activated and voltage output enabled.");
1236 AddStateName(Feedback::State::kTempCtrlRunning, "TempControl",
1237 "Temperature control activated and voltage output enabled.");
1238 AddStateName(Feedback::State::kCurrentCtrlRunning, "CurrentControl",
1239 "Current/Temp control activated and voltage output enabled.");
1240 AddStateName(Feedback::State::kCalibrating, "Calibrating",
1241 "Calibrating current offsets.");
1242
1243 AddEvent("START_FEEDBACK_CONTROL", "S:1", Feedback::State::kConnectedFAD, Feedback::State::kConnected)
1244 (bind(&StateMachineFeedback::StartFeedback, this, placeholders::_1))
1245 ("Start the feedback control loop"
1246 "|Num[short]:Number of events 'medianed' to calculate the correction value");
1247
1248 AddEvent("START_GLOBAL_FEEDBACK", "S:1", Feedback::State::kConnectedFAD, Feedback::State::kConnected)
1249 (bind(&StateMachineFeedback::StartFeedbackGlobal, this, placeholders::_1))
1250 ("Start the global feedback control loop"
1251 "Num[short]:Number of events averaged to calculate the correction value");
1252
1253 AddEvent("START_TEMP_CONTROL", "F:1", Feedback::State::kConnectedFSC, Feedback::State::kConnected)
1254 (bind(&StateMachineFeedback::StartTempCtrl, this, placeholders::_1))
1255 ("Start the temperature control loop"
1256 "|offset[V]:Offset from the nominal temperature corrected value in Volts");
1257
1258 AddEvent("START_CURRENT_CONTROL", "F:1", Feedback::State::kConnectedFSC, Feedback::State::kConnected)
1259 (bind(&StateMachineFeedback::StartCurrentCtrl, this, placeholders::_1))
1260 ("Start the current/temperature control loop"
1261 "|offset[V]:Offset from the nominal current/temperature corrected value in Volts");
1262
1263 // Feedback::State::kTempCtrlIdle, Feedback::State::kFeedbackCtrlIdle, Feedback::State::kTempCtrlRunning, Feedback::State::kFeedbackCtrlRunning
1264 AddEvent("STOP")
1265 (bind(&StateMachineFeedback::StopFeedback, this))
1266 ("Stop any control loop");
1267
1268 AddEvent("ENABLE_OUTPUT", "B:1")//, Feedback::State::kIdle)
1269 (bind(&StateMachineFeedback::EnableOutput, this, placeholders::_1))
1270 ("Enable sending of correction values caluclated by the control loop to the biasctrl");
1271
1272 AddEvent("STORE_REFERENCE")//, Feedback::State::kIdle)
1273 (bind(&StateMachineFeedback::StoreReference, this))
1274 ("Store the last (averaged) value as new reference (for debug purpose only)");
1275
1276 AddEvent("SET_REFERENCE", "F:1")//, Feedback::State::kIdle)
1277 (bind(&StateMachineFeedback::SetReference, this, placeholders::_1))
1278 ("Set a new global reference value (for debug purpose only)");
1279
1280 AddEvent("SET_Ki", "D:1")//, Feedback::State::kIdle)
1281 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 0))
1282 ("Set integral constant Ki");
1283
1284 AddEvent("SET_Kp", "D:1")//, Feedback::State::kIdle)
1285 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 1))
1286 ("Set proportional constant Kp");
1287
1288 AddEvent("SET_Kd", "D:1")//, Feedback::State::kIdle)
1289 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 2))
1290 ("Set derivative constant Kd");
1291
1292 AddEvent("SET_T", "D:1")//, Feedback::State::kIdle)
1293 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 3))
1294 ("Set time-constant. (-1 to use the cycle time, i.e. the time for the last average cycle, instead)");
1295
1296 AddEvent("CALIBRATE_CURRENTS", Feedback::State::kConnectedFSC, Feedback::State::kConnected)//, Feedback::State::kIdle)
1297 (bind(&StateMachineFeedback::CalibrateCurrents, this))
1298 ("");
1299
1300 AddEvent("SET_CURRENT_REQUEST_INTERVAL", Feedback::State::kConnectedFSC, Feedback::State::kConnected)//, Feedback::State::kIdle)
1301 (bind(&StateMachineFeedback::SetCurrentRequestInterval, this, placeholders::_1))
1302 ("|interval[ms]:Interval between two current requests in modes which need that.");
1303
1304 // Verbosity commands
1305// AddEvent("SET_VERBOSE", "B:1")
1306// (bind(&StateMachineMCP::SetVerbosity, this, placeholders::_1))
1307// ("set verbosity state"
1308// "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
1309
1310 AddEvent("PRINT")
1311 (bind(&StateMachineFeedback::Print, this))
1312 ("");
1313
1314 AddEvent("PRINT_CALIBRATION")
1315 (bind(&StateMachineFeedback::PrintCalibration, this))
1316 ("");
1317 }
1318
1319 int EvalOptions(Configuration &conf)
1320 {
1321 if (!fMap.Read(conf.Get<string>("pixel-map-file")))
1322 {
1323 Error("Reading mapping table from "+conf.Get<string>("pixel-map-file")+" failed.");
1324 return 1;
1325 }
1326
1327 fGain = 0.1; // V(Amplitude) / V(Bias)
1328
1329 // 148 -> 248
1330
1331 // 33 : 10s < 2%
1332 // 50 : 5s < 2%
1333 // 66 : 3s < 2%
1334 // 85 : 2s < 2%
1335
1336 fKp = 0;
1337 fKd = 0;
1338 fKi = 0.75;
1339 fT = 1;
1340
1341 // Is that independent of the aboslute real amplitude of
1342 // the light pulser?
1343
1344 ostringstream msg;
1345 msg << "Control loop parameters: ";
1346 msg << "Kp=" << fKp << ", Kd=" << fKd << ", Ki=" << fKi << ", ";
1347 if (fT>0)
1348 msg << fT;
1349 else
1350 msg << "<auto>";
1351 msg << ", Gain(DRS/BIAS)=" << fGain << "V/V";
1352
1353 Message(msg);
1354
1355 fCurrentRequestInterval = conf.Get<uint16_t>("current-request-interval");
1356 fNumCalibIgnore = conf.Get<uint16_t>("num-calib-ignore");
1357 fNumCalibRequests = conf.Get<uint16_t>("num-calib-average");
1358 fCalibrationOffset = conf.Get<float>("calibration-offset");
1359
1360 return -1;
1361 }
1362};
1363
1364// ------------------------------------------------------------------------
1365
1366#include "Main.h"
1367
1368template<class T>
1369int RunShell(Configuration &conf)
1370{
1371 return Main::execute<T, StateMachineFeedback>(conf);
1372}
1373
1374void SetupConfiguration(Configuration &conf)
1375{
1376 po::options_description control("Feedback options");
1377 control.add_options()
1378 ("pixel-map-file", var<string>("FACTmapV5a.txt"), "Pixel mapping file. Used here to get the default reference voltage.")
1379 ("current-request-interval", var<uint16_t>(1000), "Interval between two current requests.")
1380 ("num-calib-ignore", var<uint16_t>(30), "Number of current requests to be ignored before averaging")
1381 ("num-calib-average", var<uint16_t>(300), "Number of current requests to be averaged")
1382 ("calibration-offset", var<float>(-3), "Absolute offset relative to the G-APD operation voltage when calibrating")
1383 ;
1384
1385 conf.AddOptions(control);
1386}
1387
1388/*
1389 Extract usage clause(s) [if any] for SYNOPSIS.
1390 Translators: "Usage" and "or" here are patterns (regular expressions) which
1391 are used to match the usage synopsis in program output. An example from cp
1392 (GNU coreutils) which contains both strings:
1393 Usage: cp [OPTION]... [-T] SOURCE DEST
1394 or: cp [OPTION]... SOURCE... DIRECTORY
1395 or: cp [OPTION]... -t DIRECTORY SOURCE...
1396 */
1397void PrintUsage()
1398{
1399 cout <<
1400 "The feedback control the BIAS voltages based on the calibration signal.\n"
1401 "\n"
1402 "The default is that the program is started without user intercation. "
1403 "All actions are supposed to arrive as DimCommands. Using the -c "
1404 "option, a local shell can be initialized. With h or help a short "
1405 "help message about the usuage can be brought to the screen.\n"
1406 "\n"
1407 "Usage: feedback [-c type] [OPTIONS]\n"
1408 " or: feedback [OPTIONS]\n";
1409 cout << endl;
1410}
1411
1412void PrintHelp()
1413{
1414 Main::PrintHelp<StateMachineFeedback>();
1415
1416 /* Additional help text which is printed after the configuration
1417 options goes here */
1418
1419 /*
1420 cout << "bla bla bla" << endl << endl;
1421 cout << endl;
1422 cout << "Environment:" << endl;
1423 cout << "environment" << endl;
1424 cout << endl;
1425 cout << "Examples:" << endl;
1426 cout << "test exam" << endl;
1427 cout << endl;
1428 cout << "Files:" << endl;
1429 cout << "files" << endl;
1430 cout << endl;
1431 */
1432}
1433
1434int main(int argc, const char* argv[])
1435{
1436 Configuration conf(argv[0]);
1437 conf.SetPrintUsage(PrintUsage);
1438 Main::SetupConfiguration(conf);
1439 SetupConfiguration(conf);
1440
1441 if (!conf.DoParse(argc, argv, PrintHelp))
1442 return -1;
1443
1444 //try
1445 {
1446 // No console access at all
1447 if (!conf.Has("console"))
1448 {
1449// if (conf.Get<bool>("no-dim"))
1450// return RunShell<LocalStream, StateMachine, ConnectionFSC>(conf);
1451// else
1452 return RunShell<LocalStream>(conf);
1453 }
1454 // Cosole access w/ and w/o Dim
1455/* if (conf.Get<bool>("no-dim"))
1456 {
1457 if (conf.Get<int>("console")==0)
1458 return RunShell<LocalShell, StateMachine, ConnectionFSC>(conf);
1459 else
1460 return RunShell<LocalConsole, StateMachine, ConnectionFSC>(conf);
1461 }
1462 else
1463*/ {
1464 if (conf.Get<int>("console")==0)
1465 return RunShell<LocalShell>(conf);
1466 else
1467 return RunShell<LocalConsole>(conf);
1468 }
1469 }
1470 /*catch (std::exception& e)
1471 {
1472 cerr << "Exception: " << e.what() << endl;
1473 return -1;
1474 }*/
1475
1476 return 0;
1477}
Note: See TracBrowser for help on using the repository browser.