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

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