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

Last change on this file since 15459 was 15263, checked in by tbretz, 12 years ago
The file format is not changed automatically anymore... I think the reason for unintentionally written files is easier figured out than for missing ones.
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 // ftmctrl connected to FTM
249 if (GetCurrentState()!=RateScan::State::kConfiguring)
250 return GetCurrentState();
251
252 if (fDimFTM.state()!=FTM::State::kConfigured)
253 return GetCurrentState();
254
255 const int32_t data[2] = { -1, fThresholdMin };
256
257 Dim::SendCommand(fCommand, data);
258
259 fThreshold = fThresholdMin;
260 fCounter = -2;
261
262 const Time now;
263 fStartTime = trunc(now.UnixTime());
264
265 ofstream fout("ratescan.txt", ios::app);
266 fout << "# ----- " << now << " (" << fStartTime << ") -----\n";
267 fout << "# Command: " << fCommand << '\n';
268 fout << "# Reference: ";
269 switch (fReference)
270 {
271 case kCamera: fout << "Camera"; break;
272 case kBoard: fout << "Board #" << fReferenceIdx; break;
273 case kPatch: fout << "Patch #" << fReferenceIdx; break;
274 }
275 fout << '\n';
276 fout << "# -----" << endl;
277
278 ostringstream msg;
279 msg << "Rate scan " << now << "(" << fStartTime << ") from " << fThresholdMin << " to ";
280 msg << fThresholdMax << " in steps of " << fThresholdStep;
281 msg << " started.";
282 Message(msg);
283
284 return RateScan::State::kInProgress;
285 }
286
287 int StopRateScan()
288 {
289 if (GetCurrentState()!=RateScan::State::kConfiguring && GetCurrentState()!=RateScan::State::kInProgress)
290 return GetCurrentState();
291
292 Dim::SendCommand("FTM_CONTROL/RESET_CONFIGURE");
293 Message("Rate scan manually stopped.");
294
295 return RateScan::State::kConnected;
296 }
297
298 int SetReferenceCamera()
299 {
300 fReference = kCamera;
301
302 return GetCurrentState();
303 }
304
305 int SetReferenceBoard(const EventImp &evt)
306 {
307 if (!CheckEventSize(evt, 4))
308 return kSM_FatalError;
309
310 if (evt.GetUInt()>39)
311 {
312 Error("SetReferenceBoard - Board index out of range [0;39]");
313 return GetCurrentState();
314 }
315
316 fReference = kBoard;
317 fReferenceIdx = evt.GetUInt();
318
319 return GetCurrentState();
320 }
321
322 int SetReferencePatch(const EventImp &evt)
323 {
324 if (!CheckEventSize(evt, 4))
325 return kSM_FatalError;
326
327 if (evt.GetUInt()>159)
328 {
329 Error("SetReferencePatch - Patch index out of range [0;159]");
330 return GetCurrentState();
331 }
332
333 fReference = kPatch;
334 fReferenceIdx = evt.GetUInt();
335
336 return GetCurrentState();
337 }
338
339 int ChangeStepSize(const EventImp &evt)
340 {
341 if (!CheckEventSize(evt, 4))
342 return kSM_FatalError;
343
344 fThresholdStep = evt.Get<uint32_t>();
345
346 ostringstream msg;
347 msg << "New step size " << fThresholdStep;
348 Info(msg);
349
350 UpdateProc();
351
352 return GetCurrentState();
353 }
354
355 int ChangeMaximum(const EventImp &evt)
356 {
357 if (!CheckEventSize(evt, 4))
358 return kSM_FatalError;
359
360 fThresholdMax = evt.Get<uint32_t>();
361
362 return GetCurrentState();
363 }
364
365 int Execute()
366 {
367 if (!fDim.online())
368 return RateScan::State::kDimNetworkNA;
369
370 // All subsystems are not connected
371 if (fDimFTM.state()<FTM::State::kConnected)
372 return RateScan::State::kDisconnected;
373
374 // ftmctrl connected to FTM
375 if (GetCurrentState()<=RateScan::State::kDisconnected)
376 return RateScan::State::kConnected;
377
378 return GetCurrentState();
379 }
380
381public:
382 StateMachineRateScan(ostream &out=cout) : StateMachineDim(out, "RATE_SCAN"),
383 fDimFTM("FTM_CONTROL"),
384 fDimData("RATE_SCAN/DATA", "X:1;I:1;F:1;F:1;F:1;F:40;F:160",
385 "|Id[s]:Start time used to identify measurement (UnixTime)"
386 "|Threshold[dac]:Threshold in DAC counts"
387 "|ElapsedTime[s]:Real elapsed time"
388 "|RelOnTime[ratio]:Relative on time"
389 "|TriggerRate[Hz]:Camera trigger rate"
390 "|BoardRate[Hz]:Board trigger rates"
391 "|PatchRate[Hz]:Patch trigger rates"),
392 fDimProc("RATE_SCAN/PROCESS_DATA", "I:1;I:1;I:1",
393 "Rate scan process data"
394 "|min[DAC]:Value at which scan was started"
395 "|max[DAC]:Value at which scan will end"
396 "|step[DAC]:Step size for scan"),
397 fThreshold(-1), fReference(kCamera), fReferenceIdx(0)
398 {
399 // ba::io_service::work is a kind of keep_alive for the loop.
400 // It prevents the io_service to go to stopped state, which
401 // would prevent any consecutive calls to run()
402 // or poll() to do nothing. reset() could also revoke to the
403 // previous state but this might introduce some overhead of
404 // deletion and creation of threads and more.
405
406 fDim.Subscribe(*this);
407 fDimFTM.Subscribe(*this);
408 fDimFTM.SetCallback(bind(&StateMachineRateScan::HandleFtmStateChange, this));
409
410 Subscribe("FTM_CONTROL/TRIGGER_RATES")
411 (bind(&StateMachineRateScan::HandleTriggerRates, this, placeholders::_1));
412
413 // State names
414 AddStateName(RateScan::State::kDimNetworkNA, "DimNetworkNotAvailable",
415 "The Dim DNS is not reachable.");
416
417 AddStateName(RateScan::State::kDisconnected, "Disconnected",
418 "The Dim DNS is reachable, but the required subsystems are not available.");
419
420 AddStateName(RateScan::State::kConnected, "Connected",
421 "All needed subsystems are connected to their hardware, no action is performed.");
422
423 AddStateName(RateScan::State::kConfiguring, "Configuring",
424 "Waiting for FTM to get 'Configured'.");
425
426 AddStateName(RateScan::State::kInProgress, "InProgress",
427 "Rate scan in progress.");
428
429 AddEvent("START_THRESHOLD_SCAN", "I:3", RateScan::State::kConnected)
430 (bind(&StateMachineRateScan::StartRateScan, this, placeholders::_1, "SET_THRESHOLD"))
431 ("Start rate scan for the threshold in the defined range"
432 "|min[int]:Start value in DAC counts"
433 "|max[int]:Limiting value in DAC counts"
434 "|step[int]:Single step in DAC counts");
435
436 AddEvent("START_N_OUT_OF_4_SCAN", "I:3", RateScan::State::kConnected)
437 (bind(&StateMachineRateScan::StartRateScan, this, placeholders::_1, "SET_N_OUT_OF_4"))
438 ("Start rate scan for N-out-of-4 in the defined range"
439 "|min[int]:Start value in DAC counts"
440 "|max[int]:Limiting value in DAC counts"
441 "|step[int]:Single step in DAC counts");
442
443 AddEvent("CHANGE_STEP_SIZE", "I:1", RateScan::State::kInProgress)
444 (bind(&StateMachineRateScan::ChangeStepSize, this, placeholders::_1))
445 ("Change the step size during a ratescan in progress"
446 "|step[int]:Single step in DAC counts");
447
448 AddEvent("CHANGE_MAXIMUM", "I:1", RateScan::State::kInProgress)
449 (bind(&StateMachineRateScan::ChangeMaximum, this, placeholders::_1))
450 ("Change the maximum limit during a ratescan in progress"
451 "|max[int]:Limiting value in DAC counts");
452
453 AddEvent("STOP", RateScan::State::kConfiguring, RateScan::State::kInProgress)
454 (bind(&StateMachineRateScan::StopRateScan, this))
455 ("Stop a ratescan in progress");
456
457 AddEvent("SET_REFERENCE_CAMERA", RateScan::State::kDimNetworkNA, RateScan::State::kDisconnected, RateScan::State::kConnected)
458 (bind(&StateMachineRateScan::SetReferenceCamera, this))
459 ("Use the camera trigger rate as reference for the reolution");
460 AddEvent("SET_REFERENCE_BOARD", "I:1", RateScan::State::kDimNetworkNA, RateScan::State::kDisconnected, RateScan::State::kConnected)
461 (bind(&StateMachineRateScan::SetReferenceBoard, this, placeholders::_1))
462 ("Use the given board trigger-rate as reference for the reolution"
463 "|board[idx]:Index of the board (4*crate+board)");
464 AddEvent("SET_REFERENCE_PATCH", "I:1", RateScan::State::kDimNetworkNA, RateScan::State::kDisconnected, RateScan::State::kConnected)
465 (bind(&StateMachineRateScan::SetReferenceBoard, this, placeholders::_1))
466 ("Use the given patch trigger-rate as reference for the reolution"
467 "|patch[idx]:Index of the patch (360*crate+36*board+patch)");
468
469 AddEvent("PRINT")
470 (bind(&StateMachineRateScan::Print, this))
471 ("");
472 }
473
474 int EvalOptions(Configuration &conf)
475 {
476 fCounterMax = conf.Get<uint16_t>("max-wait");
477 fResolution = conf.Get<double>("resolution");
478
479 return -1;
480 }
481};
482
483// ------------------------------------------------------------------------
484
485#include "Main.h"
486
487template<class T>
488int RunShell(Configuration &conf)
489{
490 return Main::execute<T, StateMachineRateScan>(conf);
491}
492
493void SetupConfiguration(Configuration &conf)
494{
495 po::options_description control("Rate scan options");
496 control.add_options()
497 ("max-wait", var<uint16_t>(150), "The maximum number of seconds to wait to get the anticipated resolution for a point.")
498 ("resolution", var<double>(0.05) , "The minimum resolution required for a single data point.")
499 ;
500
501 conf.AddOptions(control);
502}
503
504/*
505 Extract usage clause(s) [if any] for SYNOPSIS.
506 Translators: "Usage" and "or" here are patterns (regular expressions) which
507 are used to match the usage synopsis in program output. An example from cp
508 (GNU coreutils) which contains both strings:
509 Usage: cp [OPTION]... [-T] SOURCE DEST
510 or: cp [OPTION]... SOURCE... DIRECTORY
511 or: cp [OPTION]... -t DIRECTORY SOURCE...
512 */
513void PrintUsage()
514{
515 cout <<
516 "The ratescan program is a tool for automation of rate scans.\n"
517 "\n"
518 "Usage: ratescan [-c type] [OPTIONS]\n"
519 " or: ratescan [OPTIONS]\n";
520 cout << endl;
521}
522
523void PrintHelp()
524{
525 Main::PrintHelp<StateMachineRateScan>();
526
527 /* Additional help text which is printed after the configuration
528 options goes here */
529
530 /*
531 cout << "bla bla bla" << endl << endl;
532 cout << endl;
533 cout << "Environment:" << endl;
534 cout << "environment" << endl;
535 cout << endl;
536 cout << "Examples:" << endl;
537 cout << "test exam" << endl;
538 cout << endl;
539 cout << "Files:" << endl;
540 cout << "files" << endl;
541 cout << endl;
542 */
543}
544
545int main(int argc, const char* argv[])
546{
547 Configuration conf(argv[0]);
548 conf.SetPrintUsage(PrintUsage);
549 Main::SetupConfiguration(conf);
550 SetupConfiguration(conf);
551
552 if (!conf.DoParse(argc, argv, PrintHelp))
553 return 127;
554
555 //try
556 {
557 // No console access at all
558 if (!conf.Has("console"))
559 {
560// if (conf.Get<bool>("no-dim"))
561// return RunShell<LocalStream, StateMachine, ConnectionFSC>(conf);
562// else
563 return RunShell<LocalStream>(conf);
564 }
565 // Cosole access w/ and w/o Dim
566/* if (conf.Get<bool>("no-dim"))
567 {
568 if (conf.Get<int>("console")==0)
569 return RunShell<LocalShell, StateMachine, ConnectionFSC>(conf);
570 else
571 return RunShell<LocalConsole, StateMachine, ConnectionFSC>(conf);
572 }
573 else
574*/ {
575 if (conf.Get<int>("console")==0)
576 return RunShell<LocalShell>(conf);
577 else
578 return RunShell<LocalConsole>(conf);
579 }
580 }
581 /*catch (std::exception& e)
582 {
583 cerr << "Exception: " << e.what() << endl;
584 return -1;
585 }*/
586
587 return 0;
588}
Note: See TracBrowser for help on using the repository browser.