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

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