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

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