source: fact/BIASctrl/User.cc@ 10050

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