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

Last change on this file since 16584 was 16413, checked in by tbretz, 12 years ago
Replaced some size() by empty() where possible.
File size: 50.5 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 "externals/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 DimDescribedService fDimCurrents;
54
55 vector<int64_t> fCurrentsAvg;
56 vector<int64_t> fCurrentsRms;
57
58 vector<float> fCalibration;
59 vector<float> fVoltGapd;
60 vector<float> fBiasVolt;
61
62 vector<vector<float>> fData;
63
64 int64_t fCursorCur;
65 uint64_t fCursorAmpl;
66 uint64_t fCursorTemp;
67
68 Time fBiasLast;
69 Time fStartTime;
70 Time fCalibTime;
71
72 valarray<double> fPV[3]; // Process variable (intgerated/averaged amplitudes)
73 valarray<double> fSP; // Set point (target amplitudes)
74
75 double fKp; // Proportional constant
76 double fKi; // Integral constant
77 double fKd; // Derivative constant
78 double fT; // Time constant (cycle time)
79 double fGain; // Gain (conversion from a DRS voltage deviation into a BIAS voltage change at G-APD reference voltage)
80
81 double fT21;
82
83 double fBiasOffset;
84 double fTempOffset;
85 double fCalibrationOffset;
86 double fAppliedOffset;
87
88 uint16_t fCurrentRequestInterval;
89 uint16_t fNumCalibIgnore;
90 uint16_t fNumCalibRequests;
91
92 bool fOutputEnabled;
93
94 int HandleCameraTemp(const EventImp &evt)
95 {
96 if (fControlType!=kTemp && fControlType!=kCurrents)
97 return GetCurrentState();
98
99 if (evt.GetSize()!=60*sizeof(float))
100 return GetCurrentState();
101
102 const float *ptr = evt.Ptr<float>();
103
104 double avgt = 0;
105 int numt = 0;
106 for (int i=1; i<32; i++)
107 if (ptr[i]!=0)
108 {
109 avgt += ptr[i];
110 numt++;
111 }
112
113 if (numt==0)
114 {
115 Warn("Received sensor temperatures all invalid.");
116 return GetCurrentState();
117 }
118
119 avgt /= numt; // [deg C]
120
121 fTempOffset = (avgt-25)*4./70; // [V]
122
123 fCursorTemp++;
124
125 return HandleCurrentControl();
126 }
127
128 int HandleCurrentControl()
129 {
130 const double dUt = fTempOffset; // [V]
131
132 if (GetCurrentState()==Feedback::State::kCalibrating && fBiasOffset>dUt-1.2)
133 {
134 fCursorTemp = 0;
135
136 ostringstream msg;
137 msg << " (applied calibration offset " << fBiasOffset << "V exceeds temperature correction " << fTempOffset << "V - 1.2V.";
138 Warn("Trying to calibrate above G-APD breakdown volatge!");
139 Warn(msg);
140 return GetCurrentState();
141 }
142
143 // FIXME: If calibrating do not wait for the temperature!
144 fAppliedOffset = fBiasOffset;
145 if (GetCurrentState()!=Feedback::State::kCalibrating)
146 fAppliedOffset += dUt;
147
148 vector<float> vec(2*BIAS::kNumChannels+2);
149 for (int i=0; i<BIAS::kNumChannels; i++)
150 vec[i+BIAS::kNumChannels] = fAppliedOffset;
151
152 vec[BIAS::kNumChannels*2] = dUt;
153 vec[BIAS::kNumChannels*2+1] = fBiasOffset;
154
155 double avg[2] = { 0, 0 };
156 double min[2] = { 90, 90 };
157 double max[2] = { -90, -90 };
158 int num[2] = { 0, 0 };
159
160 vector<double> med[2];
161 med[0].resize(416);
162 med[1].resize(416);
163
164 if (fControlType==kCurrents)
165 {
166 if (fCursorCur==0)
167 {
168 //DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
169 return GetCurrentState();
170 }
171
172 // Pixel 583: 5 31 == 191 (5) C2 B3 P3
173 // Pixel 830: 2 2 == 66 (4) C0 B8 P1
174 // Pixel 1401: 6 1 == 193 (5) C2 B4 P0
175
176 // Convert from DAC counts to uA
177 const double conv = 5000./4096;
178
179 // 3900 Ohm/n + 1000 Ohm + 1100 Ohm (with n=4 or n=5)
180 const double R[2] = { 3075, 2870 };
181
182 const float *Iavg = fCalibration.data(); // Offset at U=fCalibrationOffset
183 const float *Ravg = fCalibration.data()+BIAS::kNumChannels*2; // Measured resistance
184
185 // U0 = fCalibrationOffset
186 // dT = fAppliedVoltage
187
188 // Ifeedback = Im[i] - (U[i]-U0)/Ravg[i] - Iavg[i];
189 // dUapplied[i] + dUneu[i] = R[g] * (Im[i] - (dUapplied[i]+dUneu[i]-U0+dT)/Ravg[i] - Iavg[i])
190
191 // The assumption here is that the offset calculated from the temperature
192 // does not significanly change within a single step
193
194 // dU[i] := dUtotal[i] = dUapplied[i] + dUneu[i]
195 // dU[i] / R[g] = Im[i] - (dU[i]+dT-U0)/Ravg[i] - Iavg[i]
196 // dU[i]/R[g] + dU[i]/Ravg[i] = Im[i] + U0/Ravg[i] - dT/Ravg[i] - Iavg[i]
197 // dU[i]*(1/R[g]+1/Ravg[i]) = Im[i] - Iavg[i] + U0/Ravg[i] - dT/Ravg[i]
198 // dU[i] = (Im[i] - Iavg[i] + U0/Ravg[i] - dT/Ravg[i]) / (1/R[g]+1/Ravg[i])
199 // dU[i] = { Im[i] - Iavg[i] + (U0-dT)/Ravg[i] } * r with r := 1 / (1/R[g]+1/Ravg[i])
200
201 const double U0 = fAppliedOffset-fCalibrationOffset;
202
203 for (int i=0; i<BIAS::kNumChannels; i++)
204 {
205 const PixelMapEntry &hv = fMap.hv(i);
206 if (!hv)
207 continue;
208
209 // Average measured current
210 const double Im = double(fCurrentsAvg[i])/fCursorCur * conv; // [uA]
211
212 // Group index (0 or 1) of the of the pixel (4 or 5 pixel patch)
213 const int g = hv.group();
214
215 // Serial resistors in front of the G-APD
216 double Rg = R[g];
217
218 // This is assuming that the broken pixels have a 390 Ohm instead of 3900 Ohm serial resistor
219 if (i==66) // Pixel 830(66)
220 Rg = 2400; // 2400 = (3/3900 + 1/390) + 1000 + 1100
221 if (i==191 || i==193) // Pixel 583(191) / Pixel 1401(193)
222 Rg = 2379; // 2379 = (4/3900 + 1/390) + 1000 + 1100
223
224 const double r = 1./(1./Rg + 1./Ravg[i]); // [Ohm]
225
226 // Offset induced by the voltage above the calibration point
227 const double dI = U0/Ravg[i]; // [V/Ohm]
228
229 // Offset at the calibration point (make sure that the calibration is
230 // valid (Im[i]>Iavg[i]) and we operate above the calibration point)
231 const double I = Im>Iavg[i] ? Im - Iavg[i] : 0; // [A]
232
233 // Make sure that the averaged resistor is valid
234 const double dU = Ravg[i]>10000 ? r*(I*1e-6 - dI) : 0;
235
236 vec[i+BIAS::kNumChannels] += dU;
237
238 // Angelegte Spannung: U0+dU
239 // Gemessener Strom: Im - Iavg
240 // Strom offset: (U0+dU) / Ravg
241 // Fliessender Strom: Im-Iavg - (U0+dU)/Ravg
242 // Korrektur: [ Im-Iavg - (U0+dU)/Ravg ] * Rg
243
244 // Aufgeloest nach dU: dU = ( Im-Iavg - dU/Ravg ) / ( 1/Rg + 1/Ravg )
245 // Equivalent zu: dU = ( I*Ravg - U0 ) / ( Ravg/Rg+1 )
246
247 // Calculate statistics only for channels with a valid calibration
248 if (Iavg[i]>0)
249 {
250 med[g][num[g]] = dU;
251 avg[g] += dU;
252 num[g]++;
253
254 if (dU<min[g])
255 min[g] = dU;
256 if (dU>max[g])
257 max[g] = dU;
258 }
259 }
260
261 sort(med[0].begin(), med[0].begin()+num[0]);
262 sort(med[1].begin(), med[1].begin()+num[1]);
263
264 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
265 fCursorCur = 0;
266 }
267
268 fDimDeviation.setQuality(fControlType);
269 fDimDeviation.Update(vec);
270
271 // Warning: Here it is assumed that the ramp up and down is done properly
272 // within the time between two new temperatures and that the calibration
273 // is finished within that time.
274 if (!(GetCurrentState()==Feedback::State::kCalibrating && fCursorTemp==1 && fOutputEnabled && fDimBias.state()==BIAS::State::kVoltageOff))
275 {
276 if (!fOutputEnabled || fDimBias.state()!=BIAS::State::kVoltageOn)
277 return GetCurrentState();
278
279 // Trigger calibration
280 if (GetCurrentState()==Feedback::State::kCalibrating && fCursorTemp==2)
281 {
282 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
283 return GetCurrentState();
284 }
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 return GetCurrentState();
314 }
315
316 int AverageCurrents(const EventImp &evt)
317 {
318 if (evt.GetSize()!=BIAS::kNumChannels*sizeof(int16_t))
319 return -1;
320
321 if (fDimBias.state()!=BIAS::State::kVoltageOn)
322 return false;
323
324 if (fCursorCur++<0)
325 return true;
326
327 const int16_t *ptr = evt.Ptr<int16_t>();
328
329 for (int i=0; i<BIAS::kNumChannels; i++)
330 {
331 fCurrentsAvg[i] += ptr[i];
332 fCurrentsRms[i] += ptr[i]*ptr[i];
333 }
334
335 return true;
336 }
337
338
339 void HandleCalibration(const EventImp &evt)
340 {
341 const int rc = AverageCurrents(evt);
342 if (rc<0)
343 return;
344
345 if (fCursorCur<fNumCalibRequests)
346 {
347 if (fDimBias.state()==BIAS::State::kVoltageOn)
348 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
349 return;
350 }
351
352 if (rc==0)
353 return;
354
355 fCalibration.resize(BIAS::kNumChannels*3);
356
357 float *avg = fCalibration.data();
358 float *rms = fCalibration.data()+BIAS::kNumChannels;
359 float *res = fCalibration.data()+BIAS::kNumChannels*2;
360
361 const double conv = 5000./4096;
362
363 for (int i=0; i<BIAS::kNumChannels; i++)
364 {
365 const double I = double(fCurrentsAvg[i])/fCursorCur;
366
367 res[i] = (fVoltGapd[i]+fCalibrationOffset)/I / conv * 1e6;
368 avg[i] = conv * I;
369 rms[i] = conv * sqrt(double(fCurrentsRms[i])/fCursorCur-I*I);
370 }
371
372 fCalibTime = Time();
373
374 fDimCalibration.setData(fCalibration);
375 fDimCalibration.Update(fCalibTime);
376
377 fOutputEnabled = false;
378 fControlType = kIdle;
379
380 Info("Calibration successfully done.");
381
382 if (fDimBias.state()==BIAS::State::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::State::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::State::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 void HandleCalibrateCurrents(const EventImp &evt)
728 {
729 if (fBiasVolt.empty() || fCalibration.empty() || evt.GetSize()<416*sizeof(int16_t))
730 return;
731
732 struct dim_data {
733 float I[416];
734 float Iavg;
735 float Irms;
736 float Imed;
737 float Idev;
738 uint32_t N;
739 float Tdiff;
740
741 dim_data() { memset(this, 0, sizeof(dim_data)); }
742 } __attribute__((__packed__));
743
744 const int16_t *I = evt.Ptr<int16_t>();
745 const float *R = fCalibration.data()+BIAS::kNumChannels*2;
746 const float *U = fBiasVolt.data();
747
748 vector<float> med(416);
749 uint16_t cnt = 0;
750
751 double avg = 0;
752 double rms = 0;
753
754 dim_data data;
755 for (int i=0; i<416; i++)
756 {
757 const PixelMapEntry &hv = fMap.hv(i);
758 if (!hv)
759 continue;
760
761 if (R[i]<=0)
762 continue;
763
764 data.I[i] = I[i]*5000./4096 - U[i]/R[i]*1e6;
765 data.I[i] /= hv.group() ? 5 : 4;
766
767 avg += data.I[i];
768 rms += data.I[i]*data.I[i];
769
770 if (i>=320)
771 continue;
772
773 med[cnt++] = data.I[i];
774 }
775
776 if (cnt==0)
777 return;
778
779 avg /= cnt;
780 rms /= cnt;
781
782 data.N = cnt;
783 data.Iavg = avg;
784 data.Irms = sqrt(rms-avg*avg);
785
786 sort(med.data(), med.data()+cnt);
787
788 data.Imed = cnt%2 ? (med[cnt/2-1]+med[cnt/2])/2 : med[cnt/2];
789
790 for (int i=0; i<cnt; i++)
791 med[i] = fabs(med[i]-data.Imed);
792
793 sort(med.data(), med.data()+cnt);
794
795 data.Idev = med[uint32_t(0.682689477208650697*cnt)];
796
797 data.Tdiff = evt.GetTime().UnixTime()-fCalibTime.UnixTime();
798
799 fDimCurrents.setData(&data, sizeof(dim_data));
800 fDimCurrents.Update(evt.GetTime());
801 }
802
803 int HandleBiasCurrent(const EventImp &evt)
804 {
805 if (fControlType==kTemp && GetCurrentState()==Feedback::State::kCalibrating)
806 HandleCalibration(evt);
807
808 if (fControlType==kFeedbackGlobal || fControlType==kCurrents)
809 AverageCurrents(evt);
810
811 /*
812 if (fControlType==kCurrents && fCursorTemp>0 && fCursorCur>0)
813 {
814 // fCursorTemp: 1 2 3 4 5 6 7 8
815 // fCursor%x: 1 1 1 2 2 2 3 3 // 9 steps in ~15s
816 //if (fCursorTemp<3 && fCursorCur%(fCursorTemp/3+1)==0)
817 HandleCurrentControl();
818 }*/
819
820 HandleCalibrateCurrents(evt);
821
822 return GetCurrentState();
823 }
824
825 int HandleBiasData(const EventImp &evt)
826 {
827 if (fControlType==kFeedback)
828 HandleFeedback(evt);
829
830 if (fControlType==kFeedbackGlobal)
831 HandleGlobalFeedback(evt);
832
833 return GetCurrentState();
834 }
835
836 int HandleBiasNom(const EventImp &evt)
837 {
838 if (evt.GetSize()>=416*sizeof(float))
839 {
840 fVoltGapd.assign(evt.Ptr<float>(), evt.Ptr<float>()+416);
841 Info("Nominal bias voltages received.");
842 }
843
844 return GetCurrentState();
845 }
846
847 int HandleBiasVoltage(const EventImp &evt)
848 {
849 if (evt.GetSize()>=416*sizeof(float))
850 fBiasVolt.assign(evt.Ptr<float>(), evt.Ptr<float>()+416);
851 return GetCurrentState();
852 }
853
854 bool CheckEventSize(size_t has, const char *name, size_t size)
855 {
856 if (has==size)
857 return true;
858
859 ostringstream msg;
860 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
861 Fatal(msg);
862 return false;
863 }
864
865 int Print() const
866 {
867 Out() << fDim << endl;
868 Out() << fDimFAD << endl;
869 Out() << fDimFSC << endl;
870 Out() << fDimBias << endl;
871
872 return GetCurrentState();
873 }
874
875 int PrintCalibration()
876 {
877 if (fCalibration.empty())
878 {
879 Out() << "No calibration performed so far." << endl;
880 return GetCurrentState();
881 }
882
883 const float *avg = fCalibration.data();
884 const float *rms = fCalibration.data()+BIAS::kNumChannels;
885 const float *res = fCalibration.data()+BIAS::kNumChannels*2;
886
887 Out() << "Average current at " << fCalibrationOffset << "V below G-APD operation voltage:\n";
888
889 for (int k=0; k<13; k++)
890 for (int j=0; j<8; j++)
891 {
892 Out() << setw(2) << k << "|" << setw(2) << j*4 << "|";
893 for (int i=0; i<4; i++)
894 Out() << Tools::Form(" %6.1f+-%4.1f", avg[k*32+j*4+i], rms[k*32+j*4+i]);
895 Out() << '\n';
896 }
897 Out() << '\n';
898
899 Out() << "Measured calibration resistor:\n";
900 for (int k=0; k<13; k++)
901 for (int j=0; j<4; j++)
902 {
903 Out() << setw(2) << k << "|" << setw(2) << j*8 << "|";
904 for (int i=0; i<8; i++)
905 Out() << Tools::Form(" %5.0f", res[k*32+j*8+i]);
906 Out() << '\n';
907 }
908
909 Out() << flush;
910
911 return GetCurrentState();
912 }
913
914 void WarnState(bool needfsc, bool needfad)
915 {
916 const bool bias = fDimBias.state() >= BIAS::State::kConnecting;
917 const bool fsc = fDimFSC.state() >= FSC::State::kConnected;
918 const bool fad = fDimFAD.state() >= FAD::State::kConnected;
919
920 if (!bias)
921 Warn("Bias control not yet ready.");
922 if (needfsc && !fsc)
923 Warn("FSC control not yet ready.");
924 if (needfad && !fad)
925 Warn("FAD control not yet ready.");
926 }
927
928 int SetConstant(const EventImp &evt, int constant)
929 {
930 if (!CheckEventSize(evt.GetSize(), "SetConstant", 8))
931 return kSM_FatalError;
932
933 switch (constant)
934 {
935 case 0: fKi = evt.GetDouble(); break;
936 case 1: fKp = evt.GetDouble(); break;
937 case 2: fKd = evt.GetDouble(); break;
938 case 3: fT = evt.GetDouble(); break;
939 case 4: fGain = evt.GetDouble(); break;
940 default:
941 Fatal("SetConstant got an unexpected constant id -- this is a program bug!");
942 return kSM_FatalError;
943 }
944
945 return GetCurrentState();
946 }
947
948 int EnableOutput(const EventImp &evt)
949 {
950 if (!CheckEventSize(evt.GetSize(), "EnableOutput", 1))
951 return kSM_FatalError;
952
953 fOutputEnabled = evt.GetBool();
954
955 if (fControlType==kCurrents)
956 if (fCursorTemp>1)
957 fCursorTemp = 1;
958
959 return GetCurrentState();
960 }
961
962 void ResetData(int16_t n=-1)
963 {
964 fData.assign(n>0 ? n : fData.size(), vector<float>(0));
965
966 fCursorAmpl = 0;
967 fCursorCur = 0;
968 fCursorTemp = 0;
969
970 fStartTime = Time();
971
972 fSP = valarray<double>(0., BIAS::kNumChannels);
973
974 vector<float> vec(2*BIAS::kNumChannels+2, fBiasOffset);
975 vec[2*BIAS::kNumChannels] = 0;
976 fDimDeviation.setQuality(kIdle);
977 fDimDeviation.Update(vec);
978
979 fPV[0].resize(0);
980 fPV[1].resize(0);
981 fPV[2].resize(0);
982
983 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
984 fCurrentsRms.assign(BIAS::kNumChannels, 0);
985
986 if (fKp==0 && fKi==0 && fKd==0)
987 Warn("Control loop parameters are all set to zero.");
988 }
989
990 int StartFeedback(const EventImp &evt)
991 {
992 if (!CheckEventSize(evt.GetSize(), "StartFeedback", 2))
993 return kSM_FatalError;
994
995 WarnState(false, true);
996
997 fBiasOffset = 0;
998 ResetData(evt.GetShort());
999
1000 fControlType = kFeedback;
1001
1002 return GetCurrentState();
1003 }
1004
1005 int StartFeedbackGlobal(const EventImp &evt)
1006 {
1007 if (!CheckEventSize(evt.GetSize(), "StartFeedbackGlobal", 2))
1008 return kSM_FatalError;
1009
1010 WarnState(false, true);
1011
1012 fBiasOffset = 0;
1013 ResetData(evt.GetShort());
1014
1015 fControlType = kFeedbackGlobal;
1016
1017 return GetCurrentState();
1018 }
1019
1020 int StartTempCtrl(const EventImp &evt)
1021 {
1022 if (!CheckEventSize(evt.GetSize(), "StartTempCtrl", 4))
1023 return kSM_FatalError;
1024
1025 WarnState(true, false);
1026
1027 fBiasOffset = evt.GetFloat();
1028 fControlType = kTemp;
1029
1030 ostringstream out;
1031 out << "Starting temperature feedback with an offset of " << fBiasOffset << "V";
1032 Message(out);
1033
1034 if (fDimBias.state()==BIAS::State::kVoltageOn)
1035 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
1036
1037 return GetCurrentState();
1038 }
1039
1040 int StartCurrentCtrl(const EventImp &evt)
1041 {
1042 if (!CheckEventSize(evt.GetSize(), "StartCurrentCtrl", 4))
1043 return kSM_FatalError;
1044
1045 if (fCalibration.empty())
1046 {
1047 Warn("Current control needs a bias crate calibration first... command ignored.");
1048 return GetCurrentState();
1049 }
1050
1051 WarnState(true, false);
1052
1053 fBiasOffset = evt.GetFloat();
1054 fTempOffset = -3;
1055 ResetData(0);
1056 fControlType = kCurrents;
1057
1058 ostringstream out;
1059 out << "Starting current/temp feedback with an offset of " << fBiasOffset << "V";
1060 Message(out);
1061
1062 return GetCurrentState();
1063 }
1064
1065 int StopFeedback()
1066 {
1067 fControlType = kIdle;
1068
1069 return GetCurrentState();
1070 }
1071
1072 int StoreReference()
1073 {
1074 if (!fPV[0].size() && !fPV[1].size() && !fPV[2].size())
1075 {
1076 Warn("No values in memory. Take enough events first!");
1077 return GetCurrentState();
1078 }
1079
1080 // FIXME: Check age
1081
1082 if (!fPV[1].size() && !fPV[2].size())
1083 fSP = fPV[0];
1084
1085 if (!fPV[2].size())
1086 fSP = fPV[1];
1087 else
1088 fSP = fPV[2];
1089
1090 vector<float> vec(BIAS::kNumChannels);
1091 for (int i=0; i<BIAS::kNumChannels; i++)
1092 vec[i] = fSP[i];
1093 fDimReference.Update(vec);
1094
1095 return GetCurrentState();
1096 }
1097
1098 int SetReference(const EventImp &evt)
1099 {
1100 if (!CheckEventSize(evt.GetSize(), "SetReference", 4))
1101 return kSM_FatalError;
1102
1103 const float val = evt.GetFloat();
1104 /*
1105 if (!fPV[0].size() && !fPV[1].size() && !fPV[2].size())
1106 {
1107 Warn("No values in memory. Take enough events first!");
1108 return GetCurrentState();
1109 }*/
1110
1111 vector<float> vec(BIAS::kNumChannels);
1112 for (int i=0; i<BIAS::kNumChannels; i++)
1113 vec[i] = fSP[i] = val;
1114 fDimReference.Update(vec);
1115
1116 Out() << "New global reference value: " << val << "mV" << endl;
1117
1118 return GetCurrentState();
1119 }
1120
1121 int CalibrateCurrents()
1122 {
1123// if (!CheckEventSize(evt.GetSize(), "StartTempCtrl", 4))
1124// return kSM_FatalError;
1125
1126 if (fDimBias.state()==BIAS::State::kRamping)
1127 {
1128 Warn("Calibration cannot be started when biasctrl is in state Ramping.");
1129 return GetCurrentState();
1130 }
1131
1132 if (fVoltGapd.empty())
1133 {
1134 Error("No G-APD reference voltages received yet (BIAS_CONTROL/NOMINAL).");
1135 return GetCurrentState();
1136 }
1137
1138 WarnState(true, false);
1139
1140 ostringstream out;
1141 out << "Starting temperature feedback for calibration with an offset of " << fCalibrationOffset << "V";
1142 Message(out);
1143
1144 fBiasOffset = fCalibrationOffset;
1145 fControlType = kTemp;
1146 fCursorCur = -fNumCalibIgnore;
1147 fCursorTemp = 0;
1148 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
1149 fCurrentsRms.assign(BIAS::kNumChannels, 0);
1150 fCalibration.resize(0);
1151 fStartTime = Time();
1152 fOutputEnabled = true;
1153
1154 return Feedback::State::kCalibrating;
1155 }
1156
1157 int SetCurrentRequestInterval(const EventImp &evt)
1158 {
1159 if (!CheckEventSize(evt.GetSize(), "SetCurrentRequestInterval", 2))
1160 return kSM_FatalError;
1161
1162 fCurrentRequestInterval = evt.GetUShort();
1163
1164 Out() << "New current request interval: " << fCurrentRequestInterval << "ms" << endl;
1165
1166 return GetCurrentState();
1167 }
1168
1169 int Execute()
1170 {
1171 // Dispatch (execute) at most one handler from the queue. In contrary
1172 // to run_one(), it doesn't wait until a handler is available
1173 // which can be dispatched, so poll_one() might return with 0
1174 // handlers dispatched. The handlers are always dispatched/executed
1175 // synchronously, i.e. within the call to poll_one()
1176 //poll_one();
1177
1178 if (!fDim.online())
1179 return Feedback::State::kDimNetworkNA;
1180
1181 const bool bias = fDimBias.state() >= BIAS::State::kConnecting;
1182 const bool fad = fDimFAD.state() >= FAD::State::kConnected;
1183 const bool fsc = fDimFSC.state() >= FSC::State::kConnected;
1184
1185 // All subsystems are not connected
1186 if (!bias && !fad && !fsc)
1187 return Feedback::State::kDisconnected;
1188
1189 // At least one subsystem apart from bias is connected
1190 if (bias && !fad && !fsc)
1191 return Feedback::State::kConnecting;
1192
1193/*
1194 // All subsystems are connected
1195 if (GetCurrentStatus()==Feedback::State::kConfiguringStep1)
1196 {
1197 if (fCursor<1)
1198 return Feedback::State::kConfiguringStep1;
1199
1200 if (fCursor==1)
1201 {
1202 fStartTime = Time();
1203 return Feedback::State::kConfiguringStep2;
1204 }
1205 }
1206 if (GetCurrentStatus()==Feedback::State::kConfiguringStep2)
1207 {
1208 if (fCursor==1)
1209 {
1210 if ((Time()-fStartTime).total_microseconds()/1000000.<1.5)
1211 return Feedback::State::kConfiguringStep2;
1212
1213 Dim::SendCommand("BIAS_CONTROL/REQUEST_STATUS");
1214 }
1215 if (fCursor==2)
1216 {
1217
1218 int n=0;
1219 double avg = 0;
1220 for (size_t i=0; i<fCurrents.size(); i++)
1221 if (fCurrents[i]>=0)
1222 {
1223 avg += fCurrents[i];
1224 n++;
1225 }
1226
1227 cout << avg/n << endl;
1228 }
1229 return Feedback::State::kConnected;
1230 }
1231 */
1232
1233 // Needs connection of FAD and BIAS
1234 if (bias && fad)
1235 {
1236 if (fControlType==kFeedback || fControlType==kFeedbackGlobal)
1237 return fOutputEnabled ? Feedback::State::kFeedbackCtrlRunning : Feedback::State::kFeedbackCtrlIdle;
1238 }
1239
1240 // Needs connection of FSC and BIAS
1241 if (bias && fsc)
1242 {
1243 if (fControlType==kTemp)
1244 {
1245 if (GetCurrentState()==Feedback::State::kCalibrating && fCursorCur<fNumCalibRequests)
1246 return GetCurrentState();
1247
1248 return fOutputEnabled ? Feedback::State::kTempCtrlRunning : Feedback::State::kTempCtrlIdle;
1249 }
1250 if (fControlType==kCurrents)
1251 {
1252 static Time past;
1253 if (fCurrentRequestInterval>0 && Time()-past>boost::posix_time::milliseconds(fCurrentRequestInterval))
1254 {
1255 if (fDimBias.state()==BIAS::State::kVoltageOn)
1256 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
1257 past = Time();
1258 }
1259
1260 return fOutputEnabled && fCursorTemp>0 ? Feedback::State::kCurrentCtrlRunning : Feedback::State::kCurrentCtrlIdle;
1261 }
1262 }
1263
1264 if (bias && fad && !fsc)
1265 return Feedback::State::kConnectedFAD;
1266
1267 if (bias && fsc && !fad)
1268 return Feedback::State::kConnectedFSC;
1269
1270 return Feedback::State::kConnected;
1271 }
1272
1273public:
1274 StateMachineFeedback(ostream &out=cout) : StateMachineDim(out, "FEEDBACK"),
1275 //---
1276 fDimFAD("FAD_CONTROL"),
1277 fDimFSC("FSC_CONTROL"),
1278 fDimBias("BIAS_CONTROL"),
1279 //---
1280 fDimReference("FEEDBACK/REFERENCE", "F:416",
1281 "Amplitude reference value(s)"
1282 "Vref[mV]:Amplitude reference"),
1283 fDimDeviation("FEEDBACK/DEVIATION", "F:416;F:416;F:1;F:1",
1284 "Control loop information"
1285 "|DeltaAmpl[mV]:Amplitude offset measures"
1286 "|DeltaBias[mV]:Correction value calculated"
1287 "|DeltaTemp[mV]:Correction calculated from temperature"
1288 "|DeltaUser[mV]:Additional offset specified by user"),
1289 fDimCalibration("FEEDBACK/CALIBRATION", "F:416;F:416;F:416",
1290 "Current offsets"
1291 "|Avg[uA]:Average offset"
1292 "|Rms[uA]:Rms of offset"
1293 "|R[Ohm]:Measured calibration resistor"),
1294 fDimCurrents("FEEDBACK/CALIBRATED_CURRENTS", "F:416;F:1;F:1;F:1;F:1;I:1;F:1",
1295 "Calibrated currents"
1296 "|I[uA]:Calibrated currents"
1297 "|I_avg[uA]:Average calibrated current (320 channels)"
1298 "|I_rms[uA]:Rms of calibrated current (320 channels)"
1299 "|I_med[uA]:Median calibrated current (320 channels)"
1300 "|I_dev[uA]:Deviation of calibrated current (320 channels)"
1301 "|N[uint16]:Number of valid values"
1302 "|T_diff[s]:Time difference to calibration"),
1303 fSP(BIAS::kNumChannels),
1304 fKp(0), fKi(0), fKd(0), fT(-1),
1305 fCalibrationOffset(-3),
1306 fCurrentRequestInterval(0),
1307 fNumCalibIgnore(30),
1308 fNumCalibRequests(300),
1309 fOutputEnabled(false)
1310 {
1311 // ba::io_service::work is a kind of keep_alive for the loop.
1312 // It prevents the io_service to go to stopped state, which
1313 // would prevent any consecutive calls to run()
1314 // or poll() to do nothing. reset() could also revoke to the
1315 // previous state but this might introduce some overhead of
1316 // deletion and creation of threads and more.
1317
1318 fDim.Subscribe(*this);
1319 fDimFAD.Subscribe(*this);
1320 fDimFSC.Subscribe(*this);
1321 fDimBias.Subscribe(*this);
1322
1323 Subscribe("BIAS_CONTROL/CURRENT")
1324 (bind(&StateMachineFeedback::HandleBiasCurrent, this, placeholders::_1));
1325 Subscribe("BIAS_CONTROL/VOLTAGE")
1326 (bind(&StateMachineFeedback::HandleBiasVoltage, this, placeholders::_1));
1327 Subscribe("BIAS_CONTROL/FEEDBACK_DATA")
1328 (bind(&StateMachineFeedback::HandleBiasData, this, placeholders::_1));
1329 Subscribe("BIAS_CONTROL/NOMINAL")
1330 (bind(&StateMachineFeedback::HandleBiasNom, this, placeholders::_1));
1331 Subscribe("FSC_CONTROL/TEMPERATURE")
1332 (bind(&StateMachineFeedback::HandleCameraTemp, this, placeholders::_1));
1333
1334 // State names
1335 AddStateName(Feedback::State::kDimNetworkNA, "DimNetworkNotAvailable",
1336 "The Dim DNS is not reachable.");
1337
1338 AddStateName(Feedback::State::kDisconnected, "Disconnected",
1339 "The Dim DNS is reachable, but the required subsystems are not available.");
1340
1341 AddStateName(Feedback::State::kConnecting, "Connecting",
1342 "Only biasctrl is available and connected with its hardware.");
1343
1344 AddStateName(Feedback::State::kConnectedFSC, "ConnectedFSC",
1345 "biasctrl and fscctrl are available and connected with their hardware.");
1346 AddStateName(Feedback::State::kConnectedFAD, "ConnectedFAD",
1347 "biasctrl and fadctrl are available and connected with their hardware.");
1348 AddStateName(Feedback::State::kConnected, "Connected",
1349 "biasctrl, fadctrl and fscctrl are available and connected with their hardware.");
1350
1351 AddStateName(Feedback::State::kFeedbackCtrlIdle, "FeedbackIdle",
1352 "Feedback control activated, but voltage output disabled.");
1353 AddStateName(Feedback::State::kTempCtrlIdle, "TempCtrlIdle",
1354 "Temperature control activated, but voltage output disabled.");
1355 AddStateName(Feedback::State::kCurrentCtrlIdle, "CurrentCtrlIdle",
1356 "Current control activated, but voltage output disabled.");
1357
1358 AddStateName(Feedback::State::kFeedbackCtrlRunning, "FeedbackControl",
1359 "Feedback control activated and voltage output enabled.");
1360 AddStateName(Feedback::State::kTempCtrlRunning, "TempControl",
1361 "Temperature control activated and voltage output enabled.");
1362 AddStateName(Feedback::State::kCurrentCtrlRunning, "CurrentControl",
1363 "Current/Temp control activated and voltage output enabled.");
1364 AddStateName(Feedback::State::kCalibrating, "Calibrating",
1365 "Calibrating current offsets.");
1366
1367 AddEvent("START_FEEDBACK_CONTROL", "S:1", Feedback::State::kConnectedFAD, Feedback::State::kConnected)
1368 (bind(&StateMachineFeedback::StartFeedback, this, placeholders::_1))
1369 ("Start the feedback control loop"
1370 "|Num[short]:Number of events 'medianed' to calculate the correction value");
1371
1372 AddEvent("START_GLOBAL_FEEDBACK", "S:1", Feedback::State::kConnectedFAD, Feedback::State::kConnected)
1373 (bind(&StateMachineFeedback::StartFeedbackGlobal, this, placeholders::_1))
1374 ("Start the global feedback control loop"
1375 "Num[short]:Number of events averaged to calculate the correction value");
1376
1377 AddEvent("START_TEMP_CONTROL", "F:1", Feedback::State::kConnectedFSC, Feedback::State::kConnected)
1378 (bind(&StateMachineFeedback::StartTempCtrl, this, placeholders::_1))
1379 ("Start the temperature control loop"
1380 "|offset[V]:Offset from the nominal temperature corrected value in Volts");
1381
1382 AddEvent("START_CURRENT_CONTROL", "F:1", Feedback::State::kConnectedFSC, Feedback::State::kConnected)
1383 (bind(&StateMachineFeedback::StartCurrentCtrl, this, placeholders::_1))
1384 ("Start the current/temperature control loop"
1385 "|offset[V]:Offset from the nominal current/temperature corrected value in Volts");
1386
1387 // Feedback::State::kTempCtrlIdle, Feedback::State::kFeedbackCtrlIdle, Feedback::State::kTempCtrlRunning, Feedback::State::kFeedbackCtrlRunning
1388 AddEvent("STOP")
1389 (bind(&StateMachineFeedback::StopFeedback, this))
1390 ("Stop any control loop");
1391
1392 AddEvent("ENABLE_OUTPUT", "B:1")//, Feedback::State::kIdle)
1393 (bind(&StateMachineFeedback::EnableOutput, this, placeholders::_1))
1394 ("Enable sending of correction values caluclated by the control loop to the biasctrl");
1395
1396 AddEvent("STORE_REFERENCE")//, Feedback::State::kIdle)
1397 (bind(&StateMachineFeedback::StoreReference, this))
1398 ("Store the last (averaged) value as new reference (for debug purpose only)");
1399
1400 AddEvent("SET_REFERENCE", "F:1")//, Feedback::State::kIdle)
1401 (bind(&StateMachineFeedback::SetReference, this, placeholders::_1))
1402 ("Set a new global reference value (for debug purpose only)");
1403
1404 AddEvent("SET_Ki", "D:1")//, Feedback::State::kIdle)
1405 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 0))
1406 ("Set integral constant Ki");
1407
1408 AddEvent("SET_Kp", "D:1")//, Feedback::State::kIdle)
1409 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 1))
1410 ("Set proportional constant Kp");
1411
1412 AddEvent("SET_Kd", "D:1")//, Feedback::State::kIdle)
1413 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 2))
1414 ("Set derivative constant Kd");
1415
1416 AddEvent("SET_T", "D:1")//, Feedback::State::kIdle)
1417 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 3))
1418 ("Set time-constant. (-1 to use the cycle time, i.e. the time for the last average cycle, instead)");
1419
1420 AddEvent("CALIBRATE_CURRENTS", Feedback::State::kConnectedFSC, Feedback::State::kConnected)//, Feedback::State::kIdle)
1421 (bind(&StateMachineFeedback::CalibrateCurrents, this))
1422 ("");
1423
1424 AddEvent("SET_CURRENT_REQUEST_INTERVAL", Feedback::State::kConnectedFSC, Feedback::State::kConnected)//, Feedback::State::kIdle)
1425 (bind(&StateMachineFeedback::SetCurrentRequestInterval, this, placeholders::_1))
1426 ("|interval[ms]:Interval between two current requests in modes which need that.");
1427
1428 // Verbosity commands
1429// AddEvent("SET_VERBOSE", "B:1")
1430// (bind(&StateMachineMCP::SetVerbosity, this, placeholders::_1))
1431// ("set verbosity state"
1432// "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
1433
1434 AddEvent("PRINT")
1435 (bind(&StateMachineFeedback::Print, this))
1436 ("");
1437
1438 AddEvent("PRINT_CALIBRATION")
1439 (bind(&StateMachineFeedback::PrintCalibration, this))
1440 ("");
1441 }
1442
1443 int EvalOptions(Configuration &conf)
1444 {
1445 if (!fMap.Read(conf.Get<string>("pixel-map-file")))
1446 {
1447 Error("Reading mapping table from "+conf.Get<string>("pixel-map-file")+" failed.");
1448 return 1;
1449 }
1450
1451 fGain = 0.1; // V(Amplitude) / V(Bias)
1452
1453 // 148 -> 248
1454
1455 // 33 : 10s < 2%
1456 // 50 : 5s < 2%
1457 // 66 : 3s < 2%
1458 // 85 : 2s < 2%
1459
1460 fKp = 0;
1461 fKd = 0;
1462 fKi = 0.75;
1463 fT = 1;
1464
1465 // Is that independent of the aboslute real amplitude of
1466 // the light pulser?
1467
1468 ostringstream msg;
1469 msg << "Control loop parameters: ";
1470 msg << "Kp=" << fKp << ", Kd=" << fKd << ", Ki=" << fKi << ", ";
1471 if (fT>0)
1472 msg << fT;
1473 else
1474 msg << "<auto>";
1475 msg << ", Gain(DRS/BIAS)=" << fGain << "V/V";
1476
1477 Message(msg);
1478
1479 fCurrentRequestInterval = conf.Get<uint16_t>("current-request-interval");
1480 fNumCalibIgnore = conf.Get<uint16_t>("num-calib-ignore");
1481 fNumCalibRequests = conf.Get<uint16_t>("num-calib-average");
1482 fCalibrationOffset = conf.Get<float>("calibration-offset");
1483
1484 return -1;
1485 }
1486};
1487
1488// ------------------------------------------------------------------------
1489
1490#include "Main.h"
1491
1492template<class T>
1493int RunShell(Configuration &conf)
1494{
1495 return Main::execute<T, StateMachineFeedback>(conf);
1496}
1497
1498void SetupConfiguration(Configuration &conf)
1499{
1500 po::options_description control("Feedback options");
1501 control.add_options()
1502 ("pixel-map-file", var<string>()->required(), "Pixel mapping file. Used here to get the default reference voltage.")
1503 ("current-request-interval", var<uint16_t>(1000), "Interval between two current requests.")
1504 ("num-calib-ignore", var<uint16_t>(30), "Number of current requests to be ignored before averaging")
1505 ("num-calib-average", var<uint16_t>(300), "Number of current requests to be averaged")
1506 ("calibration-offset", var<float>(-3), "Absolute offset relative to the G-APD operation voltage when calibrating")
1507 ;
1508
1509 conf.AddOptions(control);
1510}
1511
1512/*
1513 Extract usage clause(s) [if any] for SYNOPSIS.
1514 Translators: "Usage" and "or" here are patterns (regular expressions) which
1515 are used to match the usage synopsis in program output. An example from cp
1516 (GNU coreutils) which contains both strings:
1517 Usage: cp [OPTION]... [-T] SOURCE DEST
1518 or: cp [OPTION]... SOURCE... DIRECTORY
1519 or: cp [OPTION]... -t DIRECTORY SOURCE...
1520 */
1521void PrintUsage()
1522{
1523 cout <<
1524 "The feedback control the BIAS voltages based on the calibration signal.\n"
1525 "\n"
1526 "The default is that the program is started without user intercation. "
1527 "All actions are supposed to arrive as DimCommands. Using the -c "
1528 "option, a local shell can be initialized. With h or help a short "
1529 "help message about the usuage can be brought to the screen.\n"
1530 "\n"
1531 "Usage: feedback [-c type] [OPTIONS]\n"
1532 " or: feedback [OPTIONS]\n";
1533 cout << endl;
1534}
1535
1536void PrintHelp()
1537{
1538 Main::PrintHelp<StateMachineFeedback>();
1539
1540 /* Additional help text which is printed after the configuration
1541 options goes here */
1542
1543 /*
1544 cout << "bla bla bla" << endl << endl;
1545 cout << endl;
1546 cout << "Environment:" << endl;
1547 cout << "environment" << endl;
1548 cout << endl;
1549 cout << "Examples:" << endl;
1550 cout << "test exam" << endl;
1551 cout << endl;
1552 cout << "Files:" << endl;
1553 cout << "files" << endl;
1554 cout << endl;
1555 */
1556}
1557
1558int main(int argc, const char* argv[])
1559{
1560 Configuration conf(argv[0]);
1561 conf.SetPrintUsage(PrintUsage);
1562 Main::SetupConfiguration(conf);
1563 SetupConfiguration(conf);
1564
1565 if (!conf.DoParse(argc, argv, PrintHelp))
1566 return 127;
1567
1568 //try
1569 {
1570 // No console access at all
1571 if (!conf.Has("console"))
1572 {
1573// if (conf.Get<bool>("no-dim"))
1574// return RunShell<LocalStream, StateMachine, ConnectionFSC>(conf);
1575// else
1576 return RunShell<LocalStream>(conf);
1577 }
1578 // Cosole access w/ and w/o Dim
1579/* if (conf.Get<bool>("no-dim"))
1580 {
1581 if (conf.Get<int>("console")==0)
1582 return RunShell<LocalShell, StateMachine, ConnectionFSC>(conf);
1583 else
1584 return RunShell<LocalConsole, StateMachine, ConnectionFSC>(conf);
1585 }
1586 else
1587*/ {
1588 if (conf.Get<int>("console")==0)
1589 return RunShell<LocalShell>(conf);
1590 else
1591 return RunShell<LocalConsole>(conf);
1592 }
1593 }
1594 /*catch (std::exception& e)
1595 {
1596 cerr << "Exception: " << e.what() << endl;
1597 return -1;
1598 }*/
1599
1600 return 0;
1601}
Note: See TracBrowser for help on using the repository browser.