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

Last change on this file since 12350 was 12350, checked in by tbretz, 13 years ago
Do directly set the new reference in SetReference.
File size: 27.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 kStateConnected,
54 kStateTempCtrlIdle,
55 kStateFeedbackCtrlIdle,
56 kStateTempCtrlRunning,
57 kStateFeedbackCtrlRunning,
58 };
59
60 enum control_t
61 {
62 kIdle,
63 kTemp,
64 kFeedback
65 };
66
67 control_t fControlType;
68
69 PixelMap fMap;
70
71 DimServiceInfoList fNetwork;
72
73 pair<Time, int> fStatusDim;
74 pair<Time, int> fStatusFAD;
75 pair<Time, int> fStatusFSC;
76 pair<Time, int> fStatusBias;
77
78 DimStampedInfo fDim;
79 DimStampedInfo fFAD;
80 DimStampedInfo fFSC;
81 DimStampedInfo fBias;
82
83 DimStampedInfo fBiasData;
84 DimStampedInfo fCameraTemp;
85
86 DimDescribedService fDimReference;
87 DimDescribedService fDimDeviation;
88
89 vector<vector<float>> fData;
90
91 uint64_t fCursor;
92
93 Time fBiasLast;
94 Time fStartTime;
95
96 valarray<double> fPV[3]; // Process variable (intgerated/averaged amplitudes)
97 valarray<double> fSP; // Set point (target amplitudes)
98
99 double fKp; // Proportional constant
100 double fKi; // Integral constant
101 double fKd; // Derivative constant
102 double fT; // Time constant (cycle time)
103 double fGain; // Gain (conversion from a DRS voltage deviation into a BIAS voltage change at G-APD reference voltage)
104
105 double fT21;
106
107 double fBiasOffset;
108
109 bool fOutputEnabled;
110
111 pair<Time, int> GetNewState(DimStampedInfo &info) const
112 {
113 const bool disconnected = info.getSize()==0;
114
115 // Make sure getTimestamp is called _before_ getTimestampMillisecs
116 const int tsec = info.getTimestamp();
117 const int tms = info.getTimestampMillisecs();
118
119 return make_pair(Time(tsec, tms*1000),
120 disconnected ? -2 : info.getQuality());
121 }
122
123 void ResetData()
124 {
125 fData.clear();
126 fData.resize(500);
127 fCursor = 0;
128 fStartTime = Time();
129
130 fSP.resize(416);
131 fSP = valarray<double>(0., 416);
132
133 vector<float> vec(2*BIAS::kNumChannels);
134 fDimDeviation.Update(vec);
135
136 fPV[0].resize(0);
137 fPV[1].resize(0);
138 fPV[2].resize(0);
139
140 if (fKp==0 && fKi==0 && fKd==0)
141 Warn("Control loop parameters are all set to zero.");
142 }
143
144 void infoHandler()
145 {
146 DimInfo *curr = getInfo(); // get current DimInfo address
147 if (!curr)
148 return;
149
150 if (curr==&fBias)
151 {
152 fStatusBias = GetNewState(fBias);
153 return;
154 }
155
156 if (curr==&fFAD)
157 {
158 fStatusFAD = GetNewState(fFAD);
159 return;
160 }
161
162 if (curr==&fFSC)
163 {
164 fStatusFSC = GetNewState(fFSC);
165 return;
166 }
167
168 if (curr==&fDim)
169 {
170 fStatusDim = GetNewState(fDim);
171 fStatusDim.second = curr->getSize()==4 ? curr->getInt() : 0;
172 return;
173 }
174
175 if (curr==&fCameraTemp)
176 {
177 if (curr->getSize()==0)
178 return;
179 if (curr->getSize()!=60*sizeof(float))
180 return;
181
182 const float *ptr = (float*)curr->getData();
183
184 double avg = 0;
185 int num = 0;
186 for (int i=1; i<32; i++)
187 if (ptr[i]!=0)
188 {
189 avg += ptr[i];
190 num++;
191 }
192
193 if (num==0)
194 return;
195
196 avg /= num;
197
198
199 const float diff = (avg-25)*4./70 + fBiasOffset;
200
201 vector<float> vec(2*BIAS::kNumChannels);
202 for (int i=0; i<BIAS::kNumChannels; i++)
203 vec[i+416] = diff;
204
205 if (fControlType!=kTemp)
206 return;
207
208 fDimDeviation.Update(vec);
209
210 if (fOutputEnabled && fStatusBias.second==BIAS::kVoltageOn)
211 {
212 Info("Sending correction to feedback.");
213
214 DimClient::sendCommandNB((char*)"BIAS_CONTROL/SET_GAPD_REFERENCE_OFFSET",
215 (void*)&diff, sizeof(float));
216 }
217 return;
218 }
219
220 if (curr==&fBiasData && fControlType==kFeedback)
221 {
222 if (curr->getSize()==0)
223 return;
224 if (curr->getSize()!=1440*sizeof(float))
225 return;
226
227 // -------- Check age of last stored event --------
228
229 // Must be called in this order
230 const int tsec = curr->getTimestamp();
231 const int tms = curr->getTimestampMillisecs();
232
233 const Time tm(tsec, tms*1000);
234
235 if (Time()-fBiasLast>boost::posix_time::seconds(30))
236 {
237 Warn("Last received event data older than 30s... resetting average calculation.");
238 ResetData();
239 }
240 fBiasLast = tm;
241
242 // -------- Store new event --------
243
244 fData[fCursor%fData.size()].assign(reinterpret_cast<float*>(curr->getData()),
245 reinterpret_cast<float*>(curr->getData())+1440);
246
247
248 fCursor++;
249
250 if (fCursor<fData.size())
251 return;
252
253 // -------- Calculate statistics --------
254
255 valarray<double> med(1440);
256
257 for (int ch=0; ch<1440; ch++)
258 {
259 vector<float> arr(fData.size());
260 for (size_t i=0; i<fData.size(); i++)
261 arr[i] = fData[i][ch];
262
263 sort(arr.begin(), arr.end());
264
265 med[ch] = arr[arr.size()/2];
266 }
267
268 /*
269 vector<float> med(1440);
270 vector<float> rms(1440);
271 for (size_t i=0; i<fData.size(); i++)
272 {
273 if (fData[i].size()==0)
274 return;
275
276 for (int j=0; j<1440; j++)
277 {
278 med[j] += fData[i][j];
279 rms[j] += fData[i][j]*fData[i][j];
280 }
281 }
282 */
283
284 vector<double> avg(BIAS::kNumChannels);
285 vector<int> num(BIAS::kNumChannels);
286 for (int i=0; i<1440; i++)
287 {
288 const PixelMapEntry &ch = fMap.hw(i);
289
290 // FIXME: Add a consistency check if the median makes sense...
291 // FIXME: Add a consistency check to remove pixels with bright stars (median?)
292
293 avg[ch.hv()] += med[i];
294 num[ch.hv()]++;
295 }
296
297 for (int i=0; i<BIAS::kNumChannels; i++)
298 {
299 if (num[i])
300 avg[i] /= num[i];
301
302 }
303
304 // -------- Calculate correction --------
305
306 // http://bestune.50megs.com/typeABC.htm
307
308 // CO: Controller output
309 // PV: Process variable
310 // SP: Set point
311 // T: Sampling period (loop update period)
312 // e = SP - PV
313 //
314 // Kp : No units
315 // Ki : per seconds
316 // Kd : seconds
317
318 // 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) ]
319
320 if (fCursor%fData.size()==0)
321 {
322 // FIXME: Take out broken / dead boards.
323
324 const Time tm0 = Time();
325
326 const double T21 = fT>0 ? fT : (tm0-fStartTime).total_microseconds()/1000000.;
327 const double T10 = fT21;
328 fT21 = T21;
329
330 fStartTime = tm0;
331
332 ostringstream out;
333 out << "New " << fData.size() << " event received: " << fCursor << " / " << setprecision(3) << T21 << "s";
334 Info(out);
335
336 if (fPV[0].size()==0)
337 {
338 fPV[0].resize(avg.size());
339 fPV[0] = valarray<double>(avg.data(), avg.size());
340 }
341 else
342 if (fPV[1].size()==0)
343 {
344 fPV[1].resize(avg.size());
345 fPV[1] = valarray<double>(avg.data(), avg.size());
346 }
347 else
348 if (fPV[2].size()==0)
349 {
350 fPV[2].resize(avg.size());
351 fPV[2] = valarray<double>(avg.data(), avg.size());
352 }
353 else
354 {
355 fPV[0] = fPV[1];
356 fPV[1] = fPV[2];
357
358 fPV[2].resize(avg.size());
359 fPV[2] = valarray<double>(avg.data(), avg.size());
360
361 if (T10<=0 || T21<=0)
362 return;
363
364 cout << "Calculating (" << fCursor << ":" << T21 << ")... " << endl;
365
366 // fKi[j] = response[j]*gain;
367 // Kp = 0;
368 // Kd = 0;
369
370 // => Kp = 0.01 * gain = 0.00005
371 // => Ki = 0.8 * gain/20s = 0.00025
372 // => Kd = 0.1 * gain/20s = 0.00003
373
374 //valarray<double> correction =
375 // - Kp * (PV[2] - PV[1])
376 // + dT * Ki * (SP - PV[2])
377 // - Kd / dT * (PV[2] - 2*PV[1] + PV[0]);
378 //
379 // - (Kp+Kd/dT1) * (PV[2] - PV[1])
380 // + dT2 * Ki * (SP - PV[2])
381 // + Kd / dT1 * (PV[1] - PV[0]);
382 //
383 // - Kp * (PV[2] - PV[1])
384 // + Ki * (SP - PV[2])*dT
385 // - Kd * (PV[2] - PV[1])/dT
386 // + Kd * (PV[1] - PV[0])/dT;
387 //
388 //valarray<double> correction =
389 // - Kp*(PV[2] - PV[1]) + Ki * T21 * (SP-PV[2]) - Kd*(PV[2]-PV[1])/T21 - Kd*(PV[0]-PV[1])/T01;
390 const valarray<double> correction = fGain/1000*
391 (
392 - (fKp+fKd/T21)*(fPV[2] - fPV[1])
393 + fKi*T21*(fSP-fPV[2])
394 + fKd/T10*(fPV[1]-fPV[0])
395 );
396
397 /*
398 integral = 0
399 start:
400 integral += (fSP - fPV[2])*dt
401
402 output = Kp*(fSP - fPV[2]) + Ki*integral - Kd*(fPV[2] - fPV[1])/dt
403
404 wait(dt)
405
406 goto start
407 */
408
409 vector<float> vec(2*BIAS::kNumChannels);
410 for (int i=0; i<BIAS::kNumChannels; i++)
411 vec[i] = fPV[2][i]-fSP[i];
412
413 for (int i=0; i<BIAS::kNumChannels; i++)
414 vec[i+416] = avg[i]<5*2.5 ? 0 : correction[i];
415
416 fDimDeviation.Update(vec);
417
418 if (fOutputEnabled && fStatusBias.second==BIAS::kVoltageOn)
419 {
420 Info("Sending correction to feedback.");
421
422 DimClient::sendCommandNB((char*)"BIAS_CONTROL/ADD_REFERENCE_VOLTAGES",
423 (void*)(vec.data()+416), 416*sizeof(float));
424
425 /*
426 if (!Dim::SendCommand("BIAS_CONTROL/ADD_REFERENCE_VOLTAGES",
427 (const void*)(vec.data()+416), 416*sizeof(float)))
428 {
429 Error("Sending correction to bias control failed... switching off.");
430 fOutputEnabled=false;
431 }
432 else
433 Info("Success!");
434 */
435 }
436 }
437
438 }
439
440 /*
441 vector<float> correction(416);
442 vector<float> response(416);
443 vector<float> dev(416);
444
445 double gain = 0;
446
447 for (int j=0; j<416; j++)
448 {
449 //avg[j] /= fData.size();
450 //rms[j] /= sqrt((rms[j]*fData.size() - avg[j]*avg[j]))/fData.size();
451
452 dev[j] = avg[j] - target[j];
453
454 // Determine correction from response maxtrix and change voltages
455 correction[j] = -dev[j]*response[j]*gain;
456
457 if (correction[j]==0)
458 continue;
459
460 // Limit voltage steps // Limit changes to 100 mV
461// if (fabs(correction[j]) > 0.1)
462// correction[j] = 0.1*fabs(correction[j])/correction[j];
463
464 // Add voltage change command if not too noisy
465// if (fabs(Average[i]) > 2*Sigma[i])
466// Cmd << fIDTable[i] << " " << std::showpos << Correction/Multiplicity[i] << " ";
467
468 }
469 */
470 return;
471 }
472
473 }
474
475 bool CheckEventSize(size_t has, const char *name, size_t size)
476 {
477 if (has==size)
478 return true;
479
480 ostringstream msg;
481 msg << name << " - Received event has " << has << " bytes, but expected " << size << ".";
482 Fatal(msg);
483 return false;
484 }
485
486 void PrintState(const pair<Time,int> &state, const char *server)
487 {
488 const State rc = fNetwork.GetState(server, state.second);
489
490 Out() << state.first.GetAsStr("%H:%M:%S.%f").substr(0, 12) << " - ";
491 Out() << kBold << server << ": ";
492 Out() << rc.name << "[" << rc.index << "]";
493 Out() << kReset << " - " << kBlue << rc.comment << endl;
494 }
495
496 int Print()
497 {
498 Out() << fStatusDim.first.GetAsStr("%H:%M:%S.%f").substr(0, 12) << " - ";
499 Out() << kBold << "DIM_DNS: ";
500 if (fStatusDim.second==0)
501 Out() << "Offline" << endl;
502 else
503 Out() << "V" << fStatusDim.second/100 << 'r' << fStatusDim.second%100 << endl;
504
505 PrintState(fStatusFAD, "FAD_CONTROL");
506 PrintState(fStatusBias, "BIAS_CONTROL");
507
508 return GetCurrentState();
509 }
510
511 int SetConstant(const EventImp &evt, int constant)
512 {
513 if (!CheckEventSize(evt.GetSize(), "SetConstant", 8))
514 return kSM_FatalError;
515
516 switch (constant)
517 {
518 case 0: fKi = evt.GetDouble(); break;
519 case 1: fKp = evt.GetDouble(); break;
520 case 2: fKd = evt.GetDouble(); break;
521 case 3: fT = evt.GetDouble(); break;
522 case 4: fGain = evt.GetDouble(); break;
523 default:
524 Fatal("SetConstant got an unexpected constant id -- this is a program bug!");
525 return kSM_FatalError;
526 }
527
528 return GetCurrentState();
529 }
530
531 int EnableOutput(const EventImp &evt)
532 {
533 if (!CheckEventSize(evt.GetSize(), "EnableOutput", 1))
534 return kSM_FatalError;
535
536 fOutputEnabled = evt.GetBool();
537
538 return GetCurrentState();
539 }
540
541 int StartFeedback()
542 {
543 ResetData();
544
545 fControlType = kFeedback;
546
547 return GetCurrentState();
548 }
549
550 int StartTempCtrl(const EventImp &evt)
551 {
552 if (!CheckEventSize(evt.GetSize(), "StartTempCtrl", 4))
553 return kSM_FatalError;
554
555 ostringstream out;
556 out << "Starting temperature feedback with an offset of " << fBiasOffset << "V";
557 Message(out);
558
559 fBiasOffset = evt.GetFloat();
560 fControlType = kTemp;
561
562 return GetCurrentState();
563 }
564
565 int StopFeedback()
566 {
567 fControlType = kIdle;
568
569 return GetCurrentState();
570 }
571
572 int StoreReference()
573 {
574 if (!fPV[0].size() && !fPV[1].size() && !fPV[2].size())
575 {
576 Warn("No values in memory. Take enough events first!");
577 return GetCurrentState();
578 }
579
580 // FIXME: Check age
581
582 if (!fPV[1].size() && !fPV[2].size())
583 fSP = fPV[0];
584
585 if (!fPV[2].size())
586 fSP = fPV[1];
587 else
588 fSP = fPV[2];
589
590 vector<float> vec(BIAS::kNumChannels);
591 for (int i=0; i<BIAS::kNumChannels; i++)
592 vec[i] = fSP[i];
593 fDimReference.Update(vec);
594
595 return GetCurrentState();
596 }
597
598 int SetReference(const EventImp &evt)
599 {
600 if (!CheckEventSize(evt.GetSize(), "SetReference", 4))
601 return kSM_FatalError;
602
603 const float val = evt.GetFloat();
604 /*
605 if (!fPV[0].size() && !fPV[1].size() && !fPV[2].size())
606 {
607 Warn("No values in memory. Take enough events first!");
608 return GetCurrentState();
609 }*/
610
611 vector<float> vec(BIAS::kNumChannels);
612 for (int i=0; i<BIAS::kNumChannels; i++)
613 vec[i] = fSP[i] = val;
614 fDimReference.Update(vec);
615
616 return GetCurrentState();
617 }
618
619
620 int Execute()
621 {
622 // Dispatch (execute) at most one handler from the queue. In contrary
623 // to run_one(), it doesn't wait until a handler is available
624 // which can be dispatched, so poll_one() might return with 0
625 // handlers dispatched. The handlers are always dispatched/executed
626 // synchronously, i.e. within the call to poll_one()
627 //poll_one();
628
629 if (fStatusDim.second==0)
630 return kStateDimNetworkNA;
631
632 // All subsystems are not connected
633 if (fStatusFAD.second<FAD::kConnected &&
634 fStatusBias.second<BIAS::kConnecting &&
635 fStatusFSC.second<2)
636 return kStateDisconnected;
637
638 // At least one subsystem is not connected
639 if (fStatusFAD.second<FAD::kConnected ||
640 fStatusBias.second<BIAS::kConnected ||
641 fStatusFSC.second<2)
642 return kStateConnecting;
643
644 // All subsystems are connected
645
646 if (fControlType==kFeedback)
647 return fOutputEnabled ? kStateFeedbackCtrlRunning : kStateFeedbackCtrlIdle;
648
649 if (fControlType==kTemp)
650 return fOutputEnabled ? kStateTempCtrlRunning : kStateTempCtrlIdle;
651
652 return kStateConnected;
653 }
654
655public:
656 StateMachineFeedback(ostream &out=cout) : StateMachineDim(out, "FEEDBACK"),
657 fStatusDim(make_pair(Time(), -2)),
658 fStatusFAD(make_pair(Time(), -2)),
659 fStatusBias(make_pair(Time(), -2)),
660 fDim("DIS_DNS/VERSION_NUMBER", (void*)NULL, 0, this),
661 fFAD("FAD_CONTROL/STATE", (void*)NULL, 0, this),
662 fFSC("FSC_CONTROL/STATE", (void*)NULL, 0, this),
663 fBias("BIAS_CONTROL/STATE", (void*)NULL, 0, this),
664 fBiasData("FAD_CONTROL/FEEDBACK_DATA", (void*)NULL, 0, this),
665 fCameraTemp("FSC_CONTROL/TEMPERATURE", (void*)NULL, 0, this),
666 fDimReference("FEEDBACK/REFERENCE", "F:416", ""),
667 fDimDeviation("FEEDBACK/DEVIATION", "F:416;F:416", ""),
668 fKp(0), fKi(0), fKd(0), fT(-1), fOutputEnabled(false)
669 {
670 // ba::io_service::work is a kind of keep_alive for the loop.
671 // It prevents the io_service to go to stopped state, which
672 // would prevent any consecutive calls to run()
673 // or poll() to do nothing. reset() could also revoke to the
674 // previous state but this might introduce some overhead of
675 // deletion and creation of threads and more.
676
677 // State names
678 AddStateName(kStateDimNetworkNA, "DimNetworkNotAvailable",
679 "The Dim DNS is not reachable.");
680
681 AddStateName(kStateDisconnected, "Disconnected",
682 "The Dim DNS is reachable, but the required subsystems are not available.");
683
684 AddStateName(kStateConnecting, "Connecting",
685 "Not all subsystems (FAD, FSC, Bias) are connected to their hardware.");
686
687 AddStateName(kStateConnected, "Connected",
688 "All needed subsystems are connected to their hardware, no action is performed.");
689
690 AddStateName(kStateFeedbackCtrlIdle, "FeedbackIdle",
691 "Feedback control activated, but voltage output disabled.");
692
693 AddStateName(kStateTempCtrlIdle, "FeedbackIdle",
694 "Temperature control activated, but voltage output disabled.");
695
696 AddStateName(kStateFeedbackCtrlRunning, "FeedbackControl",
697 "Feedback control activated and voltage output enabled.");
698
699 AddStateName(kStateTempCtrlRunning, "TempControl",
700 "Temperature control activated and voltage output enabled.");
701
702 AddEvent("START_FEEDBACK_CONTROL", kStateConnected)
703 (bind(&StateMachineFeedback::StartFeedback, this))
704 ("Start the feedback control loop");
705
706 AddEvent("START_TEMP_CONTROL", "F:1", kStateConnected)
707 (bind(&StateMachineFeedback::StartTempCtrl, this, placeholders::_1))
708 ("Start the temperature control loop");
709
710 // kStateTempCtrlIdle, kStateFeedbackCtrlIdle, kStateTempCtrlRunning, kStateFeedbackCtrlRunning
711 AddEvent("STOP")
712 (bind(&StateMachineFeedback::StopFeedback, this))
713 ("Stop any control loop");
714
715 AddEvent("ENABLE_OUTPUT", "B:1")//, kStateIdle)
716 (bind(&StateMachineFeedback::EnableOutput, this, placeholders::_1))
717 ("Enable sending of correction values caluclated by the control loop to the biasctrl");
718
719 AddEvent("STORE_REFERENCE")//, kStateIdle)
720 (bind(&StateMachineFeedback::StoreReference, this))
721 ("Store the last (averaged) value as new reference (for debug purpose only)");
722
723 AddEvent("SET_REFERENCE", "F:1")//, kStateIdle)
724 (bind(&StateMachineFeedback::SetReference, this, placeholders::_1))
725 ("Set a new global reference value (for debug purpose only)");
726
727 AddEvent("SET_Ki", "D:1")//, kStateIdle)
728 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 0))
729 ("Set integral constant Ki");
730
731 AddEvent("SET_Kp", "D:1")//, kStateIdle)
732 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 1))
733 ("Set proportional constant Kp");
734
735 AddEvent("SET_Kd", "D:1")//, kStateIdle)
736 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 2))
737 ("Set derivative constant Kd");
738
739 AddEvent("SET_T", "D:1")//, kStateIdle)
740 (bind(&StateMachineFeedback::SetConstant, this, placeholders::_1, 3))
741 ("Set time-constant. (-1 to use the cycle time, i.e. the time for the last average cycle, instead)");
742
743 // Verbosity commands
744// AddEvent("SET_VERBOSE", "B:1")
745// (bind(&StateMachineMCP::SetVerbosity, this, placeholders::_1))
746// ("set verbosity state"
747// "|verbosity[bool]:disable or enable verbosity for received data (yes/no), except dynamic data");
748
749 AddEvent("PRINT")
750 (bind(&StateMachineFeedback::Print, this))
751 ("");
752 }
753
754 int EvalOptions(Configuration &conf)
755 {
756 if (!fMap.Read(conf.Get<string>("pixel-map-file")))
757 {
758 Error("Reading mapping table from "+conf.Get<string>("pixel-map-file")+" failed.");
759 return 1;
760 }
761
762 // -110 / -110 (-23 DAC / -0.51V)
763 // Reference voltage: -238 / -203
764 // -360 / -343 ( 23 DAC / 0.51V)
765
766 // 0.005 A/V
767 // 220 Amplitude / 1V
768
769 // Gain = 1V / 200 = 0.005
770
771 fGain = 5; // (BIAS)V / (DRS)V ( 1V / 0.22V )
772
773 fKp = 0;
774 fKd = 0;
775 fKi = 0.12;
776 fT = 1;
777
778 ostringstream msg;
779 msg << "Control loop parameters: ";
780 msg << "Kp=" << fKp << ", Kd=" << fKd << ", Ki=" << fKi << ", ";
781 if (fT>0)
782 msg << fT;
783 else
784 msg << "<auto>";
785 msg << ", Gain(BIAS/DRS)=" << fGain << "V/V";
786
787 Message(msg);
788
789 return -1;
790 }
791};
792
793// ------------------------------------------------------------------------
794
795#include "Main.h"
796
797template<class T>
798int RunShell(Configuration &conf)
799{
800 return Main::execute<T, StateMachineFeedback>(conf);
801}
802
803void SetupConfiguration(Configuration &conf)
804{
805 po::options_description control("Feedback options");
806 control.add_options()
807 ("pixel-map-file", var<string>("FACTmapV5a.txt"), "Pixel mapping file. Used here to get the default reference voltage.")
808 ;
809
810 conf.AddOptions(control);
811}
812
813/*
814 Extract usage clause(s) [if any] for SYNOPSIS.
815 Translators: "Usage" and "or" here are patterns (regular expressions) which
816 are used to match the usage synopsis in program output. An example from cp
817 (GNU coreutils) which contains both strings:
818 Usage: cp [OPTION]... [-T] SOURCE DEST
819 or: cp [OPTION]... SOURCE... DIRECTORY
820 or: cp [OPTION]... -t DIRECTORY SOURCE...
821 */
822void PrintUsage()
823{
824 cout <<
825 "The feedback control the BIAS voltages based on the calibration signal.\n"
826 "\n"
827 "The default is that the program is started without user intercation. "
828 "All actions are supposed to arrive as DimCommands. Using the -c "
829 "option, a local shell can be initialized. With h or help a short "
830 "help message about the usuage can be brought to the screen.\n"
831 "\n"
832 "Usage: feedback [-c type] [OPTIONS]\n"
833 " or: feedback [OPTIONS]\n";
834 cout << endl;
835}
836
837void PrintHelp()
838{
839 Main::PrintHelp<StateMachineFeedback>();
840
841 /* Additional help text which is printed after the configuration
842 options goes here */
843
844 /*
845 cout << "bla bla bla" << endl << endl;
846 cout << endl;
847 cout << "Environment:" << endl;
848 cout << "environment" << endl;
849 cout << endl;
850 cout << "Examples:" << endl;
851 cout << "test exam" << endl;
852 cout << endl;
853 cout << "Files:" << endl;
854 cout << "files" << endl;
855 cout << endl;
856 */
857}
858
859int main(int argc, const char* argv[])
860{
861 Configuration conf(argv[0]);
862 conf.SetPrintUsage(PrintUsage);
863 Main::SetupConfiguration(conf);
864 SetupConfiguration(conf);
865
866 if (!conf.DoParse(argc, argv, PrintHelp))
867 return -1;
868
869 //try
870 {
871 // No console access at all
872 if (!conf.Has("console"))
873 {
874// if (conf.Get<bool>("no-dim"))
875// return RunShell<LocalStream, StateMachine, ConnectionFSC>(conf);
876// else
877 return RunShell<LocalStream>(conf);
878 }
879 // Cosole access w/ and w/o Dim
880/* if (conf.Get<bool>("no-dim"))
881 {
882 if (conf.Get<int>("console")==0)
883 return RunShell<LocalShell, StateMachine, ConnectionFSC>(conf);
884 else
885 return RunShell<LocalConsole, StateMachine, ConnectionFSC>(conf);
886 }
887 else
888*/ {
889 if (conf.Get<int>("console")==0)
890 return RunShell<LocalShell>(conf);
891 else
892 return RunShell<LocalConsole>(conf);
893 }
894 }
895 /*catch (std::exception& e)
896 {
897 cerr << "Exception: " << e.what() << endl;
898 return -1;
899 }*/
900
901 return 0;
902}
Note: See TracBrowser for help on using the repository browser.