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

Last change on this file since 13477 was 13456, checked in by tbretz, 14 years ago
Changed CALIBRATION service to SI units.
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 * conv; // [A]
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]*1e-6 : 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 const double conv = 5000./4096;
376
377 for (int i=0; i<BIAS::kNumChannels; i++)
378 {
379 const double I = double(fCurrentsAvg[i])/fCursorCur;
380
381 res[i] = fVoltGapd[i]/I / conv * 1e6;
382 avg[i] = conv * I;
383 rms[i] = conv * sqrt(double(fCurrentsRms[i])/fCursorCur-I*I);
384 }
385
386 fDimCalibration.Update(fCalibration);
387
388 fOutputEnabled = false;
389 fControlType = kIdle;
390
391 Info("Calibration successfully done.");
392
393 if (fStatusBias.second==BIAS::kVoltageOn)
394 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
395 }
396
397 void HandleFeedback()
398 {
399 if (fBiasData.getSize()!=1440*sizeof(float))
400 return;
401
402 // -------- Check age of last stored event --------
403
404 // Must be called in this order
405 const int tsec = fBiasData.getTimestamp();
406 const int tms = fBiasData.getTimestampMillisecs();
407
408 const Time tm(tsec, tms*1000);
409
410 if (Time()-fBiasLast>boost::posix_time::seconds(30))
411 {
412 Warn("Last received event data older than 30s... resetting average calculation.");
413 ResetData();
414 }
415 fBiasLast = tm;
416
417 // -------- Store new event --------
418
419 fData[fCursorAmpl%fData.size()].assign(reinterpret_cast<float*>(fBiasData.getData()),
420 reinterpret_cast<float*>(fBiasData.getData())+1440);
421
422 if (++fCursorAmpl<fData.size())
423 return;
424
425 // -------- Calculate statistics --------
426
427 valarray<double> med(1440);
428
429 for (int ch=0; ch<1440; ch++)
430 {
431 vector<float> arr(fData.size());
432 for (size_t i=0; i<fData.size(); i++)
433 arr[i] = fData[i][ch];
434
435 sort(arr.begin(), arr.end());
436
437 med[ch] = arr[arr.size()/2];
438 }
439
440 /*
441 vector<float> med(1440);
442 vector<float> rms(1440);
443 for (size_t i=0; i<fData.size(); i++)
444 {
445 if (fData[i].size()==0)
446 return;
447
448 for (int j=0; j<1440; j++)
449 {
450 med[j] += fData[i][j];
451 rms[j] += fData[i][j]*fData[i][j];
452 }
453 }
454 */
455
456 vector<double> avg(BIAS::kNumChannels);
457 vector<int> num(BIAS::kNumChannels);
458 for (int i=0; i<1440; i++)
459 {
460 const PixelMapEntry &ch = fMap.hw(i);
461
462 // FIXME: Add a consistency check if the median makes sense...
463 // FIXME: Add a consistency check to remove pixels with bright stars (median?)
464
465 avg[ch.hv()] += med[i];
466 num[ch.hv()]++;
467 }
468
469 for (int i=0; i<BIAS::kNumChannels; i++)
470 {
471 if (num[i])
472 avg[i] /= num[i];
473
474 }
475
476 // -------- Calculate correction --------
477
478 // http://bestune.50megs.com/typeABC.htm
479
480 // CO: Controller output
481 // PV: Process variable
482 // SP: Set point
483 // T: Sampling period (loop update period)
484 // e = SP - PV
485 //
486 // Kp : No units
487 // Ki : per seconds
488 // Kd : seconds
489
490 // 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) ]
491
492 if (fCursorAmpl%fData.size()>0)
493 return;
494
495 // FIXME: Take out broken / dead boards.
496
497 const Time tm0 = Time();
498
499 /*const*/ double T21 = fT>0 ? fT : (tm0-fStartTime).total_microseconds()/1000000.;
500 const double T10 = fT21;
501 fT21 = T21;
502
503 fStartTime = tm0;
504
505 ostringstream out;
506 out << "New " << fData.size() << " event received: " << fCursorAmpl << " / " << setprecision(3) << T21 << "s";
507 Info(out);
508
509 if (fPV[0].size()==0)
510 {
511 fPV[0].resize(avg.size());
512 fPV[0] = valarray<double>(avg.data(), avg.size());
513 return;
514 }
515
516 if (fPV[1].size()==0)
517 {
518 fPV[1].resize(avg.size());
519 fPV[1] = valarray<double>(avg.data(), avg.size());
520 return;
521 }
522
523 if (fPV[2].size()==0)
524 {
525 fPV[2].resize(avg.size());
526 fPV[2] = valarray<double>(avg.data(), avg.size());
527 return;
528 }
529
530 fPV[0] = fPV[1];
531 fPV[1] = fPV[2];
532
533 fPV[2].resize(avg.size());
534 fPV[2] = valarray<double>(avg.data(), avg.size());
535
536 if (T10<=0 || T21<=0)
537 return;
538
539 //cout << "Calculating (" << fCursor << ":" << T21 << ")... " << endl;
540
541 // fKi[j] = response[j]*gain;
542 // Kp = 0;
543 // Kd = 0;
544
545 // => Kp = 0.01 * gain = 0.00005
546 // => Ki = 0.8 * gain/20s = 0.00025
547 // => Kd = 0.1 * gain/20s = 0.00003
548
549 /*
550 fKp = 0;
551 fKd = 0;
552 fKi = 0.00003*20;
553 T21 = 1;
554 */
555
556 //valarray<double> correction = - Kp*(PV[2] - PV[1]) + Ki * dT * (SP-PV[2]) - Kd/dT * (PV[2] - 2*PV[1] + PV[0]);
557 //valarray<double> correction =
558 // - Kp * (PV[2] - PV[1])
559 // + dT * Ki * (SP - PV[2])
560 // - Kd / dT * (PV[2] - 2*PV[1] + PV[0]);
561 //
562 // - (Kp+Kd/dT1) * (PV[2] - PV[1])
563 // + dT2 * Ki * (SP - PV[2])
564 // + Kd / dT1 * (PV[1] - PV[0]);
565 //
566 // - Kp * (PV[2] - PV[1])
567 // + Ki * (SP - PV[2])*dT
568 // - Kd * (PV[2] - PV[1])/dT
569 // + Kd * (PV[1] - PV[0])/dT;
570 //
571 //valarray<double> correction =
572 // - Kp*(PV[2] - PV[1]) + Ki * T21 * (SP-PV[2]) - Kd*(PV[2]-PV[1])/T21 - Kd*(PV[0]-PV[1])/T01;
573 const valarray<double> correction = 1./fGain/1000*
574 (
575 - (fKp+fKd/T21)*(fPV[2] - fPV[1])
576 + fKi*T21*(fSP-fPV[2])
577 + fKd/T10*(fPV[1]-fPV[0])
578 );
579
580 /*
581 integral = 0
582 start:
583 integral += (fSP - fPV[2])*dt
584
585 output = Kp*(fSP - fPV[2]) + Ki*integral - Kd*(fPV[2] - fPV[1])/dt
586
587 wait(dt)
588
589 goto start
590 */
591
592 vector<float> vec(2*BIAS::kNumChannels);
593 for (int i=0; i<BIAS::kNumChannels; i++)
594 vec[i] = fPV[2][i]-fSP[i];
595
596 for (int i=0; i<BIAS::kNumChannels; i++)
597 vec[i+BIAS::kNumChannels] = avg[i]<5*2.5 ? 0 : correction[i];
598
599 fDimDeviation.setQuality(fControlType);
600 fDimDeviation.Update(vec);
601
602 if (!fOutputEnabled || fStatusBias.second!=BIAS::kVoltageOn)
603 return;
604
605 Info("Sending new relative offset to biasctrl.");
606
607 DimClient::sendCommandNB("BIAS_CONTROL/INCREASE_ALL_CHANNELS_VOLTAGE",
608 vec.data()+BIAS::kNumChannels, BIAS::kNumChannels*sizeof(float));
609 }
610
611 void HandleGlobalFeedback()
612 {
613 if (fBiasData.getSize()!=1440*sizeof(float))
614 return;
615
616 // -------- Store new event --------
617
618 vector<float> arr(reinterpret_cast<float*>(fBiasData.getData()),
619 reinterpret_cast<float*>(fBiasData.getData())+1440);
620
621 sort(arr.begin(), arr.end());
622
623 const float med = arr[arr.size()/2];
624
625 fData[fCursorAmpl%fData.size()].resize(1); //assign(&med, &med);
626 fData[fCursorAmpl%fData.size()][0] = med; //assign(&med, &med);
627
628 if (++fCursorAmpl<fData.size())
629 return;
630
631 // -------- Calculate statistics --------
632
633 double avg=0;
634 double rms=0;
635 for (size_t i=0; i<fData.size(); i++)
636 {
637 avg += fData[i][0];
638 rms += fData[i][0]*fData[i][0];
639 }
640
641 avg /= fData.size();
642 rms /= fData.size();
643
644 rms = sqrt(rms-avg*avg);
645
646 // -------- Calculate correction --------
647
648 if (fCursorAmpl%fData.size()!=0)
649 return;
650
651 Out() << "Amplitude: " << avg << " +- " << rms << endl;
652
653 // FIXME: Take out broken / dead boards.
654
655 /*
656 ostringstream out;
657 out << "New " << fData.size() << " event received: " << fCursor << " / " << setprecision(3) << T21 << "s";
658 Info(out);
659 */
660
661 if (fPV[0].size()==0)
662 {
663 fPV[0].resize(1);
664 fPV[0] = valarray<double>(&avg, 1);
665 return;
666 }
667
668 if (fPV[1].size()==0)
669 {
670 fPV[1].resize(1);
671 fPV[1] = valarray<double>(&avg, 1);
672 return;
673 }
674
675 if (fPV[2].size()==0)
676 {
677 fPV[2].resize(1);
678 fPV[2] = valarray<double>(&avg, 1);
679 return;
680 }
681
682 fPV[0] = fPV[1];
683 fPV[1] = fPV[2];
684
685 fPV[2].resize(1);
686 fPV[2] = valarray<double>(&avg, 1);
687
688 // ----- Calculate average currents -----
689
690 vector<float> A(BIAS::kNumChannels);
691 for (int i=0; i<BIAS::kNumChannels; i++)
692 A[i] = double(fCurrentsAvg[i]) / fCursorCur;
693
694 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
695 fCursorCur = 0;
696
697 // -------- Calculate correction --------
698
699 // correction = (fSP[0]-fPV[2])*fKi
700 /*
701 const double T21 = 1; // feedback is 1s
702 const double T10 = 1; // feedback is 20s
703
704 const valarray<double> correction = 1./fGain/1000*
705 (
706 - (fKp+fKd/T21)*(fPV[2] - fPV[1])
707 + fKi*T21*(fSP[0]-fPV[2])
708 + fKd/T10*(fPV[1]-fPV[0])
709 );
710 */
711
712 // pow of 1.6 comes from the non-linearity of the
713 // amplitude vs bias voltage
714 const valarray<double> correction = 1./fGain/1000*
715 (
716 //fKi*(pow(fSP[0], 1./1.6)-pow(fPV[2], 1./1.6))
717 fKi*(fSP[0]-fPV[2])
718 );
719
720 Out() << "Correction: " << correction[0] << "V (" << fSP[0] << ")" << endl;
721
722 const int nch = BIAS::kNumChannels;
723
724 // FIXME: Sanity check!
725
726 vector<float> vec;
727 vec.reserve(2*nch);
728 vec.insert(vec.begin(), nch, fPV[2][0]-fSP[0]);
729 vec.insert(vec.begin()+nch, nch, correction[0]);
730
731 fDimDeviation.setQuality(fControlType);
732 fDimDeviation.Update(vec);
733
734 if (!fOutputEnabled || fStatusBias.second!=BIAS::kVoltageOn)
735 return;
736
737 Info("Sending new global relative offset to biasctrl.");
738
739 DimClient::sendCommandNB("BIAS_CONTROL/INCREASE_ALL_CHANNELS_VOLTAGE",
740 vec.data()+BIAS::kNumChannels, BIAS::kNumChannels*sizeof(float));
741 }
742
743 void infoHandler()
744 {
745 DimInfo *curr = getInfo(); // get current DimInfo address
746 if (!curr)
747 return;
748
749 if (curr==&fBias)
750 {
751 fStatusBias = GetNewState(fBias);
752 return;
753 }
754
755 if (curr==&fFAD)
756 {
757 fStatusFAD = GetNewState(fFAD);
758 return;
759 }
760
761 if (curr==&fFSC)
762 {
763 fStatusFSC = GetNewState(fFSC);
764 return;
765 }
766
767 if (curr==&fDim)
768 {
769 fStatusDim = GetNewState(fDim);
770 fStatusDim.second = curr->getSize()==4 ? curr->getInt() : 0;
771 return;
772 }
773
774 if (curr==&fBiasNom)
775 {
776 const float *ptr = reinterpret_cast<float*>(fBiasNom.getData());
777 fVoltGapd.assign(ptr, ptr+416);
778 return;
779 }
780
781 if (curr==&fCameraTemp && (fControlType==kTemp || fControlType==kCurrents))
782 HandleCameraTemp();
783
784 if (curr==&fBiasA && fControlType==kTemp && GetCurrentState()==kStateCalibrating)
785 HandleCalibration();
786
787 if (curr==&fBiasA && (fControlType==kFeedbackGlobal || fControlType==kCurrents))
788 AverageCurrents();
789
790 if (curr==&fBiasData && fControlType==kFeedback)
791 HandleFeedback();
792
793 if (curr==&fBiasData && fControlType==kFeedbackGlobal)
794 HandleGlobalFeedback();
795 }
796
797 bool CheckEventSize(size_t has, const char *name, size_t size)
798 {
799 if (has==size)
800 return true;
801
802 ostringstream msg;
803 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
804 Fatal(msg);
805 return false;
806 }
807
808 void PrintState(const pair<Time,int> &state, const char *server)
809 {
810 const State rc = fNetwork.GetState(server, state.second);
811
812 Out() << state.first.GetAsStr("%H:%M:%S.%f").substr(0, 12) << " - ";
813 Out() << kBold << server << ": ";
814 Out() << rc.name << "[" << rc.index << "]";
815 Out() << kReset << " - " << kBlue << rc.comment << endl;
816 }
817
818 int Print()
819 {
820 Out() << fStatusDim.first.GetAsStr("%H:%M:%S.%f").substr(0, 12) << " - ";
821 Out() << kBold << "DIM_DNS: ";
822 if (fStatusDim.second==0)
823 Out() << "Offline" << endl;
824 else
825 Out() << "V" << fStatusDim.second/100 << 'r' << fStatusDim.second%100 << endl;
826
827 PrintState(fStatusFAD, "FAD_CONTROL");
828 PrintState(fStatusFSC, "FSC_CONTROL");
829 PrintState(fStatusBias, "BIAS_CONTROL");
830
831 return GetCurrentState();
832 }
833
834 int PrintCalibration()
835 {
836 if (fCalibration.size()==0)
837 {
838 Out() << "No calibration performed so far." << endl;
839 return GetCurrentState();
840 }
841
842 const float *avg = fCalibration.data();
843 const float *rms = fCalibration.data()+BIAS::kNumChannels;
844 const float *res = fCalibration.data()+BIAS::kNumChannels*2;
845
846 Out() << "Average current at " << fCalibrationOffset << "V below G-APD operation voltage:\n";
847
848 for (int k=0; k<13; k++)
849 for (int j=0; j<8; j++)
850 {
851 Out() << setw(2) << k << "|" << setw(2) << j*4 << "|";
852 for (int i=0; i<4; i++)
853 Out() << Tools::Form(" %6.1f+-%4.1f", avg[k*32+j*4+i], rms[k*32+j*4+i]);
854 Out() << '\n';
855 }
856 Out() << '\n';
857
858 Out() << "Measured calibration resistor:\n";
859 for (int k=0; k<13; k++)
860 for (int j=0; j<4; j++)
861 {
862 Out() << setw(2) << k << "|" << setw(2) << j*8 << "|";
863 for (int i=0; i<8; i++)
864 Out() << Tools::Form(" %5.0f", res[k*32+j*8+i]);
865 Out() << '\n';
866 }
867
868 Out() << flush;
869
870 return GetCurrentState();
871 }
872
873 int SetConstant(const EventImp &evt, int constant)
874 {
875 if (!CheckEventSize(evt.GetSize(), "SetConstant", 8))
876 return kSM_FatalError;
877
878 switch (constant)
879 {
880 case 0: fKi = evt.GetDouble(); break;
881 case 1: fKp = evt.GetDouble(); break;
882 case 2: fKd = evt.GetDouble(); break;
883 case 3: fT = evt.GetDouble(); break;
884 case 4: fGain = evt.GetDouble(); break;
885 default:
886 Fatal("SetConstant got an unexpected constant id -- this is a program bug!");
887 return kSM_FatalError;
888 }
889
890 return GetCurrentState();
891 }
892
893 int EnableOutput(const EventImp &evt)
894 {
895 if (!CheckEventSize(evt.GetSize(), "EnableOutput", 1))
896 return kSM_FatalError;
897
898 fOutputEnabled = evt.GetBool();
899
900 return GetCurrentState();
901 }
902
903 void ResetData(int16_t n=-1)
904 {
905 fData.assign(n>0 ? n : fData.size(), vector<float>(0));
906
907 fCursorAmpl = 0;
908 fCursorCur = 0;
909 fCursorTemp = 0;
910
911 fStartTime = Time();
912
913 fSP = valarray<double>(0., BIAS::kNumChannels);
914
915 vector<float> vec(2*BIAS::kNumChannels);
916 fDimDeviation.setQuality(kIdle);
917 fDimDeviation.Update(vec);
918
919 fPV[0].resize(0);
920 fPV[1].resize(0);
921 fPV[2].resize(0);
922
923 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
924 fCurrentsRms.assign(BIAS::kNumChannels, 0);
925
926 if (fKp==0 && fKi==0 && fKd==0)
927 Warn("Control loop parameters are all set to zero.");
928 }
929
930 int StartFeedback(const EventImp &evt)
931 {
932 if (!CheckEventSize(evt.GetSize(), "StartFeedback", 2))
933 return kSM_FatalError;
934
935 ResetData(evt.GetShort());
936
937 fControlType = kFeedback;
938
939 return GetCurrentState();
940 }
941
942 int StartFeedbackGlobal(const EventImp &evt)
943 {
944 if (!CheckEventSize(evt.GetSize(), "StartFeedbackGlobal", 2))
945 return kSM_FatalError;
946
947 ResetData(evt.GetShort());
948
949 fControlType = kFeedbackGlobal;
950
951 return GetCurrentState();
952 }
953
954 int StartTempCtrl(const EventImp &evt)
955 {
956 if (!CheckEventSize(evt.GetSize(), "StartTempCtrl", 4))
957 return kSM_FatalError;
958
959 fBiasOffset = evt.GetFloat();
960 fControlType = kTemp;
961
962 ostringstream out;
963 out << "Starting temperature feedback with an offset of " << fBiasOffset << "V";
964 Message(out);
965
966 if (fStatusBias.second==BIAS::kVoltageOn)
967 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
968
969 return GetCurrentState();
970 }
971
972 int StartCurrentCtrl(const EventImp &evt)
973 {
974 if (!CheckEventSize(evt.GetSize(), "StartCurrentCtrl", 4))
975 return kSM_FatalError;
976
977 if (fCalibration.size()==0)
978 {
979 Warn("Current control needs a bias crate calibration first... command ignored.");
980 return GetCurrentState();
981 }
982
983 ResetData(0);
984
985 fBiasOffset = evt.GetFloat();
986 fControlType = kCurrents;
987
988 ostringstream out;
989 out << "Starting current/temp feedback with an offset of " << fBiasOffset << "V";
990 Message(out);
991
992 return GetCurrentState();
993 }
994
995 int StopFeedback()
996 {
997 fControlType = kIdle;
998
999 return GetCurrentState();
1000 }
1001
1002 int StoreReference()
1003 {
1004 if (!fPV[0].size() && !fPV[1].size() && !fPV[2].size())
1005 {
1006 Warn("No values in memory. Take enough events first!");
1007 return GetCurrentState();
1008 }
1009
1010 // FIXME: Check age
1011
1012 if (!fPV[1].size() && !fPV[2].size())
1013 fSP = fPV[0];
1014
1015 if (!fPV[2].size())
1016 fSP = fPV[1];
1017 else
1018 fSP = fPV[2];
1019
1020 vector<float> vec(BIAS::kNumChannels);
1021 for (int i=0; i<BIAS::kNumChannels; i++)
1022 vec[i] = fSP[i];
1023 fDimReference.Update(vec);
1024
1025 return GetCurrentState();
1026 }
1027
1028 int SetReference(const EventImp &evt)
1029 {
1030 if (!CheckEventSize(evt.GetSize(), "SetReference", 4))
1031 return kSM_FatalError;
1032
1033 const float val = evt.GetFloat();
1034 /*
1035 if (!fPV[0].size() && !fPV[1].size() && !fPV[2].size())
1036 {
1037 Warn("No values in memory. Take enough events first!");
1038 return GetCurrentState();
1039 }*/
1040
1041 vector<float> vec(BIAS::kNumChannels);
1042 for (int i=0; i<BIAS::kNumChannels; i++)
1043 vec[i] = fSP[i] = val;
1044 fDimReference.Update(vec);
1045
1046 Out() << "New global reference value: " << val << "mV" << endl;
1047
1048 return GetCurrentState();
1049 }
1050
1051 int CalibrateCurrents()
1052 {
1053// if (!CheckEventSize(evt.GetSize(), "StartTempCtrl", 4))
1054// return kSM_FatalError;
1055
1056 if (fStatusBias.second==BIAS::kRamping)
1057 {
1058 Warn("Calibration cannot be started when biasctrl is in state Ramping.");
1059 return GetCurrentState();
1060 }
1061
1062 if (fVoltGapd.size()==0)
1063 {
1064 Error("No G-APD reference voltages received yet (BIAS_CONTROL/NOMINAL).");
1065 return GetCurrentState();
1066 }
1067
1068 ostringstream out;
1069 out << "Starting temperature feedback for calibration with an offset of -2V";
1070 Message(out);
1071
1072 fBiasOffset = fCalibrationOffset;
1073 fControlType = kTemp;
1074 fCursorCur = -fNumCalibIgnore;
1075 fCursorTemp = 0;
1076 fCurrentsAvg.assign(BIAS::kNumChannels, 0);
1077 fCurrentsRms.assign(BIAS::kNumChannels, 0);
1078 fCalibration.resize(0);
1079 fStartTime = Time();
1080 fOutputEnabled = true;
1081
1082 return kStateCalibrating;
1083 }
1084
1085 int SetCurrentRequestInterval(const EventImp &evt)
1086 {
1087 if (!CheckEventSize(evt.GetSize(), "SetCurrentRequestInterval", 2))
1088 return kSM_FatalError;
1089
1090 fCurrentRequestInterval = evt.GetUShort();
1091
1092 Out() << "New current request interval: " << fCurrentRequestInterval << "ms" << endl;
1093
1094 return GetCurrentState();
1095 }
1096
1097 int Execute()
1098 {
1099 // Dispatch (execute) at most one handler from the queue. In contrary
1100 // to run_one(), it doesn't wait until a handler is available
1101 // which can be dispatched, so poll_one() might return with 0
1102 // handlers dispatched. The handlers are always dispatched/executed
1103 // synchronously, i.e. within the call to poll_one()
1104 //poll_one();
1105
1106 if (fStatusDim.second==0)
1107 return kStateDimNetworkNA;
1108
1109 const bool bias = fStatusBias.second >= BIAS::kConnecting;
1110 const bool fad = fStatusFAD.second >= FAD::kConnected;
1111 const bool fsc = fStatusFSC.second >= 2;
1112
1113 // All subsystems are not connected
1114 if (!bias && !fad && !fsc)
1115 return kStateDisconnected;
1116
1117 // At least one subsystem apart from bias is connected
1118 if (bias && !fad && !fsc)
1119 return kStateConnecting;
1120
1121/*
1122 // All subsystems are connected
1123 if (GetCurrentStatus()==kStateConfiguringStep1)
1124 {
1125 if (fCursor<1)
1126 return kStateConfiguringStep1;
1127
1128 if (fCursor==1)
1129 {
1130 fStartTime = Time();
1131 return kStateConfiguringStep2;
1132 }
1133 }
1134 if (GetCurrentStatus()==kStateConfiguringStep2)
1135 {
1136 if (fCursor==1)
1137 {
1138 if ((Time()-fStartTime).total_microseconds()/1000000.<1.5)
1139 return kStateConfiguringStep2;
1140
1141 Dim::SendCommand("BIAS_CONTROL/REQUEST_STATUS");
1142 }
1143 if (fCursor==2)
1144 {
1145
1146 int n=0;
1147 double avg = 0;
1148 for (size_t i=0; i<fCurrents.size(); i++)
1149 if (fCurrents[i]>=0)
1150 {
1151 avg += fCurrents[i];
1152 n++;
1153 }
1154
1155 cout << avg/n << endl;
1156 }
1157 return kStateConnected;
1158 }
1159 */
1160
1161 // Needs connection of FAD and BIAS
1162 if (bias && fad)
1163 {
1164 if (fControlType==kFeedback || fControlType==kFeedbackGlobal)
1165 return fOutputEnabled ? kStateFeedbackCtrlRunning : kStateFeedbackCtrlIdle;
1166 }
1167
1168 // Needs connection of FSC and BIAS
1169 if (bias && fsc)
1170 {
1171 if (fControlType==kTemp)
1172 {
1173 if (GetCurrentState()==kStateCalibrating && fCursorCur<fNumCalibRequests)
1174 return GetCurrentState();
1175
1176 return fOutputEnabled ? kStateTempCtrlRunning : kStateTempCtrlIdle;
1177 }
1178 if (fControlType==kCurrents)
1179 {
1180 static Time past;
1181 if (fCurrentRequestInterval>0 && Time()-past>boost::posix_time::milliseconds(fCurrentRequestInterval))
1182 {
1183 if (fStatusBias.second==BIAS::kVoltageOn)
1184 DimClient::sendCommandNB("BIAS_CONTROL/REQUEST_STATUS", NULL, 0);
1185 past = Time();
1186 }
1187
1188 return fOutputEnabled ? kStateCurrentCtrlRunning : kStateCurrentCtrlIdle;
1189 }
1190 }
1191
1192 if (bias && fad && !fsc)
1193 return kStateConnectedFAD;
1194
1195 if (bias && fsc && !fad)
1196 return kStateConnectedFSC;
1197
1198 return kStateConnected;
1199 }
1200
1201public:
1202 StateMachineFeedback(ostream &out=cout) : StateMachineDim(out, "FEEDBACK"),
1203 fStatusDim(make_pair(Time(), -2)),
1204 fStatusFAD(make_pair(Time(), -2)),
1205 fStatusBias(make_pair(Time(), -2)),
1206 fDim("DIS_DNS/VERSION_NUMBER", (void*)NULL, 0, this),
1207 fFAD("FAD_CONTROL/STATE", (void*)NULL, 0, this),
1208 fFSC("FSC_CONTROL/STATE", (void*)NULL, 0, this),
1209 fBias("BIAS_CONTROL/STATE", (void*)NULL, 0, this),
1210 fBiasA("BIAS_CONTROL/CURRENT", (void*)NULL, 0, this),
1211 fBiasData("FAD_CONTROL/FEEDBACK_DATA", (void*)NULL, 0, this),
1212 fCameraTemp("FSC_CONTROL/TEMPERATURE", (void*)NULL, 0, this),
1213 fDimReference("FEEDBACK/REFERENCE", "F:416",
1214 "Amplitude reference value(s)"
1215 "Vref[mV]:Amplitude reference"),
1216 fDimDeviation("FEEDBACK/DEVIATION", "F:416;F:416",
1217 "Control loop information"
1218 "|DeltaAmpl[mV]:Amplitude offset measures"
1219 "|DeltaBias[mV]:Correction value calculated"),
1220 fDimCalibration("FEEDBACK/CALIBRATION", "F:416;F:416;F:416",
1221 "Current offsets"
1222 "|Avg[uA]:Average offset"
1223 "|Rms[uA]:Rms of offset"
1224 "|R[Ohm]:Measured calibration resistor"),
1225 fSP(BIAS::kNumChannels),
1226 fKp(0), fKi(0), fKd(0), fT(-1),
1227 fCalibrationOffset(-3),
1228 fCurrentRequestInterval(0),
1229 fNumCalibIgnore(30),
1230 fNumCalibRequests(300),
1231 fOutputEnabled(false)
1232 {
1233 // ba::io_service::work is a kind of keep_alive for the loop.
1234 // It prevents the io_service to go to stopped state, which
1235 // would prevent any consecutive calls to run()
1236 // or poll() to do nothing. reset() could also revoke to the
1237 // previous state but this might introduce some overhead of
1238 // deletion and creation of threads and more.
1239
1240// fSP.resize(416);
1241
1242 // State names
1243 AddStateName(kStateDimNetworkNA, "DimNetworkNotAvailable",
1244 "The Dim DNS is not reachable.");
1245
1246 AddStateName(kStateDisconnected, "Disconnected",
1247 "The Dim DNS is reachable, but the required subsystems are not available.");
1248
1249 AddStateName(kStateConnecting, "Connecting",
1250 "Only biasctrl is available and connected with its hardware.");
1251
1252 AddStateName(kStateConnectedFSC, "ConnectedFSC",
1253 "biasctrl and fscctrl are available and connected with their hardware.");
1254 AddStateName(kStateConnectedFAD, "ConnectedFAD",
1255 "biasctrl and fadctrl are available and connected with their hardware.");
1256 AddStateName(kStateConnected, "Connected",
1257 "biasctrl, fadctrl and fscctrl are available and connected with their hardware.");
1258
1259 AddStateName(kStateFeedbackCtrlIdle, "FeedbackIdle",
1260 "Feedback control activated, but voltage output disabled.");
1261 AddStateName(kStateTempCtrlIdle, "TempCtrlIdle",
1262 "Temperature control activated, but voltage output disabled.");
1263 AddStateName(kStateCurrentCtrlIdle, "CurrentCtrlIdle",
1264 "Current control activated, but voltage output disabled.");
1265
1266 AddStateName(kStateFeedbackCtrlRunning, "FeedbackControl",
1267 "Feedback control activated and voltage output enabled.");
1268 AddStateName(kStateTempCtrlRunning, "TempControl",
1269 "Temperature control activated and voltage output enabled.");
1270 AddStateName(kStateCurrentCtrlRunning, "CurrentControl",
1271 "Current/Temp control activated and voltage output enabled.");
1272 AddStateName(kStateCalibrating, "Calibrating",
1273 "Calibrating current offsets.");
1274
1275 AddEvent("START_FEEDBACK_CONTROL", "S:1", kStateConnectedFAD, kStateConnected)
1276 (bind(&StateMachineFeedback::StartFeedback, this, placeholders::_1))
1277 ("Start the feedback control loop"
1278 "|Num[short]:Number of events 'medianed' to calculate the correction value");
1279
1280 AddEvent("START_GLOBAL_FEEDBACK", "S:1", kStateConnectedFAD, kStateConnected)
1281 (bind(&StateMachineFeedback::StartFeedbackGlobal, this, placeholders::_1))
1282 ("Start the global feedback control loop"
1283 "Num[short]:Number of events averaged to calculate the correction value");
1284
1285 AddEvent("START_TEMP_CONTROL", "F:1", kStateConnectedFSC, kStateConnected)
1286 (bind(&StateMachineFeedback::StartTempCtrl, this, placeholders::_1))
1287 ("Start the temperature control loop"
1288 "|offset[V]:Offset from the nominal temperature corrected value in Volts");
1289
1290 AddEvent("START_CURRENT_CONTROL", "F:1", kStateConnectedFSC, kStateConnected)
1291 (bind(&StateMachineFeedback::StartCurrentCtrl, this, placeholders::_1))
1292 ("Start the current/temperature control loop"
1293 "|offset[V]:Offset from the nominal current/temperature corrected value in Volts");
1294
1295 // kStateTempCtrlIdle, kStateFeedbackCtrlIdle, kStateTempCtrlRunning, kStateFeedbackCtrlRunning
1296 AddEvent("STOP")
1297 (bind(&StateMachineFeedback::StopFeedback, this))
1298 ("Stop any control loop");
1299
1300 AddEvent("ENABLE_OUTPUT", "B:1")//, kStateIdle)
1301 (bind(&StateMachineFeedback::EnableOutput, this, placeholders::_1))
1302 ("Enable sending of correction values caluclated by the control loop to the biasctrl");
1303
1304 AddEvent("STORE_REFERENCE")//, kStateIdle)
1305 (bind(&StateMachineFeedback::StoreReference, this))
1306 ("Store the last (averaged) value as new reference (for debug purpose only)");
1307
1308 AddEvent("SET_REFERENCE", "F:1")//, kStateIdle)
1309 (bind(&StateMachineFeedback::SetReference, this, placeholders::_1))
1310 ("Set a new global reference value (for debug purpose only)");
1311
1312 AddEvent("SET_Ki", "D:1")//, kStateIdle)
1313 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 0))
1314 ("Set integral constant Ki");
1315
1316 AddEvent("SET_Kp", "D:1")//, kStateIdle)
1317 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 1))
1318 ("Set proportional constant Kp");
1319
1320 AddEvent("SET_Kd", "D:1")//, kStateIdle)
1321 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 2))
1322 ("Set derivative constant Kd");
1323
1324 AddEvent("SET_T", "D:1")//, kStateIdle)
1325 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 3))
1326 ("Set time-constant. (-1 to use the cycle time, i.e. the time for the last average cycle, instead)");
1327
1328 AddEvent("CALIBRATE_CURRENTS", kStateConnectedFSC, kStateConnected)//, kStateIdle)
1329 (bind(&StateMachineFeedback::CalibrateCurrents, this))
1330 ("");
1331
1332 AddEvent("SET_CURRENT_REQUEST_INTERVAL", kStateConnectedFSC, kStateConnected)//, kStateIdle)
1333 (bind(&StateMachineFeedback::SetCurrentRequestInterval, this, placeholders::_1))
1334 ("|interval[ms]:Interval between two current requests in modes which need that.");
1335
1336 // Verbosity commands
1337// AddEvent("SET_VERBOSE", "B:1")
1338// (bind(&StateMachineMCP::SetVerbosity, this, placeholders::_1))
1339// ("set verbosity state"
1340// "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
1341
1342 AddEvent("PRINT")
1343 (bind(&StateMachineFeedback::Print, this))
1344 ("");
1345
1346 AddEvent("PRINT_CALIBRATION")
1347 (bind(&StateMachineFeedback::PrintCalibration, this))
1348 ("");
1349 }
1350
1351 int EvalOptions(Configuration &conf)
1352 {
1353 if (!fMap.Read(conf.Get<string>("pixel-map-file")))
1354 {
1355 Error("Reading mapping table from "+conf.Get<string>("pixel-map-file")+" failed.");
1356 return 1;
1357 }
1358
1359 fGain = 0.1; // V(Amplitude) / V(Bias)
1360
1361 // 148 -> 248
1362
1363 // 33 : 10s < 2%
1364 // 50 : 5s < 2%
1365 // 66 : 3s < 2%
1366 // 85 : 2s < 2%
1367
1368 fKp = 0;
1369 fKd = 0;
1370 fKi = 0.75;
1371 fT = 1;
1372
1373 // Is that independent of the aboslute real amplitude of
1374 // the light pulser?
1375
1376 ostringstream msg;
1377 msg << "Control loop parameters: ";
1378 msg << "Kp=" << fKp << ", Kd=" << fKd << ", Ki=" << fKi << ", ";
1379 if (fT>0)
1380 msg << fT;
1381 else
1382 msg << "<auto>";
1383 msg << ", Gain(DRS/BIAS)=" << fGain << "V/V";
1384
1385 Message(msg);
1386
1387 fCurrentRequestInterval = conf.Get<uint16_t>("current-request-interval");
1388 fNumCalibIgnore = conf.Get<uint16_t>("num-calib-ignore");
1389 fNumCalibRequests = conf.Get<uint16_t>("num-calib-average");
1390 fCalibrationOffset = conf.Get<float>("calibration-offset");
1391
1392 return -1;
1393 }
1394};
1395
1396// ------------------------------------------------------------------------
1397
1398#include "Main.h"
1399
1400template<class T>
1401int RunShell(Configuration &conf)
1402{
1403 return Main::execute<T, StateMachineFeedback>(conf);
1404}
1405
1406void SetupConfiguration(Configuration &conf)
1407{
1408 po::options_description control("Feedback options");
1409 control.add_options()
1410 ("pixel-map-file", var<string>("FACTmapV5a.txt"), "Pixel mapping file. Used here to get the default reference voltage.")
1411 ("current-request-interval", var<uint16_t>(1000), "Interval between two current requests.")
1412 ("num-calib-ignore", var<uint16_t>(30), "Number of current requests to be ignored before averaging")
1413 ("num-calib-average", var<uint16_t>(300), "Number of current requests to be averaged")
1414 ("calibration-offset", var<float>(-3), "Absolute offset relative to the G-APD operation voltage when calibrating")
1415 ;
1416
1417 conf.AddOptions(control);
1418}
1419
1420/*
1421 Extract usage clause(s) [if any] for SYNOPSIS.
1422 Translators: "Usage" and "or" here are patterns (regular expressions) which
1423 are used to match the usage synopsis in program output. An example from cp
1424 (GNU coreutils) which contains both strings:
1425 Usage: cp [OPTION]... [-T] SOURCE DEST
1426 or: cp [OPTION]... SOURCE... DIRECTORY
1427 or: cp [OPTION]... -t DIRECTORY SOURCE...
1428 */
1429void PrintUsage()
1430{
1431 cout <<
1432 "The feedback control the BIAS voltages based on the calibration signal.\n"
1433 "\n"
1434 "The default is that the program is started without user intercation. "
1435 "All actions are supposed to arrive as DimCommands. Using the -c "
1436 "option, a local shell can be initialized. With h or help a short "
1437 "help message about the usuage can be brought to the screen.\n"
1438 "\n"
1439 "Usage: feedback [-c type] [OPTIONS]\n"
1440 " or: feedback [OPTIONS]\n";
1441 cout << endl;
1442}
1443
1444void PrintHelp()
1445{
1446 Main::PrintHelp<StateMachineFeedback>();
1447
1448 /* Additional help text which is printed after the configuration
1449 options goes here */
1450
1451 /*
1452 cout << "bla bla bla" << endl << endl;
1453 cout << endl;
1454 cout << "Environment:" << endl;
1455 cout << "environment" << endl;
1456 cout << endl;
1457 cout << "Examples:" << endl;
1458 cout << "test exam" << endl;
1459 cout << endl;
1460 cout << "Files:" << endl;
1461 cout << "files" << endl;
1462 cout << endl;
1463 */
1464}
1465
1466int main(int argc, const char* argv[])
1467{
1468 Configuration conf(argv[0]);
1469 conf.SetPrintUsage(PrintUsage);
1470 Main::SetupConfiguration(conf);
1471 SetupConfiguration(conf);
1472
1473 if (!conf.DoParse(argc, argv, PrintHelp))
1474 return -1;
1475
1476 //try
1477 {
1478 // No console access at all
1479 if (!conf.Has("console"))
1480 {
1481// if (conf.Get<bool>("no-dim"))
1482// return RunShell<LocalStream, StateMachine, ConnectionFSC>(conf);
1483// else
1484 return RunShell<LocalStream>(conf);
1485 }
1486 // Cosole access w/ and w/o Dim
1487/* if (conf.Get<bool>("no-dim"))
1488 {
1489 if (conf.Get<int>("console")==0)
1490 return RunShell<LocalShell, StateMachine, ConnectionFSC>(conf);
1491 else
1492 return RunShell<LocalConsole, StateMachine, ConnectionFSC>(conf);
1493 }
1494 else
1495*/ {
1496 if (conf.Get<int>("console")==0)
1497 return RunShell<LocalShell>(conf);
1498 else
1499 return RunShell<LocalConsole>(conf);
1500 }
1501 }
1502 /*catch (std::exception& e)
1503 {
1504 cerr << "Exception: " << e.what() << endl;
1505 return -1;
1506 }*/
1507
1508 return 0;
1509}
Note: See TracBrowser for help on using the repository browser.