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

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