source: fact/BIASctrl/User.cc@ 10118

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