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

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