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

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