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

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