source: fact/FADctrl/FAD.cc@ 16540

Last change on this file since 16540 was 14278, checked in by ogrimm, 12 years ago
Added modified calibration procedure for FADctrl for new FAD-based stand-alone oscilloscope.
File size: 38.2 KB
Line 
1/********************************************************************\
2
3 Main class of FADCtrl
4
5 If outputting text with PrintMessage(), a '\r' is used on the console automatically
6 if the given text ends with '\n'.
7
8 Comment 19/10/2010: It is assumed that boolean access is an atomic operation.
9
10\********************************************************************/
11
12#include "FAD.h"
13using namespace std;
14
15static const struct CL_Struct { const char *Name;
16 void (FAD::*CommandPointer)();
17 bool NeedIdle;
18 unsigned int MinNumParameter;
19 const char *Parameters;
20 const char *Help;
21 } CommandList[] =
22 {{"board", &FAD::cmd_board, true, 1, "<[+|-]range|none>" ,"Activate or deactivate board(s)"},
23 {"status", &FAD::cmd_status, false, 0, "[range]", "Show board status information"},
24 {"domino", &FAD::cmd_domino, true, 1, "<on|off>", "Switch Domino wave"},
25 {"dwrite", &FAD::cmd_dwrite, true, 1, "<on|off>", "Set DWRITE"},
26 {"phase", &FAD::cmd_phase, true, 1, "<phase>", "Adjust ADC phase (in 'steps')"},
27 {"srclk", &FAD::cmd_srclk, true, 1, "<on|off>", "Set SRCLK"},
28 {"sclk", &FAD::cmd_sclk, true, 1, "<on|off>", "Set SCLK"},
29 {"trigger", &FAD::cmd_trigger, false, 0, "[n|cont [rate]|stop|enable|disable]", "Issue software triggers"},
30 {"drsreset", &FAD::cmd_drsreset, true, 1, "<low|high>", "Set DRS reset line"},
31 {"reset", &FAD::cmd_reset, true, 0, "", "Reset internal trigger counter"},
32 {"runnumber", &FAD::cmd_runnumber, true, 1, "<n>", "Set runnumber"},
33 {"roi", &FAD::cmd_roi, true, 2, "<range> <value>", "Set ROI to for channel range to value"},
34 {"dac", &FAD::cmd_dac, true, 2, "<range> <value>", "Set DAC numbers in range to value"},
35 {"execute", &FAD::cmd_execute, true, 0, "", "confirm FAD configuration settings, e.g. DAC, ROI, run#"},
36 {"address", &FAD::cmd_address, true, 2, "<range> <value>", "Set addresses in range to value"},
37 {"send", &FAD::cmd_send, true, 1, "<value>", "Send arbitrary data to board"},
38 {"take", &FAD::cmd_take, true, 1, "<n> <dir>", "Start run with n events (n=0 -> unlimited)"},
39 {"acalib", &FAD::cmd_acalib, true, 0, "[n|inval|file]", "Perform or read amplitude calibration (n events)"},
40 //{"wmode", &FAD::cmd_wmode, 0, "<run|stop>", "Domino wave running or stopped during read out"},
41 //{"rmode", &FAD::cmd_rmode, 0, "<first|stop>", "Readout start at first bin or stop position (DRS4)"},
42 //{"dmode", &FAD::cmd_dmode, 0, "<single|continuous>", "Domino wave single shot or continuous"},
43 {"stop", &FAD::cmd_stop, false, 0, "", "Stop current operation/run"},
44 {"update", &FAD::cmd_update, false, 1, "<sec>", "Minimum delay between updates to DIM event service"},
45 {"socketmode", &FAD::cmd_socketmode, true, 1, "<com|daq>", "Choose which Sockets are used for data transmission"},
46 {"dynrange", &FAD::cmd_dynrange, true, 0, "", "Determine dynamic range using calibration DAC"},
47 {"exit", &FAD::cmd_exit, false, 0, "", "Exit program"},
48 {"help", &FAD::cmd_help, false, 0, "", "Print help"}};
49
50
51// ------------------------------------
52// ***** Constructor/Destructor *****
53// ------------------------------------
54
55//
56// Constructor
57//
58FAD::FAD(std::vector<std::string> List): EvidenceServer(SERVER_NAME) {
59
60 // Initialization
61 ConsoleText = NULL;
62 MainThread = pthread_self();
63 Mode = idle;
64 Datafile = -1;
65 EventUpdateDelay = atof(GetConfig("EventUpdateDelay", "1").c_str());
66 ModifiedCalibration = false;
67
68 // Create pipe for data exchange
69 if (pipe(Pipe) == -1) Message(FATAL, "pipe() failed in FAD::FAD() (%s)", strerror(errno));
70
71 // DIM console service used in PrintMessage()
72 ConsoleOut = new DimService(SERVER_NAME"/ConsoleOut", (char *) "");
73
74 // Initialise configuration information (later non-blocking access in commandHandler())
75 GetConfig("CalibTempDiffWarn", "0");
76 GetConfig("CalibFreqDiffWarn", "0");
77
78 // Construct boards
79 if (List.empty()) BoardList = Tokenize(GetConfig("BoardList"));
80 else BoardList = List;
81
82 for (unsigned int i=0; i<BoardList.size(); i++) {
83 Boards.push_back(new class FADBoard(BoardList[i], PORT, this, i));
84 }
85
86 // Create DIM event service thread
87 int Ret;
88 if ((Ret = pthread_create(&Thread, NULL, (void * (*)(void *)) LaunchEventThread, (void *) this)) != 0) {
89 Message(FATAL, "pthread_create() failed in FAD::FAD() (%s)", strerror(Ret));
90 }
91
92 // Install DIM command (after all initialized)
93 Command = new DimCommand((char *) SERVER_NAME"/Command", (char *) "C", this);
94
95 // Initialise boards
96 vector<string> Init = Tokenize(GetConfig("InitSequence", "dac 0 28000; trigger enable; domino on;"), ";");
97
98 for (unsigned int i=0; i<Init.size(); i++) {
99 DimClient::sendCommand(SERVER_NAME"/Command", Init[i].c_str());
100 }
101}
102
103//
104// Destructor
105//
106FAD::~FAD() {
107
108 int Ret;
109
110 ExitRequest = true;
111
112 // Stop run if in progress
113 if (Mode != idle) cmd_stop();
114
115 // Close pipe (will make read() on pipe in DIM service thread return)
116 if (close(Pipe[0]) == -1) Message(ERROR, "close() on Pipe[0] failed in FAD::~FAD() (%s)", strerror(errno));
117 if (close(Pipe[1]) == -1) Message(ERROR, "close() on Pipe[1] failed in FAD::~FAD() (%s)", strerror(errno));
118
119 // Wait for DIM service thread to quit
120 if ((Ret = pthread_join(Thread, NULL)) != 0) Message(ERROR, "pthread_join() failed in ~FAD() (%s)", strerror(Ret));
121
122 // Delete all boards (cancels threads automatically)
123 for (unsigned int i=0; i<Boards.size(); i++) delete Boards[i];
124
125 delete Command;
126 delete ConsoleOut;
127 free(ConsoleText);
128}
129
130// ------------------------------
131// ***** Command handling *****
132// ------------------------------
133
134//
135// DIM command handler (non-blocking, otherwise a DIM rpc would dead-lock)
136//
137void FAD::commandHandler() {
138
139 char *Command = getCommand()->getString(), *Start;
140
141 // Ignore empty or illegal strings
142 if (getCommand()->getSize() == 0) return;
143 if( *(Command+getCommand()->getSize()-1) != '\0' || strlen(Command) == 0) return;
144
145 // Shell command
146 if (*Command == '.') {
147 if (system(Command+1) == -1) PrintMessage("Error with system() call\n");
148 return;
149 }
150
151 // Parse command into tokens
152 Parameter.clear();
153 while(true) {
154 while (isspace(*Command)) Command++; // Ignore initial white spaces
155 if(*Command=='\0') break;
156 if (*Command == '\"') {
157 Start = ++Command;
158 while(*Command!='\"' && *Command!='\0') Command++;
159 }
160 else {
161 Start = Command;
162 while(!isspace(*Command) && *Command!='\0') Command++;
163 }
164 if(*Command != '\0') *Command++ = '\0';
165 Parameter.push_back(Start);
166 }
167
168 // Search for command in command list
169 for(unsigned int n=0; n<sizeof(CommandList)/sizeof(CL_Struct); n++) {
170 if (Match(Parameter[0], CommandList[n].Name)) {
171 // Check if number of parameters
172 if(Parameter.size()-1 < CommandList[n].MinNumParameter) {
173 PrintMessage("Usage: %s %s\n", CommandList[n].Name, CommandList[n].Parameters);
174 return;
175 }
176 // Check if idle mode required
177 if (CommandList[n].NeedIdle && Mode != idle) {
178 PrintMessage("Current mode is not idle ('stop' will stop current operation)\n");
179 return;
180 }
181 // Jump to command function
182 (this->*CommandList[n].CommandPointer)();
183 return;
184 }
185 }
186
187 // Command not found
188 PrintMessage("Unknown command '%s'\n", Parameter[0].c_str());
189}
190
191//
192// Switch SRCLK
193//
194void FAD::cmd_srclk() {
195
196 for (unsigned int i=0; i<Boards.size(); i++) {
197 if (Match(Parameter[1],"on")) Boards[i]->Send(CMD_SRCLK_ON);
198 else if (Match(Parameter[1],"off")) Boards[i]->Send(CMD_SRCLK_OFF);
199 else {
200 PrintUsage();
201 return;
202 }
203 }
204}
205
206//
207// Reset internal trigger
208//
209
210void FAD::cmd_reset() {
211
212 for (unsigned int i=0; i<Boards.size(); i++) Boards[i]->Send(CMD_RESET_TRIGGER_ID);
213}
214
215
216//
217// Set DRS reset line
218//
219void FAD::cmd_drsreset() {
220
221 for (unsigned int i=0; i<Boards.size(); i++) {
222 if (Match(Parameter[1], "low")) Boards[i]->Send(CMD_DRS_RST_LOW);
223 else if (Match(Parameter[1], "high")) Boards[i]->Send(CMD_DRS_RST_HIGH);
224 else {
225 PrintUsage();
226 return;
227 }
228 }
229}
230
231//
232// Execute: Confirm new ROI, DAC or what ever settings
233//
234void FAD::cmd_execute() {
235
236 for (unsigned int i=0; i<Boards.size(); i++) Boards[i]->Send(CMD_Execute);
237}
238
239//
240// Set run number
241//
242void FAD::cmd_runnumber() {
243
244 unsigned short Buffer[4] = {0};
245 int Num;
246
247 if (!ConvertToInt(Parameter[1], &Num)) {
248 PrintMessage("Error, incorrect parameter for run number\n");
249 return;
250 }
251 Buffer[0] = htons(CMD_Write | ADDR_RUNNUMBER);
252 Buffer[1] = htons( (unsigned short)( ((unsigned int)Num) >> 16 ) );
253 Buffer[2] = htons(CMD_Write | (ADDR_RUNNUMBER + 1) );
254 Buffer[3] = htons( (unsigned short)Num );
255
256 for (unsigned int i=0; i<Boards.size(); i++) {
257 Boards[i]->Send(Buffer, sizeof(Buffer));
258 Boards[i]->Send(CMD_Execute);
259 }
260}
261
262//
263// Switch socket mode
264// "com" - command mode (only socket 0 is used for event data transmission)
265// "daq" - daq mode (only sockets 1 - 7 are used)
266void FAD::cmd_socketmode() {
267
268 for (unsigned int i=0; i<Boards.size(); i++) {
269 if (Match(Parameter[1],"com")) Boards[i]->Send(CMD_mode_command);
270 else if (Match(Parameter[1],"daq")) Boards[i]->Send(CMD_mode_all_sockets);
271 else {
272 PrintUsage();
273 return;
274 }
275 }
276}
277
278//
279// Switch SCLK
280//
281void FAD::cmd_sclk() {
282
283 for (unsigned int i=0; i<Boards.size(); i++) {
284 if (Match(Parameter[1],"on")) Boards[i]->Send(CMD_SCLK_ON);
285 else if (Match(Parameter[1],"off")) Boards[i]->Send(CMD_SCLK_OFF);
286 else {
287 PrintUsage();
288 return;
289 }
290 }
291}
292
293//
294// Switch Domino wave
295//
296void FAD::cmd_domino() {
297
298 for (unsigned int i=0; i<Boards.size(); i++) {
299 if (Match(Parameter[1],"on")) Boards[i]->Send(CMD_DENABLE);
300 else if (Match(Parameter[1],"off")) Boards[i]->Send(CMD_DDISABLE);
301 else {
302 PrintUsage();
303 return;
304 }
305 }
306}
307
308//
309// Switch DWRITE
310//
311void FAD::cmd_dwrite() {
312
313 for (unsigned int i=0; i<Boards.size(); i++) {
314 if (Match(Parameter[1],"on")) Boards[i]->Send(CMD_DWRITE_RUN);
315 else if (Match(Parameter[1],"off")) Boards[i]->Send(CMD_DWRITE_STOP);
316 else {
317 PrintUsage();
318 return;
319 }
320 }
321}
322
323//
324// Issue soft trigger
325//
326void FAD::cmd_trigger() {
327
328 int Num;
329
330 for (unsigned int i=0; i<Boards.size(); i++) {
331 if (Parameter.size() == 1) Boards[i]->Send(CMD_Trigger);
332 else if (ConvertToInt(Parameter[1], &Num)) {
333 for (int j=0; j<Num; j++) Boards[i]->Send(CMD_Trigger);
334 }
335 else if (Match(Parameter[1],"continuous")) {
336 Boards[i]->Send(CMD_Trigger_C);
337 if (Parameter.size() == 3 && ConvertToInt(Parameter[2], &Num)) {
338 if (Num == 0)
339 Boards[i]->Send(CMD_Trigger_S);
340 else {
341 //Boards[i]->Send(0x2100 + (unsigned char) (1000.0/Num/12.5));
342 Boards[i]->Send( CMD_Write | BADDR_CONT_TRIGGER_TIME );
343 Boards[i]->Send((unsigned short) (1000.0/Num/12.5));
344 }
345 }
346 }
347 else if (Match(Parameter[1],"stop")) Boards[i]->Send(CMD_Trigger_S);
348 else if (Match(Parameter[1],"enable")) Boards[i]->Send(CMD_TRIGGERS_ON);
349 else if (Match(Parameter[1],"disable")) Boards[i]->Send(CMD_TRIGGERS_OFF);
350 else {
351 PrintUsage();
352 break;
353 }
354 }
355}
356
357//
358// Set DAC
359//
360void FAD::cmd_dac() {
361
362 int Value;
363 struct Range R = {0, NDAC-1};
364 unsigned short Buffer[2*NDAC] = {0};
365
366 // Check ranges
367 if(!ConvertToRange(Parameter[1], R)) {
368 PrintMessage("Error, DAC number out of range.\n");
369 return;
370 }
371
372 if (!ConvertToInt(Parameter[2], &Value) || Value<0 || Value>MAX_DACVAL) {
373 PrintMessage("Error, DAC value out of range.\n");
374 return;
375 }
376
377 // Prepare command buffer
378 for (int i=R.Min; i<=R.Max; i++) {
379 Buffer[2*i] = htons(CMD_Write | (BADDR_DAC + i));
380 Buffer[2*i+1] = htons(Value);
381 }
382
383 // Send command buffer
384 for (unsigned int i=0; i<Boards.size(); i++) {
385 Boards[i]->Send(Buffer, sizeof(Buffer));
386 Boards[i]->Send(CMD_Execute);
387 }
388}
389
390//
391// Set region-of-interest
392//
393void FAD::cmd_roi() {
394
395 int Value;
396 struct Range R = {0, NChips*NChannels-1};
397 unsigned short Buffer[2*NChips*NChannels] = {0};
398
399 // Check ranges
400 if (!ConvertToRange(Parameter[1], R)) {
401 PrintMessage("Error, ROI number out of range.\n");
402 return;
403 }
404
405 if (!ConvertToInt(Parameter[2], &Value) || Value<0 || Value>MAX_ROIVAL) {
406 PrintMessage("Error, ROI value out of range.\n");
407 return;
408 }
409
410 // Prepare command buffer
411 for (int i=R.Min; i<=R.Max; i++) {
412 Buffer[2*i] = htons(CMD_Write | (BADDR_ROI + i));
413 Buffer[2*i+1] = htons(Value);
414 }
415
416
417 // Send command buffer and enable triggers again
418 for (unsigned int i=0; i<Boards.size(); i++) {
419 Boards[i]->Send(Buffer+R.Min*2, (R.Max-R.Min+1)*2*sizeof(unsigned short));
420 Boards[i]->Send(CMD_Execute);
421 }
422
423
424}
425
426//
427// Set addresses to value
428//
429void FAD::cmd_address() {
430
431 int Value;
432 struct Range R = {0, MAX_ADDR};
433 unsigned short Buffer[2*MAX_ADDR] = {0};
434
435 // Check ranges
436 if (!ConvertToRange(Parameter[1], R)) {
437 PrintMessage("Error, address out of range.\n");
438 return;
439 }
440
441 if (!ConvertToInt(Parameter[2], &Value) || Value<0 || Value>MAX_VAL) {
442 PrintMessage("Error, value out of range.\n");
443 return;
444 }
445
446 // Prepare command buffer
447 for (int i=R.Min; i<=R.Max; i++) {
448 Buffer[2*i] = htons(CMD_Write | i);
449 Buffer[2*i+1] = htons(Value);
450 }
451
452 // Send command buffer
453 for (unsigned int i=0; i<Boards.size(); i++) {
454 Boards[i]->Send(Buffer, 2*(R.Max-R.Min+1)*sizeof(unsigned short));
455 }
456}
457
458//
459// Set ADC phase
460//
461void FAD::cmd_phase() {
462
463 int Value;
464
465 if (!ConvertToInt(Parameter[1], &Value)) {
466 PrintMessage("Error, illegal phase value\n");
467 return;
468 }
469
470 // Prepare command buffer
471 unsigned short *Buffer = new unsigned short [abs(Value)];
472 for (int i=0; i<abs(Value); i++) Buffer[i] = htons(CMD_PS_DO);
473
474 // Execute phase setting
475 for (unsigned int i=0; i<Boards.size(); i++) {
476 Boards[i]->Send(CMD_PS_RESET);
477 if (Value < 0) Boards[i]->Send(CMD_PS_DIRDEC);
478 else Boards[i]->Send(CMD_PS_DIRINC);
479 Boards[i]->Send(Buffer, abs(Value)*sizeof(unsigned short));
480 }
481
482 delete[] Buffer;
483}
484
485//
486// Send arbitrary data to board
487//
488void FAD::cmd_send() {
489
490 int Value;
491
492 if (!ConvertToInt(Parameter[1], &Value) || Value<0 || Value>MAX_VAL) {
493 PrintMessage("Error, illegal value\n");
494 return;
495 }
496
497 for (unsigned int i=0; i<Boards.size(); i++) Boards[i]->Send(Value);
498}
499
500/*
501// Set Domino mode
502void FAD::cmd_dmode() {
503 if (Match(Param[1],"continuous")) SetDOMINOMode(1);
504 else if (Match(Param[1],"single")) SetDOMINOMode(0);
505 else PrintUsage();
506}
507
508// Set Domino readout mode
509void FAD::cmd_rmode() {
510 if (Match(Param[1],"first")) SetDOMINOReadMode(0);
511 else if (Match(Param[1],"stop")) SetDOMINOReadMode(1);
512 else PrintUsage();
513}
514
515// Set Domino wave mode
516void FAD::cmd_wmode() {
517 if (Match(Param[1],"run")) SetDOMINOWaveMode(1);
518 else if (Match(Param[1],"stop")) SetDOMINOWaveMode(0);
519 else PrintUsage();
520}
521*/
522
523//
524// Start data run
525//
526void FAD::cmd_take() {
527
528 time_t Time = time(NULL);
529 struct tm *T = localtime(&Time);
530 char Filename[500];
531 double Temp;
532
533 // Set number of requested events
534 NumEventsRequested = atoi(Parameter[1].c_str());
535 NumEvents = 0;
536
537 // Open file with rwx right for owner and group, never overwrite file
538 snprintf(Filename, sizeof(Filename),"%s/%d%02d%02dT%02d%02d%02d.raw", Parameter[2].c_str(), T->tm_year+1900, T->tm_mon+1, T->tm_mday, T->tm_hour, T->tm_min, T->tm_sec);
539
540 Datafile = open(Filename,O_WRONLY|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
541 if(Datafile == -1) {
542 PrintMessage("Error: Could not open file \"%s\" (%s)\n", Filename, strerror(errno));
543 return;
544 }
545
546 // Check conditions for run of all active boards
547 float MaxTempDiff = atof(GetConfig("CalibTempDiffWarn").c_str());
548 float MaxFreqDiff = atof(GetConfig("CalibFreqDiffWarn").c_str());
549
550 for (unsigned int i=0; i<Boards.size(); i++) {
551 if (!Boards[i]->Active) continue;
552
553 if (Boards[i]->ACalib.Time == -1) PrintMessage("Warning: Amplitude calibration missing for board %d\n", i);
554 else {
555 Temp = 0;
556 for (unsigned int j=0; j<NTemp; j++) Temp += Boards[i]->GetStatus().Temp[j] / NTemp;
557 if (fabs(Boards[i]->ACalib.Temp-Temp) > MaxTempDiff) PrintMessage("Warning: Calibration to current temperature difference larger than %.1f K for board %d\n", MaxTempDiff, i);
558 if (fabs(Boards[i]->ACalib.Frequency-Boards[i]->GetStatus().Frequency) > MaxFreqDiff) PrintMessage("Warning: Calibration to current frequency difference larger than %.1f GHz for board %d\n", MaxFreqDiff, i);
559 }
560 }
561
562 // Start run
563 Mode = datarun;
564 Message(INFO, "Starting run with %d events, filename '%s'", NumEventsRequested, Filename);
565}
566
567//
568// Amplitude calibration
569//
570void FAD::cmd_acalib() {
571
572 // Invalidate calibration?
573 if (Parameter.size() == 2 && Match(Parameter[1], "invalidate")) {
574 for (unsigned int i=0; i<Boards.size(); i++) Boards[i]->ACalib.Time = -1;
575 return;
576 }
577
578 // Read calibration data from file?
579 if (Parameter.size() == 2 && !ConvertToInt(Parameter[1], &NumEventsRequested)) {
580 FILE *File;
581 struct FADBoard::CalibData Data;
582 bool Found = false;
583
584 // Open file
585 if ((File = fopen(Parameter[1].c_str(), "r")) == NULL) {
586 PrintMessage("Error opening file '%s'\n", Parameter[1].c_str());
587 return;
588 }
589 // Read data and check if it applies to any board
590 while (fread(&Data, sizeof(Data), 1, File) == 1) {
591 for (unsigned int i=0; i<Boards.size(); i++) if (Data.DNA == Boards[i]->GetStatus().DNA) {
592 PrintMessage("Found calibration for board %d - %s", i, ctime(&Data.Time));
593 Boards[i]->ACalib = Data;
594 Found = true;
595 }
596 }
597 if (!Found) PrintMessage("Did not find calibration data for any board\n");
598
599 //Close file
600 if (fclose(File) != 0) PrintMessage("Could not close file '%s'\n", Parameter[1].c_str());
601 return;
602 } // Reading calibration from file
603
604 // Set number of events required for calibration
605 if (Parameter.size()==1 || !ConvertToInt(Parameter[1], &NumEventsRequested) || NumEventsRequested<=0) {
606 NumEventsRequested = DEFAULT_NUM_CALIB_EVENTS;
607 }
608
609 // Modified calibration procedure for new FAD-based scope (Ulf)
610 if (Parameter.size() == 3 && Match(Parameter[2], "modified")) ModifiedCalibration = true;
611 else ModifiedCalibration = false;
612
613 // Start calibration by setting mode
614 Mode = acalib;
615 if (!ModifiedCalibration) Message(INFO, "Starting amplitude calibration run with 3x%d events", NumEventsRequested);
616 else Message(INFO, "Starting modified amplitude calibration run with 3x%d events", NumEventsRequested);
617}
618
619
620//
621// Determine dynamic range
622//
623void FAD::cmd_dynrange() {
624
625 Mode = dynrange;
626 Message(INFO, "Starting determination of dynamic range");
627}
628
629
630//
631// Print status
632//
633void FAD::cmd_status() {
634
635 int MinCount = std::numeric_limits<int>::max();
636 unsigned int SlowestBoard = 0;
637
638 // ==== Print board overview ====
639 if (Parameter.size() == 1) {
640
641 // Count active board
642 unsigned int Count = 0, Error = 0;
643 for (unsigned int i=0; i<Boards.size(); i++) {
644 if (Boards[i]->Active) Count++;
645 if (!Boards[i]->CommOK) Error++;
646 if (Boards[i]->Active && Boards[i]->Count < MinCount) {
647 MinCount = Boards[i]->Count;
648 SlowestBoard = i;
649 }
650 }
651
652 PrintMessage("\rTotal boards: %d (%d with communication errors)\n", Boards.size(), Error);
653
654 // Print list of active boards
655 PrintMessage("Active (%d)\t", Count);
656 for (unsigned int i=0; i<Boards.size(); i++) {
657 if (Boards[i]->Active) PrintMessage(" %d%s", i, Boards[i]->CommOK ? "":"!");
658 }
659 PrintMessage("\nInactive (%d) ", Boards.size()-Count);
660 for (unsigned int i=0; i<Boards.size(); i++) {
661 if (!Boards[i]->Active) PrintMessage(" %d%s", i, Boards[i]->CommOK ? "":"!");
662 }
663 PrintMessage("\n");
664
665 // Print current mode
666 if (Mode == idle) PrintMessage("Current mode is IDLE\n");
667 else if (Mode == acalib) PrintMessage("Current mode is ACALIB (3x%d events, slowest board %d has %d events)\n", NumEventsRequested, SlowestBoard, MinCount);
668 else if (Mode == datarun) PrintMessage("Current mode is DATARUN (%d events requested, %d events taken)\n", NumEventsRequested, NumEvents);
669 else if (Mode == dynrange) PrintMessage("Current mode is DYNRANGE\n");
670 return;
671 }
672
673 // ==== Print details for given range ====
674 struct Range R = {0, Boards.size()};
675
676 if (!ConvertToRange(Parameter[1], R)) {
677 PrintMessage("Error, out of range.\n");
678 return;
679 }
680
681 for (int i=0; i<(int) Boards.size(); i++) {
682 if (i<R.Min || i > R.Max) continue;
683
684 PrintMessage("\nBOARD #%d (%sactive) IP %s Communication %s\n", i, Boards[i]->Active ? "":"in", Boards[i]->Name, Boards[i]->CommOK ? "OK":"ERROR");
685
686 // Calibration information
687 if (Boards[i]->ACalib.Time == -1) PrintMessage("No amplitude calibration available\n");
688 else PrintMessage("Calibration data: Temperature %.1f Frequency %.2f Time %s" , Boards[i]->ACalib.Temp, Boards[i]->ACalib.Frequency, ctime(&Boards[i]->ACalib.Time));
689
690 // Status information
691 struct FADBoard::BoardStatus S = Boards[i]->GetStatus();
692
693 PrintMessage("Status: %s\n", S.Message);
694
695 if (S.Update.tv_sec == -1) {
696 PrintMessage("No event received yet, no further status information available\n");
697 continue;
698 }
699 PrintMessage("Event rate %.1f Hz Last event received %s", S.Rate, ctime(&S.Update.tv_sec));
700
701 // Board identification
702 PrintMessage("Board ID %.4x Firmware revision %.4x Serial %llx\n", S.BoardID, S.FirmwareRevision, S.DNA);
703 PrintMessage("Board time %g s Event counter %d\n", S.BoardTime/1.0e4 , S.EventCounter);
704
705 // Other data
706 PrintMessage("Frequency %.2f GHz (%s) Phase shift %d PLL lock %d %d %d %d\n", S.Frequency, S.RefClk_low ? "too low":"OK", S.PhaseShift, S.Lock[0], S.Lock[1], S.Lock[2], S.Lock[3]);
707 PrintMessage("DENABLE %d DWRITE %d SPI_clk %d DCM_lock %d DCM_ready %d\n", S.denable, S.dwrite, S.spi_clk, S.DCM_lock, S.DCM_ready);
708 PrintMessage("DAC %d %d %d %d %d %d %d %d\n", S.DAC[0], S.DAC[1], S.DAC[2], S.DAC[3], S.DAC[4], S.DAC[5], S.DAC[6], S.DAC[7] );
709 PrintMessage("Temperature %.2f %.2f %.2f %.2f", S.Temp[0], S.Temp[1], S.Temp[2], S.Temp[3]);
710
711 for (unsigned int j=0; j<NChips*NChannels; j++) {
712 if (j%NChannels == 0) PrintMessage("\nROI %2d-%2d: ", j, j+NChannels-1);
713 PrintMessage("%4d ", S.ROI[j/NChannels][j%NChannels]);
714 }
715
716 PrintMessage("\nTrigger ID: Num %d Type %d CRC %d Run number %d\n", S.TriggerNum, S.TriggerType, S.TriggerCRC, S.Runnumber);
717 } // for()
718}
719
720//
721// Adress FAD boards
722//
723void FAD::cmd_board() {
724
725 struct Range R = {0, Boards.size()};
726 int Mode = 0;
727
728 // Check if given boards should be enabled or disabled
729 if (Parameter[1].size() >= 1) {
730 if (Parameter[1][0] == '+') Mode = 1;
731 if (Parameter[1][0] == '-') Mode = -1;
732 }
733 if (Mode != 0) Parameter[1][0] = ' ';
734
735 // Disable all boards
736 if (Match(Parameter[1], "none")) {
737 for (int i=0; i<(int) Boards.size(); i++) Boards[i]->Active = false;
738 return;
739 }
740
741 // Evaluate given range
742 if (!ConvertToRange(Parameter[1], R)) {
743 PrintMessage("Error, out of range.\n");
744 return;
745 }
746
747 // Enable or disable boards
748 for (int i=0; i<(int) Boards.size(); i++) {
749 if (Mode == 0) Boards[i]->Active = false;
750 if (i >= R.Min && i <= R.Max) {
751 if (Mode != -1) Boards[i]->Active = true;
752 else Boards[i]->Active = false;
753 }
754 }
755}
756
757//
758// Set DIM event update delay
759//
760void FAD::cmd_update() {
761
762 double Delay;
763
764 if (Parameter.size()==2 && ConvertToDouble(Parameter[1], &Delay) && Delay>=0) EventUpdateDelay = Delay;
765 else PrintUsage();
766}
767
768//
769// Print help
770//
771void FAD::cmd_help() {
772
773 char *Buffer;
774
775 for(unsigned int i=0; i<sizeof(CommandList)/sizeof(CL_Struct); i++) {
776 if (asprintf(&Buffer, "%s %s", CommandList[i].Name, CommandList[i].Parameters) == -1) {
777 PrintMessage("Error printing help, asprintf() failed\n");
778 break;
779 }
780 else {
781 if (strlen(Buffer) < 25) PrintMessage("%-25s%s\n", Buffer, CommandList[i].Help);
782 else PrintMessage("%s\n%-25s%s\n", Buffer, "", CommandList[i].Help);
783 }
784 free(Buffer);
785 }
786 PrintMessage(".<command> Execute shell command\n\n"
787 "Items in <> are mandatory, in [] optional, | indicates mutual exclusive.\n"
788 "Strings containing spaces have to be enclosed in \"double quotes\".\n"
789 "Ranges can be given as 'all', a single number or in the form 'a-b'.\n");
790}
791
792//
793// Stop current operation
794//
795void FAD::cmd_stop() {
796
797 static char Stop[] = "stop\n";
798
799 if (Mode == idle) {
800 PrintMessage("Nothing to stop\n");
801 return;
802 }
803
804 if (Mode == acalib || Mode == dynrange) {
805 Mode = idle;
806 Message(INFO, "Mode set to IDLE");
807 }
808
809 if (Mode == datarun) {
810 // Inform event thread to stop run in case datarun active
811 if (write(Pipe[1], Stop, strlen(Stop)) == -1) {
812 Message(ERROR, "write() to Pipe[1] failed in FAD::cmd_cancel() (%s)", strerror(errno));
813 }
814 }
815
816 PrintMessage("Requested stopping of current operation\n");
817}
818
819//
820// Exit programm
821// SIGTERM makes readline() return (in case command came over network)
822//
823void FAD::cmd_exit() {
824
825 ExitRequest = true;
826 pthread_kill(MainThread, SIGTERM);
827}
828
829
830// -----------------------------
831// ***** Other functions *****
832// -----------------------------
833
834//
835// DIM exit handler (overwriting handler in Evidence class)
836//
837void FAD::exitHandler(int Code) {
838
839 Message(INFO, "Exit handler called (DIM exit code %d)", Code);
840 cmd_exit();
841}
842
843//
844// Save amplitude calibration data to file
845//
846void FAD::SaveAmplitudeCalibration() {
847
848 // Open calibration data file
849 string Filename = string(getenv("HOME"))+"/FAD_ACal";
850 FILE *File = fopen(Filename.c_str(), "wb");
851
852 if (File == NULL) {
853 PrintMessage("Could not open calibration data file '%s'\n", Filename.c_str());
854 return;
855 }
856
857 // Write valid calibration information for active boards
858 for (unsigned int i=0; i<Boards.size(); i++) {
859 if (!Boards[i]->Active || Boards[i]->ACalib.Time == -1) continue;
860
861 if (fwrite(&Boards[i]->ACalib, sizeof(Boards[i]->ACalib), 1, File) != 1) {
862 PrintMessage("Could not write to calibration file '%s'\n", Filename.c_str());
863 break;
864 }
865 }
866
867 // Close file
868 if (fclose(File) != 0) PrintMessage("Could not close calibration file '%s'\n", Filename.c_str());
869
870 PrintMessage("Wrote amplitude calibration to file '%s'\n", Filename.c_str());
871}
872
873//
874// Event thread (publishes/writes M0 format)
875//
876void FAD::EventThread() {
877
878 struct timeval Time;
879 struct timeval LastUpdate;
880 struct FADBoard::BoardStatus S;
881 vector<unsigned long> EventNumbers(Boards.size());
882 vector<bool> AcalibDone(Boards.size());
883 vector<class FADBoard *> ActiveBoards;
884 double Temp;
885 string IDString;
886 char Buffer[100];
887 int Ret;
888 struct stat FileStat;
889 float FileSizeMB = 0;
890 RunHeader FileRHeader;
891
892 gettimeofday(&LastUpdate, NULL);
893
894 // Create DIM event data and number services
895 char *EventData = new char [sizeof(RunHeader)+ Boards.size()*sizeof(BoardStructure)+sizeof(EventHeader) + Boards.size()*(NChips*NChannels*NBins*sizeof(short) + NChips*sizeof(int))];
896
897 DimService EventService(SERVER_NAME"/EventData", (char *) "C", NULL, 0);
898 DimService EventNumService(SERVER_NAME"/EventNumber", NumEvents);
899 DimService FileSizeService(SERVER_NAME"/FileSizeMB", FileSizeMB);
900
901 // Set/allocate pointers
902 RunHeader *RHeader = (RunHeader *) EventData;
903 BoardStructure **BStruct = new BoardStructure * [Boards.size()];
904 EventHeader *EHeader;
905 int *TriggerCell;
906 short *Data;
907
908 // Fill fixed entries in M0 RunHeader
909 RHeader->MagicNum = MAGICNUM_CLOSED;
910 RHeader->DataFormat = DATA_FORMAT;
911 RHeader->RunHeaderSize = sizeof(RunHeader);
912 RHeader->EventHeaderSize = sizeof(EventHeader);
913 RHeader->BoardStructureSize = sizeof(BoardStructure);
914 RHeader->SoftwareRevision = atoi(REVISION) * (strchr(REVISION, 'M')==NULL ? 1:-1);
915 RHeader->Identification = 0;
916 RHeader->Type = 0; // Run type: 0=data, 1=pedestal, 3=test
917 RHeader->RunNumber = -1;
918 RHeader->FileNumber = 0;
919 snprintf(RHeader->Description, sizeof(RHeader->Description), "FADctrl");
920 RHeader->Events = 1;
921 RHeader->StartSecond = LastUpdate.tv_sec;
922 RHeader->StartMicrosecond = LastUpdate.tv_usec;
923 RHeader->NChips = NChips;
924 RHeader->NChannels = NChannels;
925 RHeader->Samples = NBins; // Always full pipeline
926 RHeader->Offset = 0;
927 RHeader->NBytes = sizeof(short);
928
929 // Update loop
930 while (!ExitRequest) {
931 // Removed processed data from IDString
932 size_t LastLF = IDString.find_last_of("\n");
933 if (LastLF != string::npos) IDString = IDString.substr(LastLF+1);
934
935 // Wait for data from TCP/IP reading threads
936 if ((Ret=read(Pipe[0], Buffer, sizeof(Buffer))) == -1) Message(FATAL, "read() from Pipe[0] failed in FAD::EventThread() (%s)", strerror(errno));
937
938 // Check if pipe closed
939 if (Ret == 0) break;
940
941 IDString.append(string(Buffer, Ret));
942
943 // Active boards must not change during data taking
944 if (Mode != datarun || NumEvents == 0) {
945 ActiveBoards.clear();
946 for (unsigned int i=0; i<Boards.size(); i++) {
947 if (Boards[i]->Active) ActiveBoards.push_back(Boards[i]);
948 }
949 RHeader->NBoards = ActiveBoards.size();
950 }
951
952 // Calculate pointers to EventData array
953 for (unsigned int i=0; i<ActiveBoards.size(); i++) BStruct[i] = ((BoardStructure *) (RHeader + 1)) + i;
954 EHeader = (EventHeader *) ((char *) (RHeader + 1) + ActiveBoards.size()*sizeof(BoardStructure));
955 TriggerCell = (int *) (EHeader + 1);
956 Data = (short *) (TriggerCell + NChips*ActiveBoards.size());
957
958 // If amplitude calibration mode, check if all boards finished procedure
959 if (Mode == acalib || Mode == dynrange) {
960 bool Done = true;
961 for (unsigned int i=0; i<Boards.size(); i++) {
962 if (IDString.find(string("ACALIBDONE")+Boards[i]->Name) != string::npos) AcalibDone[i] = true;
963 if (!AcalibDone[i] && Boards[i]->Active) Done = false;
964 }
965 // Amplitude calibration finished?
966 if (Done) {
967 if (Mode == acalib) {
968 SaveAmplitudeCalibration();
969 Message(INFO, "Amplitude calibration done, mode set to IDLE");
970 }
971 if (Mode == dynrange) {
972 Message(INFO, "Dynamic range measurement done, mode set to IDLE");
973 }
974 Mode = idle;
975 }
976 }
977 else for (unsigned int i=0; i<Boards.size(); i++) AcalibDone[i] = false;
978
979 // Update run and event header
980 gettimeofday(&Time, NULL);
981 RHeader->EndSecond = Time.tv_sec;
982 RHeader->EndMicrosecond = Time.tv_usec;
983
984 EHeader->EventSize = RHeader->NBoards * (NChips*NChannels*NBins*sizeof(short) + NChips*sizeof(int));
985 EHeader->Second = Time.tv_sec;
986 EHeader->Microsecond = Time.tv_usec;
987
988 // Check all boards that have new data
989 for (unsigned int Brd=0; Brd<ActiveBoards.size(); Brd++) {
990 if (IDString.find(string("EVENT")+ActiveBoards[Brd]->Name) == string::npos) continue;
991
992 // Fill M0 BoardStructure
993 S = ActiveBoards[Brd]->GetStatus();
994 BStruct[Brd]->SerialNo = (U32) S.DNA;
995 BStruct[Brd]->NomFreq = S.Frequency;
996 BStruct[Brd]->BoardTemp = 0;
997 for (unsigned int i=0; i<NTemp; i++) BStruct[Brd]->BoardTemp += S.Temp[i]/NTemp;
998 BStruct[Brd]->ScaleFactor = 1/2.048;
999
1000 // Update event header with ID and Type of current board
1001 EHeader->EventNumber = S.TriggerNum;
1002 EHeader->TriggerType = S.TriggerType;
1003
1004 // Register event number for data writing below
1005 EventNumbers[Brd] = S.TriggerNum;
1006
1007 // Write trigger cells
1008 for(unsigned int i=0; i<NChips; i++) TriggerCell[Brd*NChips+i] = (int) S.TriggerCell[i];
1009
1010 // Write channel data
1011 int Count = Brd*NChips*NChannels*NBins;
1012 memset(Data+Count, 0, NChips*NChannels*NBins*sizeof(short));
1013
1014 ActiveBoards[Brd]->Lock();
1015 for (unsigned int Chip=0; Chip<NChips; Chip++) for (unsigned int Chan=0; Chan<NChannels; Chan++) {
1016 for (int i=0; i<S.ROI[Chip][Chan]; i++) {
1017 if (ActiveBoards[Brd]->ACalib.Time == -1) Data[Count++] = ActiveBoards[Brd]->Data[Chip][Chan][i];
1018 else {
1019 Temp = (ActiveBoards[Brd]->Data[Chip][Chan][i] - ActiveBoards[Brd]->ACalib.Baseline[Chip][Chan][(i+S.TriggerCell[Chip])%NBins]);
1020 Temp *= ActiveBoards[Brd]->ACalib.Gain[Chip][Chan][0]/ActiveBoards[Brd]->ACalib.Gain[Chip][Chan][(i+S.TriggerCell[Chip])%NBins];
1021 //Temp -= ActiveBoards[Brd]->ACalib.Secondary[Chip][Chan][i];
1022 Data[Count++] = (short) Temp;
1023 }
1024 }
1025 Count += NBins - S.ROI[Chip][Chan];
1026 }
1027 ActiveBoards[Brd]->Unlock();
1028 }
1029
1030 // Inform TCP/IP thread of all boards that send data that processing is finished
1031 for (unsigned int Brd=0; Brd<Boards.size(); Brd++) if (IDString.find(string("EVENT")+Boards[Brd]->Name) != string::npos) {
1032 Boards[Brd]->Lock();
1033 Boards[Brd]->Continue = true;
1034 Boards[Brd]->Unlock();
1035
1036 if ((Ret = pthread_cond_signal(&Boards[Brd]->CondVar)) != 0) {
1037 Message(FATAL, "pthread_cond_signal() failed (%s)", strerror(Ret));
1038 }
1039 }
1040
1041 // Check if DIM service should be updated
1042 if ((Time.tv_sec-LastUpdate.tv_sec)*1e6 + Time.tv_usec-LastUpdate.tv_usec > EventUpdateDelay*1e6) {
1043 gettimeofday(&LastUpdate, NULL);
1044
1045 EventService.updateService(EventData, sizeof(RunHeader) + sizeof(EventHeader) + ActiveBoards.size()*(sizeof(BoardStructure) + NChips*NChannels*NBins*sizeof(short) + NChips*sizeof(int)));
1046 EventNumService.updateService();
1047
1048 if (Mode == datarun) FileSizeService.updateService();
1049 }
1050
1051 // ===== Data writing ===
1052 if (Mode != datarun) continue;
1053
1054 // Check if event numbers of all active boards are the same
1055 unsigned long CommonEventNum = numeric_limits<unsigned long>::max();
1056
1057 for (unsigned int i=0; i<Boards.size(); i++) if (Boards[i]->Active) {
1058 if (CommonEventNum == numeric_limits<unsigned long>::max()) CommonEventNum = EventNumbers[i];
1059 if (CommonEventNum != EventNumbers[i]) {
1060 CommonEventNum = numeric_limits<unsigned long>::max();
1061 break;
1062 }
1063 }
1064 if (CommonEventNum == numeric_limits<unsigned long>::max()) continue;
1065
1066 int Error = 0;
1067
1068 // Initialize run
1069 if (NumEvents == 0) {
1070 FileSizeMB = 0;
1071
1072 FileRHeader = *RHeader;
1073 FileRHeader.MagicNum = MAGICNUM_OPEN;
1074 FileRHeader.StartSecond = Time.tv_sec;
1075 FileRHeader.StartMicrosecond = Time.tv_usec;
1076
1077 // Write run header and board structures
1078 if (write(Datafile, &FileRHeader, sizeof(RunHeader)) == -1) Error = errno;
1079 else if (write(Datafile, BStruct[0], FileRHeader.NBoards*sizeof(BoardStructure)) == -1) Error = errno;
1080 }
1081
1082 // Write event header, trigger cells and ADC data to file
1083 if (write(Datafile, EHeader, sizeof(EventHeader)+FileRHeader.NBoards*NChips*(sizeof(int)+NChannels*NBins*sizeof(short))) == -1) Error = errno;
1084
1085 NumEvents++;
1086
1087 // Update file size
1088 if (fstat(Datafile, &FileStat) == -1) Error = errno;
1089 else FileSizeMB = FileStat.st_size/1024.0/1024.0;
1090
1091 // Check for write errors and for correct file size
1092 if (Error !=0) {
1093 Message(ERROR, "Error writing to data data file (%s), terminating run, setting mode to IDLE", strerror(Error));
1094 }
1095 else if ((size_t) FileStat.st_size != sizeof(RunHeader)+ FileRHeader.NBoards*sizeof(BoardStructure)+NumEvents*(sizeof(EventHeader) + FileRHeader.NBoards*(NChips*NChannels*NBins*sizeof(short) + NChips*sizeof(int)))) {
1096 Message(ERROR, "Could not write all data to file, terminating run, setting mode to IDLE");
1097 Error = 1;
1098 }
1099
1100 // Close file if error
1101 if (Error != 0) {
1102 if (close(Datafile) == -1) Message(ERROR, "Could not close data file (%s)", strerror(errno));
1103 Datafile = -1;
1104 Mode = idle;
1105 continue;
1106 }
1107
1108 // Close data file if requested or requested number of events reached
1109 if(IDString.find("stop")!=string::npos || (NumEvents==NumEventsRequested && NumEventsRequested!=0)) {
1110
1111 // Update run header for writing
1112 FileRHeader.MagicNum = MAGICNUM_CLOSED;
1113 FileRHeader.Events = NumEvents;
1114 FileRHeader.EndSecond = Time.tv_sec;
1115 FileRHeader.EndMicrosecond = Time.tv_usec;
1116
1117 if (lseek(Datafile, 0, SEEK_SET) == -1) {
1118 Message(ERROR, "Could not rewind file to write updated run header (%s)", strerror(errno));
1119 }
1120 else if (write(Datafile, &FileRHeader, sizeof(RunHeader)) != sizeof(RunHeader)) {
1121 Message(ERROR, "Could not write updated run header (%s)", strerror(errno));
1122 }
1123
1124 // Close data file and terminate run
1125 if(close(Datafile) == -1) Message(ERROR, "Could not close data file (%s)", strerror(errno));
1126 else PrintMessage("Data file closed (size %.1f MByte, rate %.1f MByte/s, %d events).\n", FileSizeMB, FileSizeMB/(FileRHeader.EndSecond-FileRHeader.StartSecond+(FileRHeader.EndMicrosecond-FileRHeader.StartMicrosecond)/1000000.0), NumEvents);
1127
1128 Datafile = -1;
1129 Mode = idle;
1130 Message(INFO, "Data run ended, mode set to IDLE");
1131 }
1132 }
1133
1134 delete[] BStruct;
1135 delete[] EventData;
1136}
1137
1138// Launch event thread inside class
1139void FAD::LaunchEventThread(class FAD *m) {
1140
1141 m->EventThread();
1142}
1143
1144
1145/*
1146// Set DOMINO mode
1147void FAD::SetDOMINOMode(int mode) {
1148
1149 for (int i=FirstBoard; i<=LastBoard; i++) {
1150 GetBoard(i)->SetDominoMode(mode==1 ? 1:0);
1151 PrintMessage("Domino mode of board %d switched to %s.\n",i,mode==1 ? "continuous":"single shot");
1152 }
1153}
1154
1155// Set DOMINO readout mode
1156void FAD::SetDOMINOReadMode(int mode) {
1157
1158 for (int i=FirstBoard; i<=LastBoard; i++) {
1159 GetBoard(i)->SetReadoutMode(mode);
1160 PrintMessage("Start readout of board %d from %s.\n",i,mode==0 ? "first bin":"stop position");
1161 }
1162}
1163
1164// Set DOMINO wave mode
1165void FAD::SetDOMINOWaveMode(int mode) {
1166
1167 for (int i=FirstBoard; i<=LastBoard; i++) {
1168 GetBoard(i)->SetDominoActive(mode);
1169 PrintMessage("Domino wave of board %d is %s during readout\n",i,mode==1 ? "running":"stopped");
1170 }
1171}
1172
1173*/
1174
1175
1176//
1177// Print usage text for command
1178//
1179void FAD::PrintUsage() {
1180
1181 for(unsigned int i=0; i<sizeof(CommandList)/sizeof(CL_Struct); i++) {
1182 if (Match(Parameter[0], CommandList[i].Name)) {
1183 PrintMessage("Usage: %s %s\n", CommandList[i].Name, CommandList[i].Parameters);
1184 }
1185 }
1186}
1187
1188//
1189// Print message to console
1190//
1191void FAD::PrintMessage(const char *Format, ...) {
1192
1193 static char Error[] = "vasprintf() failed in PrintMessage()";
1194 char *Text;
1195
1196 // Evaluate arguments
1197 va_list ArgumentPointer;
1198 va_start(ArgumentPointer, Format);
1199 if (vasprintf(&Text, Format, ArgumentPointer) == -1) Text = Error;
1200 va_end(ArgumentPointer);
1201
1202 if (strlen(Text) == 0) return;
1203
1204 // Print to console
1205 //if (Text[strlen(Text)-1] == '\n') printf("\r"); // Overwrite prompt
1206 printf("%s", Text);
1207 fflush(stdout);
1208 if (Text[strlen(Text)-1] == '\n') rl_on_new_line();
1209
1210 // Send to DIM text service
1211 ConsoleOut->updateService(Text);
1212
1213 // Free old text
1214 if (ConsoleText != Error) free(ConsoleText);
1215 ConsoleText = Text;
1216}
1217
1218//
1219// Check if two strings match (min 1 character must match)
1220//
1221bool FAD::Match(string str, const char *cmd) {
1222
1223 return strncasecmp(str.c_str(),cmd,strlen(str.c_str())==0 ? 1:strlen(str.c_str())) ? false:true;
1224}
1225
1226//
1227// Conversion function from string to double, int or range
1228//
1229// Return false if conversion did not stop on whitespace or EOL character
1230bool FAD::ConvertToDouble(string String, double *Result) {
1231
1232 char *EndPointer;
1233
1234 *Result = strtod(String.c_str(), &EndPointer);
1235 if(!isspace(*EndPointer) && *EndPointer!='\0') return false;
1236 return true;
1237}
1238
1239bool FAD::ConvertToInt(string String, int *Result) {
1240
1241 char *EndPointer;
1242
1243 *Result = (int) strtol(String.c_str(), &EndPointer, 0);
1244 if(!isspace(*EndPointer) && *EndPointer!='\0') return false;
1245 return true;
1246}
1247
1248bool FAD::ConvertToRange(string String, struct FAD::Range &R) {
1249
1250 int N=0, M=0;
1251
1252 // Full range
1253 if (Match(String, "all")) return true;
1254
1255 // Single number
1256 if (ConvertToInt(String, &N)) {
1257 if (N>= R.Min && N<=R.Max) {
1258 R.Max = R.Min = N;
1259 return true;
1260 }
1261 return false;
1262 }
1263
1264 // Range a-b
1265 vector<string> V = EvidenceServer::Tokenize(String, "-");
1266 if (V.size()==2 && ConvertToInt(V[0], &N) && ConvertToInt(V[1], &M) && N>=R.Min && M<=R.Max) {
1267 R.Min = N;
1268 R.Max = M;
1269 return true;
1270 }
1271
1272 return false;
1273}
Note: See TracBrowser for help on using the repository browser.