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

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