source: fact/BIASctrl/User.cc@ 10099

Last change on this file since 10099 was 10096, checked in by ogrimm, 14 years ago
Small changes to limit error messages in case crate communication breaks
File size: 17.5 KB
Line 
1//
2// Class processing user input
3//
4
5#include "User.h"
6#include <readline/readline.h>
7
8using namespace std;
9
10// Branch table for command evaluation
11static const struct CL_Struct { const char *Name;
12 void (User::*CommandPointer)();
13 unsigned int MinNumParameter;
14 const char *Parameters;
15 const char *Help;
16 } CommandList[] =
17 {{"synch", &User::cmd_synch, 0, "", "Synchronize board"},
18 {"hv", &User::cmd_hv, 2, "<id>|<ch>|<all> <v>", "Change bias of pixel or (all) chan. of active boards"},
19 {"gs", &User::cmd_gs, 1, "[crate] <volt>", "Global voltage set"},
20 {"status", &User::cmd_status, 0, "[dac|current]", "Show status information (DAC values if requested)"},
21 {"ccal", &User::cmd_ccal, 1, "<volt>", "Calibrate current measurement at given voltage"},
22 {"mode", &User::cmd_mode, 1, "<static|dynamic>", "Set voltage stabilization mode"},
23 {"load", &User::cmd_load, 1, "<file>", "Load and set bias settings from file"},
24 {"save", &User::cmd_save, 1, "<file>", "Save current bias settings to file"},
25 {"rate", &User::cmd_rate, 1, "<rate>", "Set refresh rate in Hz"},
26 {"timeout", &User::cmd_timeout, 1, "<time>", "Set timeout to return from read in seconds"},
27 {"reset", &User::cmd_reset, 1, "<crates>", "Reset crates"},
28 {"help", &User::cmd_help, 0, "", "Print help"},
29 {"exit", &User::cmd_exit, 0, "", "Exit program"}};
30
31
32//
33// Constructor
34//
35User::User(): EvidenceServer(SERVER_NAME) {
36
37 // DIM console service used in PrintMessage()
38 ConsoleText = NULL;
39 ConsoleOut = new DimService(SERVER_NAME"/ConsoleOut", (char *) "");
40
41 // Get configuration data
42 vector<string> Boards = Tokenize(GetConfig("Boards"), " \t");
43 Boards = Tokenize("FTE00FOH", " \t");
44 fTimeOut = atof(GetConfig("TimeOut").c_str());
45 fStatusRefreshRate = atof(GetConfig("StatusRefreshRate").c_str());
46 fMaxDiff = atof(GetConfig("HVMaxDiffNew").c_str());
47
48 if (fStatusRefreshRate < MIN_RATE || fStatusRefreshRate > MAX_RATE) fStatusRefreshRate = 1;
49
50 // Open devices
51 for (unsigned int i=0; i<Boards.size(); i++) {
52
53 class Crate *New = new class Crate(Boards[i], Crates.size(), this);
54
55 if (New->InitOK && New->Synch()) {
56 PrintMessage("Synchronized and reset crate %s (#%d)\n", Boards[i].c_str(), Crates.size());
57 Crates.push_back(New);
58 }
59 else {
60 Message(WARN, "Failed to synchronize crate %s", Boards[i].c_str());
61 delete New;
62 }
63 }
64
65 // Create instances
66 pm = new PixelMap(GetConfig("PixMapTable"));
67
68 // Install DIM command (after all initialized)
69 DIMCommand = new DimCommand((char *) SERVER_NAME"/Command", (char *) "C", this);
70
71 // Create monitor thread and make accessible for sending signal
72 if ((pthread_create(&Thread, NULL, (void * (*)(void *)) LaunchMonitor,(void *) this)) != 0) {
73 Message(FATAL, "pthread_create() failed with Monitor thread");
74 }
75}
76
77
78//
79// Destructor
80//
81User::~User() {
82
83 // Wait for thread to quit
84 if (pthread_join(Thread, NULL) != 0) {
85 PrintMessage("pthread_join() failed");
86 }
87
88 // Delete all crates
89 for (unsigned int i=0; i<Crates.size(); i++) delete Crates[i];
90
91 delete DIMCommand;
92 delete pm;
93 delete ConsoleOut;
94 free(ConsoleText);
95}
96
97//
98// Process user input
99//
100void User::commandHandler() {
101
102 // Build string safely
103 string Command = string(getCommand()->getString(), getCommand()->getSize());
104
105 // Check if command is legal and ignore empty commands
106 if (getCommand() != DIMCommand || Command.size() < 2) return;
107
108 // Shell command
109 if(Command[0]=='.') {
110 system(Command.c_str()+1);
111 return;
112 }
113
114 // Parse command into tokens
115 Parameter = Tokenize(Command, " ");
116
117 // Search for command in command list
118 for(unsigned int CmdNumber=0; CmdNumber<sizeof(CommandList)/sizeof(CL_Struct); CmdNumber++) {
119 if (Match(Parameter[0], CommandList[CmdNumber].Name)) {
120 if(Parameter.size()-1 < CommandList[CmdNumber].MinNumParameter) {
121 PrintMessage("Usage: %s %s\n", CommandList[CmdNumber].Name, CommandList[CmdNumber].Parameters);
122 return;
123 }
124
125 // Jump to command function
126 (this->*CommandList[CmdNumber].CommandPointer)();
127 return;
128 }
129 }
130 PrintMessage("Unknown command '%s'\n", Parameter[0].c_str());
131}
132
133
134// Print help
135void User::cmd_help() {
136
137 char Buffer[MAX_COM_SIZE];
138 for(unsigned int i=0; i<sizeof(CommandList)/sizeof(CL_Struct); i++) {
139 snprintf(Buffer, sizeof(Buffer), "%s %s", CommandList[i].Name, CommandList[i].Parameters);
140 PrintMessage("%-28s%s\n", Buffer, CommandList[i].Help);
141 }
142
143 PrintMessage(".<command> Execute shell command\n\n"
144 "Items in <> are mandatory, in [] optional, | indicates mutual exclusive or.\n");
145}
146
147//
148// Synchronize boards
149//
150void User::cmd_synch() {
151
152 for (unsigned int i=0; i<Crates.size(); i++) {
153 if (Crates[i]->Synch()) PrintMessage("Synchronized crate %d\n", i);
154 else PrintMessage("Failed to synchronize crate %d\n", i);
155 }
156}
157
158//
159// Set new bias voltage
160//
161void User::cmd_hv() {
162
163 unsigned int Errors=0;
164 double Double;
165 struct Range Crt, Chan;
166 vector< map<unsigned int, double> > Voltages (Crates.size());
167
168 // Loop over all parameters
169 for (unsigned int n=1; n < Parameter.size()-1; n+=2) {
170
171 // Extract channel identification
172 if (pm->Pixel_to_HVboard(Parameter[n]) != 999999999) {
173 Crt.Min = Crt.Max = pm->Pixel_to_HVboard(Parameter[n]);
174 Chan.Min = Chan.Max = pm->Pixel_to_HVchain(Parameter[n])*NUM_CHANNELS + pm->Pixel_to_HVchannel(Parameter[n]);
175 }
176 else {
177 vector<string> T = Tokenize(Parameter[n], "/");
178 Crt.Min = 0;
179 Crt.Max = Crates.size()-1;
180 Chan.Min = 0;
181 Chan.Max = MAX_NUM_BOARDS*NUM_CHANNELS-1;
182
183 if (Parameter[n] == "-") continue;
184
185 if (T.size() == 2) {
186 if(!ConvertToRange(T[0], Crt) || !ConvertToRange(T[1], Chan)) {
187 PrintMessage("Numeric conversion or out-of-range error for parameter %d, skipping channel\n", n);
188 continue;
189 }
190 }
191 else {
192 Crt.Min = Crt.Max = 0;
193 if (!ConvertToRange(T[0], Chan)) {
194 PrintMessage("Numeric conversion or out-of-range error for parameter %d, skipping channel\n", n);
195 continue;
196 }
197 }
198 }
199
200 // Convert voltage value and check format
201 if (!ConvertToDouble(Parameter[n+1], &Double)) {
202 PrintMessage("Error: Wrong number format for voltage setting\n");
203 continue;
204 }
205
206 // Loop over given crates and channels
207 for (int i=Crt.Min; i<=Crt.Max; i++) for (int j=Chan.Min; j<=Chan.Max; j++) {
208 // Voltage change (number starts with + oder -) ignored if current DAC value is zero
209 if (isdigit(Parameter[n+1][0])==0 && Crates[i]->GetDAC(j) == 0) continue;
210
211 // Relative or absolute change?
212 if (isdigit(Parameter[n+1][0]) == 0) Voltages[i][j] = Crates[i]->GetVoltage(j) + Double;
213 else Voltages[i][j] = Double;
214 } // Channels
215 } // Loop over command argument
216
217 // Ramp voltages and update DIM services
218 for (unsigned int i=0; i<Voltages.size(); i++) {
219 Errors += RampVoltages(i, Voltages[i]);
220 Crates[i]->UpdateDIM();
221 }
222
223 // Error message only if not yet too many errors
224 if (Errors > 0) {
225 for (unsigned int i=0; i<Crates.size(); i++) {
226 if (Crates[i]->ErrorCount > MAX_ERR_COUNT) return;
227 }
228 Message(ERROR, "%d errors occurred from SetChannels()", Errors);
229 }
230}
231
232//
233// Load bias settings from file
234//
235void User::cmd_load() {
236
237 char Buffer[MAX_COM_SIZE];
238 int Errors = 0, Channel;
239 unsigned int NBoards = 0;
240 double Value;
241 FILE *File;
242 map<unsigned int, double> Voltages;
243
244 // Open file
245 if ((File=fopen(Parameter[1].c_str(), "r")) == NULL) {
246 PrintMessage("Error: Could not open file '%s' (%s)\n", Parameter[1].c_str(), strerror(errno));
247 return;
248 }
249
250 // Scan through file line by line
251 while (fgets(Buffer, sizeof(Buffer), File) != NULL) {
252 for (unsigned int Crate=0; Crate<Crates.size(); Crate++) if (Match(Crates[Crate]->Name, Buffer)) {
253
254 PrintMessage("Found bias settings for board %s (#%d)\n\r", Crates[Crate]->Name, Crate);
255
256 Voltages.clear();
257 Channel = 0;
258 while (fscanf(File, "%lf", &Value)==1 && Channel<MAX_NUM_BOARDS*NUM_CHANNELS) {
259 Voltages[Channel++] = Value;
260 }
261
262 // Ramp channels
263 Errors += RampVoltages(Crate, Voltages);
264
265 // Update DIM service
266 Crates[Crate]->UpdateDIM();
267
268 if (ferror(File) != 0) {
269 PrintMessage("Error reading DAC value from file, terminating. (%s)\n",strerror(errno));
270 return;
271 }
272 else PrintMessage("\nFinished updating board\n");
273 NBoards++;
274 } // Loop over boards
275 } // while()
276
277 if (NBoards != Crates.size()) PrintMessage("Warning: Could not load bias settings for all connected crates\n");
278 else if (Errors == 0) PrintMessage("Success: Read bias settings for all connected crates\n");
279
280 if (Errors != 0) PrintMessage("Warning: %d error(s) occurred\n", Errors);
281
282 if (fclose(File) != 0) PrintMessage("Error: Could not close file '%s'\n", Parameter[1].c_str());
283}
284
285//
286// Set refresh rate
287//
288void User::cmd_rate() {
289
290 double Rate;
291
292 if (!ConvertToDouble(Parameter[1], &Rate)) {
293 PrintMessage("Error: Wrong number format\n");
294 return;
295 }
296
297 // Check limits
298 if (Rate<MIN_RATE || Rate>MAX_RATE) {
299 PrintMessage("Refresh rate out of range (min: %.2f Hz, max: %.2f Hz)\n", MIN_RATE, MAX_RATE);
300 return;
301 }
302
303 fStatusRefreshRate = Rate;
304 PrintMessage("Refresh rate set to %.2f Hz\n", fStatusRefreshRate);
305}
306
307//
308// Reset crates
309//
310void User::cmd_reset() {
311
312 struct Range R = {0, Crates.size()-1};
313
314 // Check ranges
315 if(!ConvertToRange(Parameter[1], R)) {
316 PrintMessage("Error, crate number out of range\n");
317 return;
318 }
319
320 for (int i=R.Min; i<=R.Max; i++) {
321 if (Crates[i]->SystemReset() == 1) PrintMessage("System reset of crate %s (#%d)\n", Crates[i]->Name, i);
322 else PrintMessage("Error: Could not reset board %s (#%d)\n", Crates[i]->Name, i);
323 }
324}
325
326//
327// Read channel
328//
329void User::cmd_gs() {
330
331 double Voltage;
332
333 if (!ConvertToDouble(Parameter[1], &Voltage)) return;
334
335 for (unsigned int i=0; i<Crates.size(); i++) {
336 if (Crates[i]->GlobalSet(Voltage) != 1) {
337 PrintMessage("Error: Could not global set crate %d\n", i);
338 }
339 }
340}
341
342//
343// Determine current measurement offset
344//
345void User::cmd_ccal() {
346
347 double Voltage;
348
349 if (!ConvertToDouble(Parameter[1], &Voltage)) {
350 PrintMessage("Error with format of voltage parameter\n");
351 return;
352 }
353
354 // Execute current offset determination
355 for (unsigned int i=0; i<Crates.size(); i++) {
356 if (!Crates[i]->CurrentCalib(Voltage)) {
357 PrintMessage("Error with current calibration of crate %d\n", i);
358 return;
359 }
360
361 PrintMessage("Current calibration of crate %d done\n", i);
362 }
363}
364
365//
366// Save bias settings of all boards
367//
368void User::cmd_save() {
369
370 FILE *File;
371 time_t Time = time(NULL);
372
373 if ((File = fopen(Parameter[1].c_str(), "w")) == NULL) {
374 PrintMessage("Error: Could not open file '%s' (%s)\n", Parameter[1].c_str(), strerror(errno));
375 return;
376 }
377
378 fprintf(File,"********** Bias settings of %s **********\n\n", ctime(&Time));
379
380 for (unsigned int i=0; i<Crates.size(); i++) {
381 fprintf(File, "%s\n\n", Crates[i]->Name);
382
383 for (int j=0; j<MAX_NUM_BOARDS*NUM_CHANNELS; j++) fprintf(File,"%.3f ",Crates[i]->GetVoltage(j));
384 fprintf(File, "\n");
385 }
386
387 if (fclose(File) != 0) {
388 PrintMessage("Error: Could not close file '%s' (%s)\n", Parameter[1].c_str(), strerror(errno));
389 }
390}
391
392//
393// Set operation mode
394//
395void User::cmd_mode() {
396
397 if (Match(Parameter[1], "static")) Mode = mode_static;
398 else {
399 Mode = mode_dynamic;
400 for (unsigned int i=0; i<Crates.size(); i++) {
401 Crates[i]->SetRefCurrent();
402 }
403 }
404}
405
406//
407// Print status
408//
409void User::cmd_status() {
410
411 PrintMessage(" Number of crates: %d\n", Crates.size());
412 PrintMessage(" Refresh rate: %.2f Hz\n", fStatusRefreshRate);
413 PrintMessage(" Time out: %.2f s\n\n", fTimeOut);
414 PrintMessage(" MaxDiff : %u\n", fMaxDiff);
415
416 for (unsigned int i=0; i<Crates.size(); i++) {
417 PrintMessage(" CRATE %d (%s)\n Wrap counter: %s (%d) Reset: %s Error count: %d\n ",
418 i, Crates[i]->Name, Crates[i]->WrapOK ? "ok":"error", Crates[i]->WrapCount,
419 Crates[i]->ResetHit ? "yes" : "no", Crates[i]->ErrorCount);
420
421 if (Parameter.size() == 1) PrintMessage("Channel voltages (in V)");
422 else if (Match(Parameter[1], "dac")) PrintMessage("Channel voltages (in DAC values)");
423 else PrintMessage("Channel currents (in uA)");
424
425 for (int j=0; j<MAX_NUM_BOARDS*NUM_CHANNELS; j++) {
426 if (j%12 == 0) PrintMessage("\n%3.1d: ", j);
427 if (!Crates[i]->Present[j/NUM_CHANNELS][j%NUM_CHANNELS]) PrintMessage(" - ");
428 else if (Parameter.size() == 1) PrintMessage("%#5.2f ",Crates[i]->GetVoltage(j));
429 else if (Match(Parameter[1], "dac")) PrintMessage("%5d ", Crates[i]->GetDAC(j));
430 else PrintMessage("%#5.2f %s ", Crates[i]->GetCurrent(j), Crates[i]->OC[j/NUM_CHANNELS][j%NUM_CHANNELS] ? "OC":"");
431 }
432 PrintMessage("\n");
433 }
434}
435
436//
437// Set timeout to return from read
438//
439void User::cmd_timeout() {
440
441 double Timeout;
442
443 if (!ConvertToDouble(Parameter[1], &Timeout)) {
444 PrintMessage("Error: Wrong number format\n");
445 return;
446 }
447
448 fTimeOut = Timeout;
449 PrintMessage("Timeout set to %.2f s\n", fTimeOut);
450}
451
452//
453// Exit program
454//
455void User::cmd_exit() {
456
457 ExitRequest = true;
458 pthread_kill(Thread, SIGUSR1); // Make tjread return from usleep()
459}
460
461
462//
463// Print message to screen and to DIM text service
464//
465void User::PrintMessage(const char *Format, ...) {
466
467 static char Error[] = "vasprintf() failed in PrintMessage()";
468 char *Text;
469
470 // Evaluate arguments
471 va_list ArgumentPointer;
472 va_start(ArgumentPointer, Format);
473 if (vasprintf(&Text, Format, ArgumentPointer) == -1) Text = Error;
474 va_end(ArgumentPointer);
475
476 // Print to console
477 printf("%s", Text); // New prompt
478 fflush(stdout);
479 if (strlen(Text)>0 && Text[strlen(Text)-1]=='\n') rl_on_new_line(); // New prompt
480
481 // Send to DIM text service
482 ConsoleOut->updateService(Text);
483
484 // Free old text
485 if (ConsoleText != Error) free(ConsoleText);
486 ConsoleText = Text;
487}
488
489
490// Ramp to new voltage with maximum step size given in fMaxDiff
491// No ramping when decreasing voltage
492unsigned int User::RampVoltages(int Crate, map<unsigned int, double> Voltages) {
493
494 map<unsigned int, double> Target;
495 int Errors = 0;
496
497 // Ramp until all channels at desired value
498 while (!Voltages.empty() && Errors < MAX_ERR_COUNT) {
499 // Remove channels already at target (check for DAC, not for floating-point voltage)
500 for (map<unsigned int, double>::iterator it = Voltages.begin(); it != Voltages.end(); ++it) {
501 //if (Crates[Crate]->GetDAC(it->first) == (unsigned int ) (it->second/90.0*0x0fff)) Voltages.erase(it);
502 if (fabs(Crates[Crate]->GetVoltage(it->first)-it->second) < 0.001) Voltages.erase(it);
503 }
504
505 // Limit voltage changes to fMaxDiff
506 Target = Voltages;
507 for (map<unsigned int, double>::iterator it = Target.begin(); it != Target.end(); ++it) {
508 if (Crates[Crate]->GetVoltage(it->first) + fMaxDiff < it->second) {
509 it->second = Crates[Crate]->GetVoltage(it->first) + fMaxDiff;
510 }
511 }
512
513 // Set channels to next target and wait 10 ms
514 if (Crates[Crate]->SetChannels(Target) != 1) Errors++;
515 usleep(10000);
516 }
517
518 return Errors;
519}
520
521
522//
523// Check status
524//
525void User::Monitor() {
526
527 static bool Warned = false;
528
529 while (!ExitRequest) {
530 for (unsigned int i=0; i<Crates.size(); i++) {
531 if (Crates[i]->ErrorCount > MAX_ERR_COUNT) {
532 if (!Warned) {
533 Warned = true;
534 Message(WARN, "Warning: Crate %d has many read/write errors, further error reporting disabled", i);
535 }
536 continue;
537 }
538
539 if (Crates[i]->ResetHit) {
540 Message(INFO, "Manual reset of board %d, setting voltages to zero and issuing system reset", i);
541 Crates[i]->GlobalSet(0);
542 Crates[i]->SystemReset();
543 }
544
545 if (!Crates[i]->WrapOK) {
546 Message(ERROR, "Wrap counter mismatch of board %d", i);
547 }
548
549 if (Crates[i]->ReadAll() != 1) {
550 Message(ERROR, "Monitor could not read status from crate %d", i);
551 continue;
552 }
553
554 map<unsigned int, double> Voltages;
555
556 for (int j=0; j<MAX_NUM_BOARDS*NUM_CHANNELS; j++) {
557 if (Crates[i]->OC[j/NUM_CHANNELS][j%NUM_CHANNELS]) {
558 Message(WARN, "Overcurrent on crate %d, board %d, channel %d, setting voltage to zero", i, j/NUM_CHANNELS, j%NUM_CHANNELS);
559 Voltages[j] = 0;
560 }
561 }
562 if (!Voltages.empty()) {
563 Crates[i]->SetChannels(Voltages);
564 Crates[i]->SystemReset();
565 }
566
567 if (Mode == mode_dynamic) Crates[i]->AdaptVoltages();
568 } // for
569
570 // Wait
571 usleep((unsigned long) floor(1000000./fStatusRefreshRate));
572 } // while
573}
574
575// Call monitor loop inside class
576void User::LaunchMonitor(User *m) {
577
578 m->Monitor();
579}
580
581
582//
583// Check if two strings match (min 1 character must match)
584//
585bool User::Match(string str, const char *cmd) {
586
587 return strncasecmp(str.c_str(),cmd,strlen(str.c_str())==0 ? 1:strlen(str.c_str())) ? false:true;
588}
589
590//
591// Conversion function from string to double or int
592//
593// Return false if conversion did not stop on whitespace or EOL character
594bool User::ConvertToDouble(string String, double *Result) {
595
596 char *EndPointer;
597
598 *Result = strtod(String.c_str(), &EndPointer);
599 if(!isspace(*EndPointer) && *EndPointer!='\0') return false;
600 return true;
601}
602
603bool User::ConvertToInt(string String, int *Result) {
604
605 char *EndPointer;
606
607 *Result = (int) strtol(String.c_str(), &EndPointer, 0);
608 if(!isspace(*EndPointer) && *EndPointer!='\0') return false;
609 return true;
610}
611
612//
613// Interprets a range
614//
615bool User::ConvertToRange(string String, struct User::Range &R) {
616
617 int N, M;
618
619 // Full range
620 if (Match(String, "all")) return true;
621
622 // Single number
623 if (ConvertToInt(String, &N)) {
624 if (N>= R.Min && N<=R.Max) {
625 R.Max = R.Min = N;
626 return true;
627 }
628 return false;
629 }
630
631 // Range a-b
632 vector<string> V = EvidenceServer::Tokenize(String, "-");
633 if (V.size()==2 && ConvertToInt(V[0], &N) && ConvertToInt(V[1], &M) && N>=R.Min && M<=R.Max) {
634 R.Min = N;
635 R.Max = M;
636 return true;
637 }
638
639 return false;
640}
Note: See TracBrowser for help on using the repository browser.