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

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