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

Last change on this file since 15019 was 15019, checked in by tbretz, 12 years ago
Added Dim service with calibrated currents.
File size: 50.4 KB
Line 
1#include <valarray>
2
3#include "Dim.h"
4#include "Event.h"
5#include "Shell.h"
6#include "StateMachineDim.h"
7#include "Connection.h"
8#include "Configuration.h"
9#include "Console.h"
10#include "Converter.h"
11#include "PixelMap.h"
12
13#include "tools.h"
14
15#include "LocalControl.h"
16
17#include "HeadersFAD.h"
18#include "HeadersFSC.h"
19#include "HeadersBIAS.h"
20#include "HeadersFeedback.h"
21
22#include "DimState.h"
23#include "DimDescriptionService.h"
24
25using namespace std;
26
27// ------------------------------------------------------------------------
28
29class StateMachineFeedback : public StateMachineDim
30{
31private:
32 enum control_t
33 {
34 kIdle,
35 kTemp,
36 kFeedback,
37 kFeedbackGlobal,
38 kCurrents,
39 };
40
41 control_t fControlType;
42
43 PixelMap fMap;
44
45 DimVersion fDim;
46 DimDescribedState fDimFAD;
47 DimDescribedState fDimFSC;
48 DimDescribedState fDimBias;
49
50 DimDescribedService fDimReference;
51 DimDescribedService fDimDeviation;
52 DimDescribedService fDimCalibration;
53 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.size()==0 || fCalibration.size()==0)
730 return;
731
732 struct dim_data {
733 float I[416];
734 float Iavg;
735 float Irms;
736 float Imed;
737 float Idev;
738 uint16_t N;
739 float Tdiff;
740
741 dim_data() : Iavg(0), Irms(0), Imed(0), Idev(0), N(0), Tdiff(0) { memset(I, 0, sizeof(float)*416); }
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 fVoltGapd.assign(evt.Ptr<float>(), evt.Ptr<float>()+416);
839
840 Info("Nominal bias voltages received.");
841
842 return GetCurrentState();
843 }
844
845 int HandleBiasVoltage(const EventImp &evt)
846 {
847 fBiasVolt.assign(evt.Ptr<float>(), evt.Ptr<float>()+416);
848 return GetCurrentState();
849 }
850
851 bool CheckEventSize(size_t has, const char *name, size_t size)
852 {
853 if (has==size)
854 return true;
855
856 ostringstream msg;
857 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
858 Fatal(msg);
859 return false;
860 }
861
862 int Print() const
863 {
864 Out() << fDim << endl;
865 Out() << fDimFAD << endl;
866 Out() << fDimFSC << endl;
867 Out() << fDimBias << endl;
868
869 return GetCurrentState();
870 }
871
872 int PrintCalibration()
873 {
874 if (fCalibration.size()==0)
875 {
876 Out() << "No calibration performed so far." << endl;
877 return GetCurrentState();
878 }
879
880 const float *avg = fCalibration.data();
881 const float *rms = fCalibration.data()+BIAS::kNumChannels;
882 const float *res = fCalibration.data()+BIAS::kNumChannels*2;
883
884 Out() << "Average current at " << fCalibrationOffset << "V below G-APD operation voltage:\n";
885
886 for (int k=0; k<13; k++)
887 for (int j=0; j<8; j++)
888 {
889 Out() << setw(2) << k << "|" << setw(2) << j*4 << "|";
890 for (int i=0; i<4; i++)
891 Out() << Tools::Form(" %6.1f+-%4.1f", avg[k*32+j*4+i], rms[k*32+j*4+i]);
892 Out() << '\n';
893 }
894 Out() << '\n';
895
896 Out() << "Measured calibration resistor:\n";
897 for (int k=0; k<13; k++)
898 for (int j=0; j<4; j++)
899 {
900 Out() << setw(2) << k << "|" << setw(2) << j*8 << "|";
901 for (int i=0; i<8; i++)
902 Out() << Tools::Form(" %5.0f", res[k*32+j*8+i]);
903 Out() << '\n';
904 }
905
906 Out() << flush;
907
908 return GetCurrentState();
909 }
910
911 void WarnState(bool needfsc, bool needfad)
912 {
913 const bool bias = fDimBias.state() >= BIAS::State::kConnecting;
914 const bool fsc = fDimFSC.state() >= FSC::State::kConnected;
915 const bool fad = fDimFAD.state() >= FAD::State::kConnected;
916
917 if (!bias)
918 Warn("Bias control not yet ready.");
919 if (needfsc && !fsc)
920 Warn("FSC control not yet ready.");
921 if (needfad && !fad)
922 Warn("FAD control not yet ready.");
923 }
924
925 int SetConstant(const EventImp &evt, int constant)
926 {
927 if (!CheckEventSize(evt.GetSize(), "SetConstant", 8))
928 return kSM_FatalError;
929
930 switch (constant)
931 {
932 case 0: fKi = evt.GetDouble(); break;
933 case 1: fKp = evt.GetDouble(); break;
934 case 2: fKd = evt.GetDouble(); break;
935 case 3: fT = evt.GetDouble(); break;
936 case 4: fGain = evt.GetDouble(); break;
937 default:
938 Fatal("SetConstant got an unexpected constant id -- this is a program bug!");
939 return kSM_FatalError;
940 }
941
942 return GetCurrentState();
943 }
944
945 int EnableOutput(const EventImp &evt)
946 {
947 if (!CheckEventSize(evt.GetSize(), "EnableOutput", 1))
948 return kSM_FatalError;
949
950 fOutputEnabled = evt.GetBool();
951
952 if (fControlType==kCurrents)
953 if (fCursorTemp>1)
954 fCursorTemp = 1;
955
956 return GetCurrentState();
957 }
958
959 void ResetData(int16_t n=-1)
960 {
961 fData.assign(n>0 ? n : fData.size(), vector<float>(0));
962
963 fCursorAmpl = 0;
964 fCursorCur = 0;
965 fCursorTemp = 0;
966
967 fStartTime = Time();
968
969 fSP = valarray<double>(0., BIAS::kNumChannels);
970
971 vector<float> vec(2*BIAS::kNumChannels+2, fBiasOffset);
972 vec[2*BIAS::kNumChannels] = 0;
973 fDimDeviation.setQuality(kIdle);
974 fDimDeviation.Update(vec);
975
976 fPV[0].resize(0);
977 fPV[1].resize(0);
978 fPV[2].resize(0);
979
980 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
981 fCurrentsRms.assign(BIAS::kNumChannels, 0);
982
983 if (fKp==0 && fKi==0 && fKd==0)
984 Warn("Control loop parameters are all set to zero.");
985 }
986
987 int StartFeedback(const EventImp &evt)
988 {
989 if (!CheckEventSize(evt.GetSize(), "StartFeedback", 2))
990 return kSM_FatalError;
991
992 WarnState(false, true);
993
994 fBiasOffset = 0;
995 ResetData(evt.GetShort());
996
997 fControlType = kFeedback;
998
999 return GetCurrentState();
1000 }
1001
1002 int StartFeedbackGlobal(const EventImp &evt)
1003 {
1004 if (!CheckEventSize(evt.GetSize(), "StartFeedbackGlobal", 2))
1005 return kSM_FatalError;
1006
1007 WarnState(false, true);
1008
1009 fBiasOffset = 0;
1010 ResetData(evt.GetShort());
1011
1012 fControlType = kFeedbackGlobal;
1013
1014 return GetCurrentState();
1015 }
1016
1017 int StartTempCtrl(const EventImp &evt)
1018 {
1019 if (!CheckEventSize(evt.GetSize(), "StartTempCtrl", 4))
1020 return kSM_FatalError;
1021
1022 WarnState(true, false);
1023
1024 fBiasOffset = evt.GetFloat();
1025 fControlType = kTemp;
1026
1027 ostringstream out;
1028 out << "Starting temperature feedback with an offset of " << fBiasOffset << "V";
1029 Message(out);
1030
1031 if (fDimBias.state()==BIAS::State::kVoltageOn)
1032 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
1033
1034 return GetCurrentState();
1035 }
1036
1037 int StartCurrentCtrl(const EventImp &evt)
1038 {
1039 if (!CheckEventSize(evt.GetSize(), "StartCurrentCtrl", 4))
1040 return kSM_FatalError;
1041
1042 if (fCalibration.size()==0)
1043 {
1044 Warn("Current control needs a bias crate calibration first... command ignored.");
1045 return GetCurrentState();
1046 }
1047
1048 WarnState(true, false);
1049
1050 fBiasOffset = evt.GetFloat();
1051 fTempOffset = -3;
1052 ResetData(0);
1053 fControlType = kCurrents;
1054
1055 ostringstream out;
1056 out << "Starting current/temp feedback with an offset of " << fBiasOffset << "V";
1057 Message(out);
1058
1059 return GetCurrentState();
1060 }
1061
1062 int StopFeedback()
1063 {
1064 fControlType = kIdle;
1065
1066 return GetCurrentState();
1067 }
1068
1069 int StoreReference()
1070 {
1071 if (!fPV[0].size() && !fPV[1].size() && !fPV[2].size())
1072 {
1073 Warn("No values in memory. Take enough events first!");
1074 return GetCurrentState();
1075 }
1076
1077 // FIXME: Check age
1078
1079 if (!fPV[1].size() && !fPV[2].size())
1080 fSP = fPV[0];
1081
1082 if (!fPV[2].size())
1083 fSP = fPV[1];
1084 else
1085 fSP = fPV[2];
1086
1087 vector<float> vec(BIAS::kNumChannels);
1088 for (int i=0; i<BIAS::kNumChannels; i++)
1089 vec[i] = fSP[i];
1090 fDimReference.Update(vec);
1091
1092 return GetCurrentState();
1093 }
1094
1095 int SetReference(const EventImp &evt)
1096 {
1097 if (!CheckEventSize(evt.GetSize(), "SetReference", 4))
1098 return kSM_FatalError;
1099
1100 const float val = evt.GetFloat();
1101 /*
1102 if (!fPV[0].size() && !fPV[1].size() && !fPV[2].size())
1103 {
1104 Warn("No values in memory. Take enough events first!");
1105 return GetCurrentState();
1106 }*/
1107
1108 vector<float> vec(BIAS::kNumChannels);
1109 for (int i=0; i<BIAS::kNumChannels; i++)
1110 vec[i] = fSP[i] = val;
1111 fDimReference.Update(vec);
1112
1113 Out() << "New global reference value: " << val << "mV" << endl;
1114
1115 return GetCurrentState();
1116 }
1117
1118 int CalibrateCurrents()
1119 {
1120// if (!CheckEventSize(evt.GetSize(), "StartTempCtrl", 4))
1121// return kSM_FatalError;
1122
1123 if (fDimBias.state()==BIAS::State::kRamping)
1124 {
1125 Warn("Calibration cannot be started when biasctrl is in state Ramping.");
1126 return GetCurrentState();
1127 }
1128
1129 if (fVoltGapd.size()==0)
1130 {
1131 Error("No G-APD reference voltages received yet (BIAS_CONTROL/NOMINAL).");
1132 return GetCurrentState();
1133 }
1134
1135 WarnState(true, false);
1136
1137 ostringstream out;
1138 out << "Starting temperature feedback for calibration with an offset of " << fCalibrationOffset << "V";
1139 Message(out);
1140
1141 fBiasOffset = fCalibrationOffset;
1142 fControlType = kTemp;
1143 fCursorCur = -fNumCalibIgnore;
1144 fCursorTemp = 0;
1145 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
1146 fCurrentsRms.assign(BIAS::kNumChannels, 0);
1147 fCalibration.resize(0);
1148 fStartTime = Time();
1149 fOutputEnabled = true;
1150
1151 return Feedback::State::kCalibrating;
1152 }
1153
1154 int SetCurrentRequestInterval(const EventImp &evt)
1155 {
1156 if (!CheckEventSize(evt.GetSize(), "SetCurrentRequestInterval", 2))
1157 return kSM_FatalError;
1158
1159 fCurrentRequestInterval = evt.GetUShort();
1160
1161 Out() << "New current request interval: " << fCurrentRequestInterval << "ms" << endl;
1162
1163 return GetCurrentState();
1164 }
1165
1166 int Execute()
1167 {
1168 // Dispatch (execute) at most one handler from the queue. In contrary
1169 // to run_one(), it doesn't wait until a handler is available
1170 // which can be dispatched, so poll_one() might return with 0
1171 // handlers dispatched. The handlers are always dispatched/executed
1172 // synchronously, i.e. within the call to poll_one()
1173 //poll_one();
1174
1175 if (!fDim.online())
1176 return Feedback::State::kDimNetworkNA;
1177
1178 const bool bias = fDimBias.state() >= BIAS::State::kConnecting;
1179 const bool fad = fDimFAD.state() >= FAD::State::kConnected;
1180 const bool fsc = fDimFSC.state() >= FSC::State::kConnected;
1181
1182 // All subsystems are not connected
1183 if (!bias && !fad && !fsc)
1184 return Feedback::State::kDisconnected;
1185
1186 // At least one subsystem apart from bias is connected
1187 if (bias && !fad && !fsc)
1188 return Feedback::State::kConnecting;
1189
1190/*
1191 // All subsystems are connected
1192 if (GetCurrentStatus()==Feedback::State::kConfiguringStep1)
1193 {
1194 if (fCursor<1)
1195 return Feedback::State::kConfiguringStep1;
1196
1197 if (fCursor==1)
1198 {
1199 fStartTime = Time();
1200 return Feedback::State::kConfiguringStep2;
1201 }
1202 }
1203 if (GetCurrentStatus()==Feedback::State::kConfiguringStep2)
1204 {
1205 if (fCursor==1)
1206 {
1207 if ((Time()-fStartTime).total_microseconds()/1000000.<1.5)
1208 return Feedback::State::kConfiguringStep2;
1209
1210 Dim::SendCommand("BIAS_CONTROL/REQUEST_STATUS");
1211 }
1212 if (fCursor==2)
1213 {
1214
1215 int n=0;
1216 double avg = 0;
1217 for (size_t i=0; i<fCurrents.size(); i++)
1218 if (fCurrents[i]>=0)
1219 {
1220 avg += fCurrents[i];
1221 n++;
1222 }
1223
1224 cout << avg/n << endl;
1225 }
1226 return Feedback::State::kConnected;
1227 }
1228 */
1229
1230 // Needs connection of FAD and BIAS
1231 if (bias && fad)
1232 {
1233 if (fControlType==kFeedback || fControlType==kFeedbackGlobal)
1234 return fOutputEnabled ? Feedback::State::kFeedbackCtrlRunning : Feedback::State::kFeedbackCtrlIdle;
1235 }
1236
1237 // Needs connection of FSC and BIAS
1238 if (bias && fsc)
1239 {
1240 if (fControlType==kTemp)
1241 {
1242 if (GetCurrentState()==Feedback::State::kCalibrating && fCursorCur<fNumCalibRequests)
1243 return GetCurrentState();
1244
1245 return fOutputEnabled ? Feedback::State::kTempCtrlRunning : Feedback::State::kTempCtrlIdle;
1246 }
1247 if (fControlType==kCurrents)
1248 {
1249 static Time past;
1250 if (fCurrentRequestInterval>0 && Time()-past>boost::posix_time::milliseconds(fCurrentRequestInterval))
1251 {
1252 if (fDimBias.state()==BIAS::State::kVoltageOn)
1253 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
1254 past = Time();
1255 }
1256
1257 return fOutputEnabled && fCursorTemp>0 ? Feedback::State::kCurrentCtrlRunning : Feedback::State::kCurrentCtrlIdle;
1258 }
1259 }
1260
1261 if (bias && fad && !fsc)
1262 return Feedback::State::kConnectedFAD;
1263
1264 if (bias && fsc && !fad)
1265 return Feedback::State::kConnectedFSC;
1266
1267 return Feedback::State::kConnected;
1268 }
1269
1270public:
1271 StateMachineFeedback(ostream &out=cout) : StateMachineDim(out, "FEEDBACK"),
1272 //---
1273 fDimFAD("FAD_CONTROL"),
1274 fDimFSC("FSC_CONTROL"),
1275 fDimBias("BIAS_CONTROL"),
1276 //---
1277 fDimReference("FEEDBACK/REFERENCE", "F:416",
1278 "Amplitude reference value(s)"
1279 "Vref[mV]:Amplitude reference"),
1280 fDimDeviation("FEEDBACK/DEVIATION", "F:416;F:416;F:1;F:1",
1281 "Control loop information"
1282 "|DeltaAmpl[mV]:Amplitude offset measures"
1283 "|DeltaBias[mV]:Correction value calculated"
1284 "|DeltaTemp[mV]:Correction calculated from temperature"
1285 "|DeltaUser[mV]:Additional offset specified by user"),
1286 fDimCalibration("FEEDBACK/CALIBRATION", "F:416;F:416;F:416",
1287 "Current offsets"
1288 "|Avg[uA]:Average offset"
1289 "|Rms[uA]:Rms of offset"
1290 "|R[Ohm]:Measured calibration resistor"),
1291 fDimCurrents("FEEDBACK/CALIBRATED_CURRENTS", "F:416;F:1;F:1;F:1;F:1;I:1;F:1",
1292 "Calibrated currents"
1293 "|I[uA]:Calibrated currents"
1294 "|I_avg[uA]:Average calibrated current (320 channels)"
1295 "|I_rms[uA]:Rms of calibrated current (320 channels)"
1296 "|I_med[uA]:Median calibrated current (320 channels)"
1297 "|I_dev[uA]:Deviation of calibrated current (320 channels)"
1298 "|N:Number of valid values"
1299 "|T_diff[s]:Time difference to calibration"),
1300 fSP(BIAS::kNumChannels),
1301 fKp(0), fKi(0), fKd(0), fT(-1),
1302 fCalibrationOffset(-3),
1303 fCurrentRequestInterval(0),
1304 fNumCalibIgnore(30),
1305 fNumCalibRequests(300),
1306 fOutputEnabled(false)
1307 {
1308 // ba::io_service::work is a kind of keep_alive for the loop.
1309 // It prevents the io_service to go to stopped state, which
1310 // would prevent any consecutive calls to run()
1311 // or poll() to do nothing. reset() could also revoke to the
1312 // previous state but this might introduce some overhead of
1313 // deletion and creation of threads and more.
1314
1315 fDim.Subscribe(*this);
1316 fDimFAD.Subscribe(*this);
1317 fDimFSC.Subscribe(*this);
1318 fDimBias.Subscribe(*this);
1319
1320 Subscribe("BIAS_CONTROL/CURRENT")
1321 (bind(&StateMachineFeedback::HandleBiasCurrent, this, placeholders::_1));
1322 Subscribe("BIAS_CONTROL/VOLTAGE")
1323 (bind(&StateMachineFeedback::HandleBiasVoltage, this, placeholders::_1));
1324 Subscribe("BIAS_CONTROL/FEEDBACK_DATA")
1325 (bind(&StateMachineFeedback::HandleBiasData, this, placeholders::_1));
1326 Subscribe("BIAS_CONTROL/NOMINAL")
1327 (bind(&StateMachineFeedback::HandleBiasNom, this, placeholders::_1));
1328 Subscribe("FSC_CONTROL/TEMPERATURE")
1329 (bind(&StateMachineFeedback::HandleCameraTemp, this, placeholders::_1));
1330
1331 // State names
1332 AddStateName(Feedback::State::kDimNetworkNA, "DimNetworkNotAvailable",
1333 "The Dim DNS is not reachable.");
1334
1335 AddStateName(Feedback::State::kDisconnected, "Disconnected",
1336 "The Dim DNS is reachable, but the required subsystems are not available.");
1337
1338 AddStateName(Feedback::State::kConnecting, "Connecting",
1339 "Only biasctrl is available and connected with its hardware.");
1340
1341 AddStateName(Feedback::State::kConnectedFSC, "ConnectedFSC",
1342 "biasctrl and fscctrl are available and connected with their hardware.");
1343 AddStateName(Feedback::State::kConnectedFAD, "ConnectedFAD",
1344 "biasctrl and fadctrl are available and connected with their hardware.");
1345 AddStateName(Feedback::State::kConnected, "Connected",
1346 "biasctrl, fadctrl and fscctrl are available and connected with their hardware.");
1347
1348 AddStateName(Feedback::State::kFeedbackCtrlIdle, "FeedbackIdle",
1349 "Feedback control activated, but voltage output disabled.");
1350 AddStateName(Feedback::State::kTempCtrlIdle, "TempCtrlIdle",
1351 "Temperature control activated, but voltage output disabled.");
1352 AddStateName(Feedback::State::kCurrentCtrlIdle, "CurrentCtrlIdle",
1353 "Current control activated, but voltage output disabled.");
1354
1355 AddStateName(Feedback::State::kFeedbackCtrlRunning, "FeedbackControl",
1356 "Feedback control activated and voltage output enabled.");
1357 AddStateName(Feedback::State::kTempCtrlRunning, "TempControl",
1358 "Temperature control activated and voltage output enabled.");
1359 AddStateName(Feedback::State::kCurrentCtrlRunning, "CurrentControl",
1360 "Current/Temp control activated and voltage output enabled.");
1361 AddStateName(Feedback::State::kCalibrating, "Calibrating",
1362 "Calibrating current offsets.");
1363
1364 AddEvent("START_FEEDBACK_CONTROL", "S:1", Feedback::State::kConnectedFAD, Feedback::State::kConnected)
1365 (bind(&StateMachineFeedback::StartFeedback, this, placeholders::_1))
1366 ("Start the feedback control loop"
1367 "|Num[short]:Number of events 'medianed' to calculate the correction value");
1368
1369 AddEvent("START_GLOBAL_FEEDBACK", "S:1", Feedback::State::kConnectedFAD, Feedback::State::kConnected)
1370 (bind(&StateMachineFeedback::StartFeedbackGlobal, this, placeholders::_1))
1371 ("Start the global feedback control loop"
1372 "Num[short]:Number of events averaged to calculate the correction value");
1373
1374 AddEvent("START_TEMP_CONTROL", "F:1", Feedback::State::kConnectedFSC, Feedback::State::kConnected)
1375 (bind(&StateMachineFeedback::StartTempCtrl, this, placeholders::_1))
1376 ("Start the temperature control loop"
1377 "|offset[V]:Offset from the nominal temperature corrected value in Volts");
1378
1379 AddEvent("START_CURRENT_CONTROL", "F:1", Feedback::State::kConnectedFSC, Feedback::State::kConnected)
1380 (bind(&StateMachineFeedback::StartCurrentCtrl, this, placeholders::_1))
1381 ("Start the current/temperature control loop"
1382 "|offset[V]:Offset from the nominal current/temperature corrected value in Volts");
1383
1384 // Feedback::State::kTempCtrlIdle, Feedback::State::kFeedbackCtrlIdle, Feedback::State::kTempCtrlRunning, Feedback::State::kFeedbackCtrlRunning
1385 AddEvent("STOP")
1386 (bind(&StateMachineFeedback::StopFeedback, this))
1387 ("Stop any control loop");
1388
1389 AddEvent("ENABLE_OUTPUT", "B:1")//, Feedback::State::kIdle)
1390 (bind(&StateMachineFeedback::EnableOutput, this, placeholders::_1))
1391 ("Enable sending of correction values caluclated by the control loop to the biasctrl");
1392
1393 AddEvent("STORE_REFERENCE")//, Feedback::State::kIdle)
1394 (bind(&StateMachineFeedback::StoreReference, this))
1395 ("Store the last (averaged) value as new reference (for debug purpose only)");
1396
1397 AddEvent("SET_REFERENCE", "F:1")//, Feedback::State::kIdle)
1398 (bind(&StateMachineFeedback::SetReference, this, placeholders::_1))
1399 ("Set a new global reference value (for debug purpose only)");
1400
1401 AddEvent("SET_Ki", "D:1")//, Feedback::State::kIdle)
1402 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 0))
1403 ("Set integral constant Ki");
1404
1405 AddEvent("SET_Kp", "D:1")//, Feedback::State::kIdle)
1406 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 1))
1407 ("Set proportional constant Kp");
1408
1409 AddEvent("SET_Kd", "D:1")//, Feedback::State::kIdle)
1410 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 2))
1411 ("Set derivative constant Kd");
1412
1413 AddEvent("SET_T", "D:1")//, Feedback::State::kIdle)
1414 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 3))
1415 ("Set time-constant. (-1 to use the cycle time, i.e. the time for the last average cycle, instead)");
1416
1417 AddEvent("CALIBRATE_CURRENTS", Feedback::State::kConnectedFSC, Feedback::State::kConnected)//, Feedback::State::kIdle)
1418 (bind(&StateMachineFeedback::CalibrateCurrents, this))
1419 ("");
1420
1421 AddEvent("SET_CURRENT_REQUEST_INTERVAL", Feedback::State::kConnectedFSC, Feedback::State::kConnected)//, Feedback::State::kIdle)
1422 (bind(&StateMachineFeedback::SetCurrentRequestInterval, this, placeholders::_1))
1423 ("|interval[ms]:Interval between two current requests in modes which need that.");
1424
1425 // Verbosity commands
1426// AddEvent("SET_VERBOSE", "B:1")
1427// (bind(&StateMachineMCP::SetVerbosity, this, placeholders::_1))
1428// ("set verbosity state"
1429// "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
1430
1431 AddEvent("PRINT")
1432 (bind(&StateMachineFeedback::Print, this))
1433 ("");
1434
1435 AddEvent("PRINT_CALIBRATION")
1436 (bind(&StateMachineFeedback::PrintCalibration, this))
1437 ("");
1438 }
1439
1440 int EvalOptions(Configuration &conf)
1441 {
1442 if (!fMap.Read(conf.Get<string>("pixel-map-file")))
1443 {
1444 Error("Reading mapping table from "+conf.Get<string>("pixel-map-file")+" failed.");
1445 return 1;
1446 }
1447
1448 fGain = 0.1; // V(Amplitude) / V(Bias)
1449
1450 // 148 -> 248
1451
1452 // 33 : 10s < 2%
1453 // 50 : 5s < 2%
1454 // 66 : 3s < 2%
1455 // 85 : 2s < 2%
1456
1457 fKp = 0;
1458 fKd = 0;
1459 fKi = 0.75;
1460 fT = 1;
1461
1462 // Is that independent of the aboslute real amplitude of
1463 // the light pulser?
1464
1465 ostringstream msg;
1466 msg << "Control loop parameters: ";
1467 msg << "Kp=" << fKp << ", Kd=" << fKd << ", Ki=" << fKi << ", ";
1468 if (fT>0)
1469 msg << fT;
1470 else
1471 msg << "<auto>";
1472 msg << ", Gain(DRS/BIAS)=" << fGain << "V/V";
1473
1474 Message(msg);
1475
1476 fCurrentRequestInterval = conf.Get<uint16_t>("current-request-interval");
1477 fNumCalibIgnore = conf.Get<uint16_t>("num-calib-ignore");
1478 fNumCalibRequests = conf.Get<uint16_t>("num-calib-average");
1479 fCalibrationOffset = conf.Get<float>("calibration-offset");
1480
1481 return -1;
1482 }
1483};
1484
1485// ------------------------------------------------------------------------
1486
1487#include "Main.h"
1488
1489template<class T>
1490int RunShell(Configuration &conf)
1491{
1492 return Main::execute<T, StateMachineFeedback>(conf);
1493}
1494
1495void SetupConfiguration(Configuration &conf)
1496{
1497 po::options_description control("Feedback options");
1498 control.add_options()
1499 ("pixel-map-file", var<string>("FACTmapV5a.txt"), "Pixel mapping file. Used here to get the default reference voltage.")
1500 ("current-request-interval", var<uint16_t>(1000), "Interval between two current requests.")
1501 ("num-calib-ignore", var<uint16_t>(30), "Number of current requests to be ignored before averaging")
1502 ("num-calib-average", var<uint16_t>(300), "Number of current requests to be averaged")
1503 ("calibration-offset", var<float>(-3), "Absolute offset relative to the G-APD operation voltage when calibrating")
1504 ;
1505
1506 conf.AddOptions(control);
1507}
1508
1509/*
1510 Extract usage clause(s) [if any] for SYNOPSIS.
1511 Translators: "Usage" and "or" here are patterns (regular expressions) which
1512 are used to match the usage synopsis in program output. An example from cp
1513 (GNU coreutils) which contains both strings:
1514 Usage: cp [OPTION]... [-T] SOURCE DEST
1515 or: cp [OPTION]... SOURCE... DIRECTORY
1516 or: cp [OPTION]... -t DIRECTORY SOURCE...
1517 */
1518void PrintUsage()
1519{
1520 cout <<
1521 "The feedback control the BIAS voltages based on the calibration signal.\n"
1522 "\n"
1523 "The default is that the program is started without user intercation. "
1524 "All actions are supposed to arrive as DimCommands. Using the -c "
1525 "option, a local shell can be initialized. With h or help a short "
1526 "help message about the usuage can be brought to the screen.\n"
1527 "\n"
1528 "Usage: feedback [-c type] [OPTIONS]\n"
1529 " or: feedback [OPTIONS]\n";
1530 cout << endl;
1531}
1532
1533void PrintHelp()
1534{
1535 Main::PrintHelp<StateMachineFeedback>();
1536
1537 /* Additional help text which is printed after the configuration
1538 options goes here */
1539
1540 /*
1541 cout << "bla bla bla" << endl << endl;
1542 cout << endl;
1543 cout << "Environment:" << endl;
1544 cout << "environment" << endl;
1545 cout << endl;
1546 cout << "Examples:" << endl;
1547 cout << "test exam" << endl;
1548 cout << endl;
1549 cout << "Files:" << endl;
1550 cout << "files" << endl;
1551 cout << endl;
1552 */
1553}
1554
1555int main(int argc, const char* argv[])
1556{
1557 Configuration conf(argv[0]);
1558 conf.SetPrintUsage(PrintUsage);
1559 Main::SetupConfiguration(conf);
1560 SetupConfiguration(conf);
1561
1562 if (!conf.DoParse(argc, argv, PrintHelp))
1563 return 127;
1564
1565 //try
1566 {
1567 // No console access at all
1568 if (!conf.Has("console"))
1569 {
1570// if (conf.Get<bool>("no-dim"))
1571// return RunShell<LocalStream, StateMachine, ConnectionFSC>(conf);
1572// else
1573 return RunShell<LocalStream>(conf);
1574 }
1575 // Cosole access w/ and w/o Dim
1576/* if (conf.Get<bool>("no-dim"))
1577 {
1578 if (conf.Get<int>("console")==0)
1579 return RunShell<LocalShell, StateMachine, ConnectionFSC>(conf);
1580 else
1581 return RunShell<LocalConsole, StateMachine, ConnectionFSC>(conf);
1582 }
1583 else
1584*/ {
1585 if (conf.Get<int>("console")==0)
1586 return RunShell<LocalShell>(conf);
1587 else
1588 return RunShell<LocalConsole>(conf);
1589 }
1590 }
1591 /*catch (std::exception& e)
1592 {
1593 cerr << "Exception: " << e.what() << endl;
1594 return -1;
1595 }*/
1596
1597 return 0;
1598}
Note: See TracBrowser for help on using the repository browser.