source: fact/BIASctrl/User.cc@ 10060

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