source: fact/BIASctrl/User.cc@ 10071

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