source: trunk/FACT++/src/ratescan.cc@ 13898

Last change on this file since 13898 was 13893, checked in by tbretz, 13 years ago
Updated to configure the ftm properly before a ratescan is started; added new configuration states and a callback to record the ftm state change properly.
File size: 17.0 KB
Line 
1#include <valarray>
2
3#include "Dim.h"
4#include "Event.h"
5#include "Shell.h"
6#include "StateMachineDim.h"
7#include "Connection.h"
8#include "Configuration.h"
9#include "Console.h"
10#include "Converter.h"
11//#include "PixelMap.h"
12
13#include "tools.h"
14
15#include "LocalControl.h"
16
17#include "HeadersFTM.h"
18
19namespace ba = boost::asio;
20namespace bs = boost::system;
21
22using namespace std;
23
24// ------------------------------------------------------------------------
25
26#include "DimDescriptionService.h"
27#include "DimState.h"
28
29// ------------------------------------------------------------------------
30
31class StateMachineRateScan : public StateMachineDim
32{
33private:
34 enum states_t
35 {
36 kStateDimNetworkNA = 1,
37 kStateDisconnected,
38 kStateConnecting,
39 kStateConnected,
40 kStateConfiguring,
41 kStateInProgress,
42 };
43
44 DimVersion fDim;
45 DimState fDimFTM;
46
47 DimDescribedService fDimData;
48 DimDescribedService fDimProc;
49
50 int fCounter;
51 int fCounterMax;
52
53 int fThreshold;
54 int fThresholdMin;
55 int fThresholdMax;
56 int fThresholdStep;
57 int fThresholdStepDyn;
58
59 double fRate;
60 double fRateBoard[40];
61 double fRatePatch[160];
62
63 double fOnTime;
64
65 uint64_t fStartTime;
66
67 float fResolution;
68
69 enum reference_t
70 {
71 kCamera,
72 kBoard,
73 kPatch
74 };
75
76 reference_t fReference;
77 uint16_t fReferenceIdx;
78
79 string fCommand;
80
81 void UpdateProc()
82 {
83 const array<uint32_t,3> v = {{ fThresholdMin, fThresholdMax, fThresholdStep }};
84 fDimProc.Update(v);
85 }
86
87 bool CheckEventSize(const EventImp &evt, size_t size)
88 {
89 if (size_t(evt.GetSize())==size)
90 return true;
91
92 if (evt.GetSize()==0)
93 return false;
94
95 ostringstream msg;
96 msg << evt.GetName() << " - Received event has " << evt.GetSize() << " bytes, but expected " << size << ".";
97 Fatal(msg);
98 return false;
99 }
100
101 int HandleTriggerRates(const EventImp &evt)
102 {
103 if (!CheckEventSize(evt, sizeof(FTM::DimTriggerRates)))
104 return GetCurrentState();
105
106 if (GetCurrentState()!=kStateInProgress)
107 return GetCurrentState();
108
109 const FTM::DimTriggerRates &sdata = *static_cast<const FTM::DimTriggerRates*>(evt.GetData());
110
111 if (++fCounter<0)
112 return GetCurrentState();
113
114 if (fCounter==0)
115 {
116 fRate = 0;
117
118 memset(fRateBoard, 0, 40*sizeof(double));
119 memset(fRatePatch, 0, 160*sizeof(double));
120
121 fOnTime = 0;
122 return GetCurrentState();
123 }
124/*
125 if (sdata.fTriggerRate==0)
126 {
127 Message("Rate scan stopped due zero trigger rate.");
128 fThreshold = -1;
129 return;
130 }
131*/
132
133 fRate += sdata.fTriggerRate;
134 for (int i=0; i<40; i++)
135 fRateBoard[i] += sdata.fBoardRate[i];
136 for (int i=0; i<160; i++)
137 fRatePatch[i] += sdata.fPatchRate[i];
138
139 double reference = fRate;
140 if (fReference==kBoard)
141 reference = fRateBoard[fReferenceIdx];
142 if (fReference==kPatch)
143 reference = fRatePatch[fReferenceIdx];
144
145 fOnTime += sdata.fOnTime;
146
147 reference *= sdata.fElapsedTime;
148
149 if ((reference==0 || sqrt(reference)>fResolution*reference) && fCounter<fCounterMax)
150 {
151 ostringstream out;
152 out << "Triggers so far: " << reference;
153 if (reference>0)
154 out << " (" << sqrt(reference)/reference << ")";
155 Info(out);
156
157 return GetCurrentState();
158 }
159
160 const double time = sdata.fElapsedTime*fCounter;
161 const uint32_t th = fThreshold;
162
163 float data[2+3+1+40+160];
164 memcpy(data, &fStartTime, 8);
165 memcpy(data+2, &th, 4);
166 data[3] = time; // total elapsed time
167 data[4] = fOnTime/time; // relative on time
168 data[5] = fRate/fCounter;
169 for (int i=0; i<40; i++)
170 data[i+6] = fRateBoard[i]/fCounter;
171 for (int i=0; i<160; i++)
172 data[i+46] = fRatePatch[i]/fCounter;
173
174 ostringstream sout1, sout2, sout3;
175
176 sout1 << th << " " << data[5];
177 for (int i=0; i<200; i++)
178 sout2 << " " << data[i+6];
179 sout3 << " " << data[3] << " " << data[4];
180
181 Info(sout1.str());
182
183 ofstream fout("ratescan.txt", ios::app);
184 fout << sout1.str() << sout2.str() << sout3.str() << endl;
185
186 fDimData.setQuality(fCommand=="FTM_CONTROL/SET_THRESHOLD");
187 fDimData.setData(data, sizeof(data));
188 fDimData.Update();
189
190 fThreshold += fThresholdStep;
191
192 if (fCounter>=fCounterMax)
193 {
194 Message("Rate scan stopped due to timeout.");
195 return kStateConnected;
196 }
197
198 if (fThreshold>fThresholdMax)
199 {
200 Message("Rate scan finished.");
201 return kStateConnected;
202 }
203
204 // Does this need to be shifted upwards?
205 if (fCounter>1 && fThresholdStepDyn>0)
206 {
207 //const double scale = fCounter/reference/fResolution/fResolution;
208 //const double step = floor(scale*fThresholdStepDyn);
209
210 fThresholdStep = fCounter*fThresholdStepDyn;
211 }
212
213 //fCounter = -2; // FIXME: In principle one missed report is enough
214 fCounter = -1;
215
216 const int32_t cmd[2] = { -1, fThreshold };
217 DimClient::sendCommandNB(fCommand.c_str(), (void*)cmd, 8);
218
219 return GetCurrentState();
220 }
221
222 int Print() const
223 {
224 Out() << fDim << endl;
225 Out() << fDimFTM << endl;
226
227 return GetCurrentState();
228 }
229
230 int StartRateScan(const EventImp &evt, const string &command)
231 {
232 if (!CheckEventSize(evt, 12))
233 return kSM_FatalError;
234
235 fCommand = "FTM_CONTROL/"+command;
236
237 const int32_t step = evt.Get<int32_t>(8);
238
239 fThresholdMin = evt.Get<uint32_t>();
240 fThresholdMax = evt.Get<uint32_t>(4);
241 fThresholdStep = abs(step);
242
243 fThresholdStepDyn = step<0 ? -step : 0;
244
245 UpdateProc();
246
247 const string data = "\0\0\0\0\0\0\0\0ratescan";
248
249 Dim::SendCommand("FAD_CONTROL/SET_FILE_FORMAT", uint16_t(0));
250 Dim::SendCommand("FTM_CONTROL/CONFIGURE", data);
251
252 Message("Configuration for ratescan started.");
253
254 return kStateConfiguring;
255 }
256
257 int HandleFtmStateChange(/*const EventImp &evt*/)
258 {
259 if (GetCurrentState()!=kStateConfiguring)
260 return GetCurrentState();
261
262 if (fDimFTM.state()!=FTM::kConfigured)
263 return GetCurrentState();
264
265 const int32_t data[2] = { -1, fThresholdMin };
266
267 Dim::SendCommand(fCommand, data);
268
269 fThreshold = fThresholdMin;
270 fCounter = -2;
271
272 const Time now;
273 fStartTime = trunc(now.UnixTime());
274
275 ofstream fout("ratescan.txt", ios::app);
276 fout << "# ----- " << now << " (" << fStartTime << ") -----\n";
277 fout << "# Command: " << fCommand << '\n';
278 fout << "# Reference: ";
279 switch (fReference)
280 {
281 case kCamera: fout << "Camera"; break;
282 case kBoard: fout << "Board #" << fReferenceIdx; break;
283 case kPatch: fout << "Patch #" << fReferenceIdx; break;
284 }
285 fout << '\n';
286 fout << "# -----" << endl;
287
288 ostringstream msg;
289 msg << "Rate scan " << now << "(" << fStartTime << ") from " << fThresholdMin << " to ";
290 msg << fThresholdMax << " in steps of " << fThresholdStep;
291 msg << " started.";
292 Message(msg);
293
294 return kStateInProgress;
295 }
296
297 int StopRateScan()
298 {
299 if (GetCurrentState()!=kStateConfiguring && GetCurrentState()!=kStateInProgress)
300 return GetCurrentState();
301
302 Message("Rate scan manually stopped.");
303
304 return kStateConnected;
305 }
306
307 int SetReferenceCamera()
308 {
309 fReference = kCamera;
310
311 return GetCurrentState();
312 }
313
314 int SetReferenceBoard(const EventImp &evt)
315 {
316 if (!CheckEventSize(evt, 4))
317 return kSM_FatalError;
318
319 if (evt.GetUInt()>39)
320 {
321 Error("SetReferenceBoard - Board index out of range [0;39]");
322 return GetCurrentState();
323 }
324
325 fReference = kBoard;
326 fReferenceIdx = evt.GetUInt();
327
328 return GetCurrentState();
329 }
330
331 int SetReferencePatch(const EventImp &evt)
332 {
333 if (!CheckEventSize(evt, 4))
334 return kSM_FatalError;
335
336 if (evt.GetUInt()>159)
337 {
338 Error("SetReferencePatch - Patch index out of range [0;159]");
339 return GetCurrentState();
340 }
341
342 fReference = kPatch;
343 fReferenceIdx = evt.GetUInt();
344
345 return GetCurrentState();
346 }
347
348 int ChangeStepSize(const EventImp &evt)
349 {
350 if (!CheckEventSize(evt, 4))
351 return kSM_FatalError;
352
353 fThresholdStep = evt.Get<uint32_t>();
354
355 ostringstream msg;
356 msg << "New step size " << fThresholdStep;
357 Info(msg);
358
359 UpdateProc();
360
361 return GetCurrentState();
362 }
363
364 int ChangeMaximum(const EventImp &evt)
365 {
366 if (!CheckEventSize(evt, 4))
367 return kSM_FatalError;
368
369 fThresholdMax = evt.Get<uint32_t>();
370
371 return GetCurrentState();
372 }
373
374 int Execute()
375 {
376 if (!fDim.online())
377 return kStateDimNetworkNA;
378
379 // All subsystems are not connected
380 if (fDimFTM.state()<FTM::kConnected)
381 return kStateDisconnected;
382
383 return GetCurrentState();
384 }
385
386public:
387 StateMachineRateScan(ostream &out=cout) : StateMachineDim(out, "RATE_SCAN"),
388 fDimFTM("FTM_CONTROL"),
389 fDimData("RATE_SCAN/DATA", "X:1;I:1;F:1;F:1;F:1;F:40;F:160",
390 "|Id[s]:Start time used to identify measurement (UnixTime)"
391 "|Threshold[dac]:Threshold in DAC counts"
392 "|ElapsedTime[s]:Real elapsed time"
393 "|RelOnTime[ratio]:Relative on time"
394 "|TriggerRate[Hz]:Camera trigger rate"
395 "|BoardRate[Hz]:Board trigger rates"
396 "|PatchRate[Hz]:Patch trigger rates"),
397 fDimProc("RATE_SCAN/PROCESS_DATA", "I:1;I:1;I:1",
398 "Rate scan process data"
399 "|min[DAC]:Value at which scan was started"
400 "|max[DAC]:Value at which scan will end"
401 "|step[DAC]:Step size for scan"),
402 fThreshold(-1), fReference(kCamera), fReferenceIdx(0)
403 {
404 // ba::io_service::work is a kind of keep_alive for the loop.
405 // It prevents the io_service to go to stopped state, which
406 // would prevent any consecutive calls to run()
407 // or poll() to do nothing. reset() could also revoke to the
408 // previous state but this might introduce some overhead of
409 // deletion and creation of threads and more.
410
411 fDim.Subscribe(*this);
412 fDimFTM.Subscribe(*this);
413 fDimFTM.SetCallback(bind(&StateMachineRateScan::HandleFtmStateChange, this));
414
415 Subscribe("FTM_CONTROL/TRIGGER_RATES")
416 (bind(&StateMachineRateScan::HandleTriggerRates, this, placeholders::_1));
417
418 // State names
419 AddStateName(kStateDimNetworkNA, "DimNetworkNotAvailable",
420 "The Dim DNS is not reachable.");
421
422 AddStateName(kStateDisconnected, "Disconnected",
423 "The Dim DNS is reachable, but the required subsystems are not available.");
424
425 AddStateName(kStateConnected, "Connected",
426 "All needed subsystems are connected to their hardware, no action is performed.");
427
428 AddStateName(kStateInProgress, "InProgress",
429 "Rate scan in progress.");
430
431 AddEvent("START_THRESHOLD_SCAN", "I:3", kStateConnected)
432 (bind(&StateMachineRateScan::StartRateScan, this, placeholders::_1, "SET_THRESHOLD"))
433 ("Start rate scan for the threshold in the defined range"
434 "|min[int]:Start value in DAC counts"
435 "|max[int]:Limiting value in DAC counts"
436 "|step[int]:Single step in DAC counts");
437
438 AddEvent("START_N_OUT_OF_4_SCAN", "I:3", kStateConnected)
439 (bind(&StateMachineRateScan::StartRateScan, this, placeholders::_1, "SET_N_OUT_OF_4"))
440 ("Start rate scan for N-out-of-4 in the defined range"
441 "|min[int]:Start value in DAC counts"
442 "|max[int]:Limiting value in DAC counts"
443 "|step[int]:Single step in DAC counts");
444
445 AddEvent("CHANGE_STEP_SIZE", "I:1", kStateInProgress)
446 (bind(&StateMachineRateScan::ChangeStepSize, this, placeholders::_1))
447 ("Change the step size during a ratescan in progress"
448 "|step[int]:Single step in DAC counts");
449
450 AddEvent("CHANGE_MAXIMUM", "I:1", kStateInProgress)
451 (bind(&StateMachineRateScan::ChangeMaximum, this, placeholders::_1))
452 ("Change the maximum limit during a ratescan in progress"
453 "|max[int]:Limiting value in DAC counts");
454
455 AddEvent("STOP", kStateConfiguring, kStateInProgress)
456 (bind(&StateMachineRateScan::StopRateScan, this))
457 ("Stop a ratescan in progress");
458
459 AddEvent("SET_REFERENCE_CAMERA", kStateDimNetworkNA, kStateDisconnected, kStateConnected)
460 (bind(&StateMachineRateScan::SetReferenceCamera, this))
461 ("Use the camera trigger rate as reference for the reolution");
462 AddEvent("SET_REFERENCE_BOARD", "I:1", kStateDimNetworkNA, kStateDisconnected, kStateConnected)
463 (bind(&StateMachineRateScan::SetReferenceBoard, this, placeholders::_1))
464 ("Use the given board trigger-rate as reference for the reolution"
465 "|board[idx]:Index of the board (4*crate+board)");
466 AddEvent("SET_REFERENCE_PATCH", "I:1", kStateDimNetworkNA, kStateDisconnected, kStateConnected)
467 (bind(&StateMachineRateScan::SetReferenceBoard, this, placeholders::_1))
468 ("Use the given patch trigger-rate as reference for the reolution"
469 "|patch[idx]:Index of the patch (360*crate+36*board+patch)" );
470
471 AddEvent("PRINT")
472 (bind(&StateMachineRateScan::Print, this))
473 ("");
474 }
475
476 int EvalOptions(Configuration &conf)
477 {
478 fCounterMax = conf.Get<uint16_t>("max-wait");
479 fResolution = conf.Get<double>("resolution");
480
481 return -1;
482 }
483};
484
485// ------------------------------------------------------------------------
486
487#include "Main.h"
488
489template<class T>
490int RunShell(Configuration &conf)
491{
492 return Main::execute<T, StateMachineRateScan>(conf);
493}
494
495void SetupConfiguration(Configuration &conf)
496{
497 po::options_description control("Rate scan options");
498 control.add_options()
499 ("max-wait", var<uint16_t>(150), "The maximum number of seconds to wait to get the anticipated resolution for a point.")
500 ("resolution", var<double>(0.05) , "The minimum resolution required for a single data point.")
501 ;
502
503 conf.AddOptions(control);
504}
505
506/*
507 Extract usage clause(s) [if any] for SYNOPSIS.
508 Translators: "Usage" and "or" here are patterns (regular expressions) which
509 are used to match the usage synopsis in program output. An example from cp
510 (GNU coreutils) which contains both strings:
511 Usage: cp [OPTION]... [-T] SOURCE DEST
512 or: cp [OPTION]... SOURCE... DIRECTORY
513 or: cp [OPTION]... -t DIRECTORY SOURCE...
514 */
515void PrintUsage()
516{
517 cout <<
518 "The ratescan program is a tool for automation of rate scans.\n"
519 "\n"
520 "Usage: ratescan [-c type] [OPTIONS]\n"
521 " or: ratescan [OPTIONS]\n";
522 cout << endl;
523}
524
525void PrintHelp()
526{
527 Main::PrintHelp<StateMachineRateScan>();
528
529 /* Additional help text which is printed after the configuration
530 options goes here */
531
532 /*
533 cout << "bla bla bla" << endl << endl;
534 cout << endl;
535 cout << "Environment:" << endl;
536 cout << "environment" << endl;
537 cout << endl;
538 cout << "Examples:" << endl;
539 cout << "test exam" << endl;
540 cout << endl;
541 cout << "Files:" << endl;
542 cout << "files" << endl;
543 cout << endl;
544 */
545}
546
547int main(int argc, const char* argv[])
548{
549 Configuration conf(argv[0]);
550 conf.SetPrintUsage(PrintUsage);
551 Main::SetupConfiguration(conf);
552 SetupConfiguration(conf);
553
554 if (!conf.DoParse(argc, argv, PrintHelp))
555 return -1;
556
557 //try
558 {
559 // No console access at all
560 if (!conf.Has("console"))
561 {
562// if (conf.Get<bool>("no-dim"))
563// return RunShell<LocalStream, StateMachine, ConnectionFSC>(conf);
564// else
565 return RunShell<LocalStream>(conf);
566 }
567 // Cosole access w/ and w/o Dim
568/* if (conf.Get<bool>("no-dim"))
569 {
570 if (conf.Get<int>("console")==0)
571 return RunShell<LocalShell, StateMachine, ConnectionFSC>(conf);
572 else
573 return RunShell<LocalConsole, StateMachine, ConnectionFSC>(conf);
574 }
575 else
576*/ {
577 if (conf.Get<int>("console")==0)
578 return RunShell<LocalShell>(conf);
579 else
580 return RunShell<LocalConsole>(conf);
581 }
582 }
583 /*catch (std::exception& e)
584 {
585 cerr << "Exception: " << e.what() << endl;
586 return -1;
587 }*/
588
589 return 0;
590}
Note: See TracBrowser for help on using the repository browser.