source: fact/BIASctrl/User.cc@ 10116

Last change on this file since 10116 was 10107, checked in by ogrimm, 14 years ago
hv command crashed when no bias board present
File size: 17.6 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
207 // Loop over given crates and channels
208 for (int i=Crt.Min; i<=Crt.Max; i++) for (int j=Chan.Min; j<=Chan.Max; j++) {
209 // Check that indices are in legal range
210 if (i<0 || i>=(int) Crates.size() || j<0 || j >=NUM_CHANNELS) continue;
211
212 // Voltage change (number starts with + oder -) ignored if current DAC value is zero
213 if (isdigit(Parameter[n+1][0])==0 && Crates[i]->GetDAC(j) == 0) continue;
214
215 // Relative or absolute change?
216 if (isdigit(Parameter[n+1][0]) == 0) Voltages[i][j] = Crates[i]->GetVoltage(j) + Double;
217 else Voltages[i][j] = Double;
218 } // Channels
219 } // Loop over command argument
220
221 // Ramp voltages and update DIM services
222 for (unsigned int i=0; i<Voltages.size(); i++) {
223 Errors += RampVoltages(i, Voltages[i]);
224 Crates[i]->UpdateDIM();
225 }
226
227 // Error message only if not yet too many errors
228 if (Errors > 0) {
229 for (unsigned int i=0; i<Crates.size(); i++) {
230 if (Crates[i]->ErrorCount > MAX_ERR_COUNT) return;
231 }
232 Message(ERROR, "%d errors occurred from SetChannels()", Errors);
233 }
234}
235
236//
237// Load bias settings from file
238//
239void User::cmd_load() {
240
241 char Buffer[MAX_COM_SIZE];
242 int Errors = 0, Channel;
243 unsigned int NBoards = 0;
244 double Value;
245 FILE *File;
246 map<unsigned int, double> Voltages;
247
248 // Open file
249 if ((File=fopen(Parameter[1].c_str(), "r")) == NULL) {
250 PrintMessage("Error: Could not open file '%s' (%s)\n", Parameter[1].c_str(), strerror(errno));
251 return;
252 }
253
254 // Scan through file line by line
255 while (fgets(Buffer, sizeof(Buffer), File) != NULL) {
256 for (unsigned int Crate=0; Crate<Crates.size(); Crate++) if (Match(Crates[Crate]->Name, Buffer)) {
257
258 PrintMessage("Found bias settings for board %s (#%d)\n\r", Crates[Crate]->Name, Crate);
259
260 Voltages.clear();
261 Channel = 0;
262 while (fscanf(File, "%lf", &Value)==1 && Channel<MAX_NUM_BOARDS*NUM_CHANNELS) {
263 Voltages[Channel++] = Value;
264 }
265
266 // Ramp channels
267 Errors += RampVoltages(Crate, Voltages);
268
269 // Update DIM service
270 Crates[Crate]->UpdateDIM();
271
272 if (ferror(File) != 0) {
273 PrintMessage("Error reading DAC value from file, terminating. (%s)\n",strerror(errno));
274 return;
275 }
276 else PrintMessage("\nFinished updating board\n");
277 NBoards++;
278 } // Loop over boards
279 } // while()
280
281 if (NBoards != Crates.size()) PrintMessage("Warning: Could not load bias settings for all connected crates\n");
282 else if (Errors == 0) PrintMessage("Success: Read bias settings for all connected crates\n");
283
284 if (Errors != 0) PrintMessage("Warning: %d error(s) occurred\n", Errors);
285
286 if (fclose(File) != 0) PrintMessage("Error: Could not close file '%s'\n", Parameter[1].c_str());
287}
288
289//
290// Set refresh rate
291//
292void User::cmd_rate() {
293
294 double Rate;
295
296 if (!ConvertToDouble(Parameter[1], &Rate)) {
297 PrintMessage("Error: Wrong number format\n");
298 return;
299 }
300
301 // Check limits
302 if (Rate<MIN_RATE || Rate>MAX_RATE) {
303 PrintMessage("Refresh rate out of range (min: %.2f Hz, max: %.2f Hz)\n", MIN_RATE, MAX_RATE);
304 return;
305 }
306
307 fStatusRefreshRate = Rate;
308 PrintMessage("Refresh rate set to %.2f Hz\n", fStatusRefreshRate);
309}
310
311//
312// Reset crates
313//
314void User::cmd_reset() {
315
316 struct Range R = {0, Crates.size()-1};
317
318 // Check ranges
319 if(!ConvertToRange(Parameter[1], R)) {
320 PrintMessage("Error, crate number out of range\n");
321 return;
322 }
323
324 for (int i=R.Min; i<=R.Max; i++) {
325 if (Crates[i]->SystemReset() == 1) PrintMessage("System reset of crate %s (#%d)\n", Crates[i]->Name, i);
326 else PrintMessage("Error: Could not reset board %s (#%d)\n", Crates[i]->Name, i);
327 }
328}
329
330//
331// Read channel
332//
333void User::cmd_gs() {
334
335 double Voltage;
336
337 if (!ConvertToDouble(Parameter[1], &Voltage)) return;
338
339 for (unsigned int i=0; i<Crates.size(); i++) {
340 if (Crates[i]->GlobalSet(Voltage) != 1) {
341 PrintMessage("Error: Could not global set crate %d\n", i);
342 }
343 }
344}
345
346//
347// Determine current measurement offset
348//
349void User::cmd_ccal() {
350
351 double Voltage;
352
353 if (!ConvertToDouble(Parameter[1], &Voltage)) {
354 PrintMessage("Error with format of voltage parameter\n");
355 return;
356 }
357
358 // Execute current offset determination
359 for (unsigned int i=0; i<Crates.size(); i++) {
360 if (!Crates[i]->CurrentCalib(Voltage)) {
361 PrintMessage("Error with current calibration of crate %d\n", i);
362 return;
363 }
364
365 PrintMessage("Current calibration of crate %d done\n", i);
366 }
367}
368
369//
370// Save bias settings of all boards
371//
372void User::cmd_save() {
373
374 FILE *File;
375 time_t Time = time(NULL);
376
377 if ((File = fopen(Parameter[1].c_str(), "w")) == NULL) {
378 PrintMessage("Error: Could not open file '%s' (%s)\n", Parameter[1].c_str(), strerror(errno));
379 return;
380 }
381
382 fprintf(File,"********** Bias settings of %s **********\n\n", ctime(&Time));
383
384 for (unsigned int i=0; i<Crates.size(); i++) {
385 fprintf(File, "%s\n\n", Crates[i]->Name);
386
387 for (int j=0; j<MAX_NUM_BOARDS*NUM_CHANNELS; j++) fprintf(File,"%.3f ",Crates[i]->GetVoltage(j));
388 fprintf(File, "\n");
389 }
390
391 if (fclose(File) != 0) {
392 PrintMessage("Error: Could not close file '%s' (%s)\n", Parameter[1].c_str(), strerror(errno));
393 }
394}
395
396//
397// Set operation mode
398//
399void User::cmd_mode() {
400
401 if (Match(Parameter[1], "static")) Mode = mode_static;
402 else {
403 Mode = mode_dynamic;
404 for (unsigned int i=0; i<Crates.size(); i++) {
405 Crates[i]->SetRefCurrent();
406 }
407 }
408}
409
410//
411// Print status
412//
413void User::cmd_status() {
414
415 PrintMessage(" Number of crates: %d\n", Crates.size());
416 PrintMessage(" Refresh rate: %.2f Hz\n", fStatusRefreshRate);
417 PrintMessage(" Time out: %.2f s\n\n", fTimeOut);
418 PrintMessage(" MaxDiff : %u\n", fMaxDiff);
419
420 for (unsigned int i=0; i<Crates.size(); i++) {
421 PrintMessage(" CRATE %d (%s)\n Wrap counter: %s (%d) Reset: %s Error count: %d\n ",
422 i, Crates[i]->Name, Crates[i]->WrapOK ? "ok":"error", Crates[i]->WrapCount,
423 Crates[i]->ResetHit ? "yes" : "no", Crates[i]->ErrorCount);
424
425 if (Parameter.size() == 1) PrintMessage("Channel voltages (in V)");
426 else if (Match(Parameter[1], "dac")) PrintMessage("Channel voltages (in DAC values)");
427 else PrintMessage("Channel currents (in uA)");
428
429 for (int j=0; j<MAX_NUM_BOARDS*NUM_CHANNELS; j++) {
430 if (j%12 == 0) PrintMessage("\n%3.1d: ", j);
431 if (!Crates[i]->Present[j/NUM_CHANNELS][j%NUM_CHANNELS]) PrintMessage(" - ");
432 else if (Parameter.size() == 1) PrintMessage("%#5.2f ",Crates[i]->GetVoltage(j));
433 else if (Match(Parameter[1], "dac")) PrintMessage("%5d ", Crates[i]->GetDAC(j));
434 else PrintMessage("%#5.2f %s ", Crates[i]->GetCurrent(j), Crates[i]->OC[j/NUM_CHANNELS][j%NUM_CHANNELS] ? "OC":"");
435 }
436 PrintMessage("\n");
437 }
438}
439
440//
441// Set timeout to return from read
442//
443void User::cmd_timeout() {
444
445 double Timeout;
446
447 if (!ConvertToDouble(Parameter[1], &Timeout)) {
448 PrintMessage("Error: Wrong number format\n");
449 return;
450 }
451
452 fTimeOut = Timeout;
453 PrintMessage("Timeout set to %.2f s\n", fTimeOut);
454}
455
456//
457// Exit program
458//
459void User::cmd_exit() {
460
461 ExitRequest = true;
462 pthread_kill(Thread, SIGUSR1); // Make tjread return from usleep()
463}
464
465
466//
467// Print message to screen and to DIM text service
468//
469void User::PrintMessage(const char *Format, ...) {
470
471 static char Error[] = "vasprintf() failed in PrintMessage()";
472 char *Text;
473
474 // Evaluate arguments
475 va_list ArgumentPointer;
476 va_start(ArgumentPointer, Format);
477 if (vasprintf(&Text, Format, ArgumentPointer) == -1) Text = Error;
478 va_end(ArgumentPointer);
479
480 // Print to console
481 printf("%s", Text); // New prompt
482 fflush(stdout);
483 if (strlen(Text)>0 && Text[strlen(Text)-1]=='\n') rl_on_new_line(); // New prompt
484
485 // Send to DIM text service
486 ConsoleOut->updateService(Text);
487
488 // Free old text
489 if (ConsoleText != Error) free(ConsoleText);
490 ConsoleText = Text;
491}
492
493
494// Ramp to new voltage with maximum step size given in fMaxDiff
495// No ramping when decreasing voltage
496unsigned int User::RampVoltages(int Crate, map<unsigned int, double> Voltages) {
497
498 map<unsigned int, double> Target;
499 int Errors = 0;
500
501 // Ramp until all channels at desired value
502 while (!Voltages.empty() && Errors < MAX_ERR_COUNT) {
503 // Remove channels already at target (check for DAC, not for floating-point voltage)
504 for (map<unsigned int, double>::iterator it = Voltages.begin(); it != Voltages.end(); ++it) {
505 //if (Crates[Crate]->GetDAC(it->first) == (unsigned int ) (it->second/90.0*0x0fff)) Voltages.erase(it);
506 if (fabs(Crates[Crate]->GetVoltage(it->first)-it->second) < 0.001) Voltages.erase(it);
507 }
508
509 // Limit voltage changes to fMaxDiff
510 Target = Voltages;
511 for (map<unsigned int, double>::iterator it = Target.begin(); it != Target.end(); ++it) {
512 if (Crates[Crate]->GetVoltage(it->first) + fMaxDiff < it->second) {
513 it->second = Crates[Crate]->GetVoltage(it->first) + fMaxDiff;
514 }
515 }
516
517 // Set channels to next target and wait 10 ms
518 if (Crates[Crate]->SetChannels(Target) != 1) Errors++;
519 usleep(10000);
520 }
521
522 return Errors;
523}
524
525
526//
527// Check status
528//
529void User::Monitor() {
530
531 static bool Warned = false;
532
533 while (!ExitRequest) {
534 for (unsigned int i=0; i<Crates.size(); i++) {
535 if (Crates[i]->ErrorCount > MAX_ERR_COUNT) {
536 if (!Warned) {
537 Warned = true;
538 Message(WARN, "Warning: Crate %d has many read/write errors, further error reporting disabled", i);
539 }
540 continue;
541 }
542
543 if (Crates[i]->ResetHit) {
544 Message(INFO, "Manual reset of board %d, setting voltages to zero and issuing system reset", i);
545 Crates[i]->GlobalSet(0);
546 Crates[i]->SystemReset();
547 }
548
549 if (!Crates[i]->WrapOK) {
550 Message(ERROR, "Wrap counter mismatch of board %d", i);
551 }
552
553 if (Crates[i]->ReadAll() != 1) {
554 Message(ERROR, "Monitor could not read status from crate %d", i);
555 continue;
556 }
557
558 map<unsigned int, double> Voltages;
559
560 for (int j=0; j<MAX_NUM_BOARDS*NUM_CHANNELS; j++) {
561 if (Crates[i]->OC[j/NUM_CHANNELS][j%NUM_CHANNELS]) {
562 Message(WARN, "Overcurrent on crate %d, board %d, channel %d, setting voltage to zero", i, j/NUM_CHANNELS, j%NUM_CHANNELS);
563 Voltages[j] = 0;
564 }
565 }
566 if (!Voltages.empty()) {
567 Crates[i]->SetChannels(Voltages);
568 Crates[i]->SystemReset();
569 }
570
571 if (Mode == mode_dynamic) Crates[i]->AdaptVoltages();
572 } // for
573
574 // Wait
575 usleep((unsigned long) floor(1000000./fStatusRefreshRate));
576 } // while
577}
578
579// Call monitor loop inside class
580void User::LaunchMonitor(User *m) {
581
582 m->Monitor();
583}
584
585
586//
587// Check if two strings match (min 1 character must match)
588//
589bool User::Match(string str, const char *cmd) {
590
591 return strncasecmp(str.c_str(),cmd,strlen(str.c_str())==0 ? 1:strlen(str.c_str())) ? false:true;
592}
593
594//
595// Conversion function from string to double or int
596//
597// Return false if conversion did not stop on whitespace or EOL character
598bool User::ConvertToDouble(string String, double *Result) {
599
600 char *EndPointer;
601
602 *Result = strtod(String.c_str(), &EndPointer);
603 if(!isspace(*EndPointer) && *EndPointer!='\0') return false;
604 return true;
605}
606
607bool User::ConvertToInt(string String, int *Result) {
608
609 char *EndPointer;
610
611 *Result = (int) strtol(String.c_str(), &EndPointer, 0);
612 if(!isspace(*EndPointer) && *EndPointer!='\0') return false;
613 return true;
614}
615
616//
617// Interprets a range
618//
619bool User::ConvertToRange(string String, struct User::Range &R) {
620
621 int N, M;
622
623 // Full range
624 if (Match(String, "all")) return true;
625
626 // Single number
627 if (ConvertToInt(String, &N)) {
628 if (N>= R.Min && N<=R.Max) {
629 R.Max = R.Min = N;
630 return true;
631 }
632 return false;
633 }
634
635 // Range a-b
636 vector<string> V = EvidenceServer::Tokenize(String, "-");
637 if (V.size()==2 && ConvertToInt(V[0], &N) && ConvertToInt(V[1], &M) && N>=R.Min && M<=R.Max) {
638 R.Min = N;
639 R.Max = M;
640 return true;
641 }
642
643 return false;
644}
Note: See TracBrowser for help on using the repository browser.