source: Feedback/Feedback.cc@ 2521

Last change on this file since 2521 was 269, checked in by ogrimm, 14 years ago
First commit of separated Feedback program
File size: 13.9 KB
Line 
1/**************************************************************\
2
3 Bias feedback
4
5 Oliver Grimm, July 2010
6
7\**************************************************************/
8
9
10#include "Feedback.h"
11#include "PixelMap.h"
12
13#define PIXMAP_LOCATION "../config/PixelMap.txt"
14
15static const char* FBState_Description[] = {
16 "Feedback off",
17 "Feedback active",
18 "Feedback acquiring new targets",
19 "Feedback measuring response with first voltage",
20 "Feedback measuring response with second voltage"
21};
22
23static const struct CL_Struct { const char *Name;
24 void (Feedback::*CommandPointer)();
25 const char *Parameters;
26 const char *Help;
27 } CommandList[] =
28 {{"mode", &Feedback::cmd_mode, "[off|active|target]", "Set or get feedback mode"},
29 {"average", &Feedback::cmd_average, "[n]", "Set ot get number of averages for feedback"},
30 {"gain", &Feedback::cmd_gain, "[gain]", "Set ot get feedback gain"},
31 {"target", &Feedback::cmd_target, "[pixel id]", "Set or get target value"},
32 {"response", &Feedback::cmd_response, "[voltage]", "Start or get response measurement"},
33 {"clear", &Feedback::cmd_clear, "", "Clear feedback signals"},
34 {"data", &Feedback::cmd_data, "", "New feedback signals"},
35 {"help", &Feedback::cmd_help, "", "Print help"},
36 {"exit", &Feedback::cmd_exit, "", "Exit program"}};
37
38using namespace std;
39
40
41// ----- Constructor: Initialise feedback
42Feedback::Feedback(): EvidenceServer(SERVER_NAME) {
43
44 PixMap = new PixelMap(PIXMAP_LOCATION, false);
45 TimeBarrier = 0;
46
47 // DIM console service used in PrintMessage()
48 ConsoleText = NULL;
49 ConsoleOut = new DimService(SERVER_NAME"/ConsoleOut", (char *) "");
50
51 // Get pixel ID table
52 fIDTable = Tokenize(GetConfig("IDTable"), " \t");
53 Multiplicity = new unsigned int [fIDTable.size()];
54
55 multiset<string> A;
56 char *Buf;
57
58 for (unsigned int i=0; i<fIDTable.size(); i++) {
59 if (asprintf(&Buf, "BiasID%d%d%d", PixMap->Pixel_to_HVboard(fIDTable[i]),
60 PixMap->Pixel_to_HVchain(fIDTable[i]), PixMap->Pixel_to_HVchannel(fIDTable[i])) == -1) Message(FATAL, "asprintf() failed");
61 A.insert(Buf);
62 free(Buf);
63 }
64
65 for (unsigned int i=0; i<fIDTable.size(); i++) {
66 if (asprintf(&Buf, "BiasID%d%d%d", PixMap->Pixel_to_HVboard(fIDTable[i]),
67 PixMap->Pixel_to_HVchain(fIDTable[i]), PixMap->Pixel_to_HVchannel(fIDTable[i])) == -1) Message(FATAL, "asprintf() failed");
68 Multiplicity[i] = A.count(Buf);
69 free(Buf);
70 }
71
72 // Initialise with zero content ???
73 Average = new float [fIDTable.size()];
74 Sigma = new float [fIDTable.size()];
75 Response = new float [fIDTable.size()];
76 Target = new float [fIDTable.size()];
77 Buffer = new float [fIDTable.size()];
78
79 DIMAverage = new float [fIDTable.size()];
80 DIMSigma = new float [fIDTable.size()];
81
82 // Get remaing configuration data
83 fDefaultNumAverage = atoi(GetConfig("DefaultNumAverage").c_str());
84
85 vector<string> Token = Tokenize(GetConfig("DefaultResponse"), " \t");
86 for (unsigned int i=0; i< Token.size(); i++) {
87 if (i < fIDTable.size()) Response[i] = (float) atof(Token[i].c_str());
88 }
89
90 Token = Tokenize(GetConfig("DefaultTarget"), " \t");
91 for (unsigned int i=0; i<Token.size(); i++) {
92 if (i < fIDTable.size()) Target[i] = (float) atof(Token[i].c_str());
93 }
94
95 // Provide DIM services
96 FeedbackAverage = new DimService (SERVER_NAME"/Average", "F", DIMAverage, fIDTable.size() * sizeof(float));
97 FeedbackSigma = new DimService (SERVER_NAME"/Sigma", "F", DIMSigma, fIDTable.size() * sizeof(float));
98 FeedbackResponse = new DimService (SERVER_NAME"/Response", "F", Response, fIDTable.size() * sizeof(float));
99 FeedbackTarget = new DimService (SERVER_NAME"/Target", "F", Target, fIDTable.size() * sizeof(float));
100 CountService = new DimService (SERVER_NAME"/Count", Count);
101 FeedbackState = new DimService (SERVER_NAME"/State", "I:1;C", NULL, 0);
102
103 // Initial state
104 Gain = atof(GetConfig("DefaultGain").c_str());
105 SetFBMode(Off);
106 NumAverages = fDefaultNumAverage;
107 LastServiceUpdate = 0;
108
109 // Install DIM command (after all initialized)
110 Command = new DimCommand((char *) SERVER_NAME"/Command", (char *) "C", this);
111}
112
113
114// ----- Destructor
115Feedback::~Feedback() {
116
117 delete Command;
118 delete FeedbackState;
119 delete CountService;
120 delete FeedbackAverage;
121 delete FeedbackSigma;
122 delete FeedbackResponse;
123 delete FeedbackTarget;
124
125 delete[] Average; delete[] Response;
126 delete[] DIMAverage; delete[] DIMSigma;
127 delete[] Sigma; delete[] Target;
128 delete[] Buffer; delete[] Multiplicity;
129 delete PixMap;
130
131 delete ConsoleOut;
132 free(ConsoleText);
133}
134
135
136// ----- Set/get mode of feedback
137void Feedback::cmd_mode() {
138
139 if (Match(Parameter[1], "off")) SetFBMode(Off);
140 else if (Match(Parameter[1], "active")) SetFBMode(Active);
141 else if (Match(Parameter[1], "targets")) SetFBMode(Targets);
142 else PrintMessage("%s.\n", FBState_Description[FBMode]);
143}
144
145
146// ----- Set/get current number of events
147void Feedback::cmd_average() {
148
149 if (Parameter.size() == 1) {
150 PrintMessage("Current feedback events: %u (acting when %u events reached)\n", Count, NumAverages);
151 }
152 else if (atoi(Parameter[1].c_str())>=0) NumAverages = atoi(Parameter[1].c_str());
153 else PrintUsage();
154}
155
156
157// ----- Set/get feedback gain
158void Feedback::cmd_gain() {
159
160 if (Parameter.size() == 2) Gain = atof(Parameter[1].c_str());
161 PrintMessage("Feedback gain is %.2f\n", Gain);
162}
163
164
165// ----- Set/get target value
166void Feedback::cmd_target() {
167
168 if (Parameter.size() == 1) {
169 for (unsigned int i=0; i<fIDTable.size(); i++) {
170 PrintMessage("%s: %.2f ", fIDTable[i].c_str(), Target[i]);
171 if (i%5 == 4) PrintMessage("\n\r");
172 }
173 PrintMessage("\n");
174 return;
175 }
176
177 if (Parameter.size() != 3) {
178 PrintUsage();
179 return;
180 }
181
182 if (Match(Parameter[1], "all")) {
183 for (unsigned int i=0; i<fIDTable.size(); i++) {
184 Target[i] = atof(Parameter[2].c_str());
185 }
186 FeedbackTarget->updateService();
187 return;
188 }
189
190 for (unsigned int i=0; i<fIDTable.size(); i++) {
191 if (Match(Parameter[1], fIDTable[i])) {
192 Target[i] = atof(Parameter[2].c_str());
193 FeedbackTarget->updateService();
194 return;
195 }
196 }
197
198 PrintMessage("Invalid board, chip or channel number.\n");
199}
200
201
202// ----- Start response measurement
203void Feedback::cmd_response() {
204
205 if (Parameter.size() == 1) {
206 for (unsigned int i=0; i<fIDTable.size(); i++) {
207 PrintMessage("%s: %.2f ", fIDTable[i].c_str(), Response[i]);
208 if (i%5 == 4) PrintMessage("\n\r");
209 }
210 PrintMessage("\n");
211 }
212 else if (atof(Parameter[1].c_str()) != 0) MeasureResponse(atof(Parameter[1].c_str()));
213 else PrintUsage();
214}
215
216
217// ----- Clear accumulated averages
218void Feedback::cmd_clear() {
219
220 ClearAverages();
221}
222
223
224// ----- Accumulate feedback data and calculate voltage change if required number of events reached.
225void Feedback::cmd_data() {
226
227 float Correction;
228
229 // Refect data is feedback off or timestamp too early
230 if (FBMode == Off || getCommand()->getTimestamp() < TimeBarrier) return;
231 TimeBarrier = 0;
232
233 // Calculate average signal
234 for (unsigned int i=0; i<Parameter.size()-1, i<fIDTable.size(); i++) {
235 Average[i] += atof(Parameter[i+1].c_str());
236 Sigma[i] += pow(atof(Parameter[i+1].c_str()), 2);
237 }
238
239 // Update DIM count service regularly
240 if (time(NULL)-LastServiceUpdate > 2) {
241 LastServiceUpdate = time(NULL);
242 CountService->updateService();
243 }
244
245 // Check if acquired number of event requires action
246 if (++Count<NumAverages) return;
247
248 // Feedback action
249 std::stringstream Cmd;
250
251 for (unsigned int i=0; i<fIDTable.size(); i++) {
252 // Calculate average
253 Average[i] /= Count;
254 Sigma[i] = sqrt(Sigma[i]/Count - pow(Average[i],2))/sqrt(Count);
255 DIMAverage[i] = Average[i];
256 DIMSigma[i] = Sigma[i];
257
258 switch (FBMode) {
259 case Active:
260 // Determine correction from response maxtrix and change voltages
261 Correction = -(Target[i] - Average[i])*Response[i]*Gain;
262 // Limit voltage steps
263 if (fabs(Correction) > 0.1) Correction = fabs(Correction)/Correction*0.1; // Limit changes to 100 mV
264 if (Correction==0 || Target[i]==0) break;
265 // Add voltage change command if not too noisy
266 if(fabs(Average[i]) > 2*Sigma[i]) {
267 Cmd << fIDTable[i] << " " << std::showpos << Correction/Multiplicity[i] << " ";
268 }
269 break;
270
271 case Targets: // Take average as new targets
272 Target[i] = Average[i];
273 break;
274
275 case ResponseFirst: // First point of response measurement done
276 Buffer[i] = Average[i];
277 Cmd << fIDTable[i] << " " << std::showpos << DiffVoltage/Multiplicity[i] << " ";
278 break;
279
280 case ResponseSecond: // Determine response from signal variation
281 if (Buffer[i] == Average[i]) {
282 PrintMessage("Warning, response singular for pixel %s\n", fIDTable[i].c_str());
283 Response[i] = 0;
284 }
285 else Response[i] = DiffVoltage/(Buffer[i] - Average[i]);
286
287 Cmd << fIDTable[i] << " " << std::showpos << -DiffVoltage/2/Multiplicity[i] << " ";
288 break;
289
290 default: break; // to suppress warning abount not handled enumeration value
291 }
292 } // for()
293
294 // Update DIM service
295 FeedbackAverage->updateService();
296 FeedbackSigma->updateService();
297
298 // Send command (non-blocking since in handler thread)
299 if (!Cmd.str().empty()) {
300 DimClient::sendCommandNB("Bias/Command", (char *) ("hv "+Cmd.str()).c_str());
301 }
302
303 switch (FBMode) {
304 case Targets:
305 FeedbackTarget->updateService();
306 PrintMessage("New targets set, switching off\n");
307 SetFBMode(Off);
308 break;
309 case ResponseFirst:
310 SetFBMode(ResponseSecond);
311 PrintMessage("Increasing voltages by %f for response measurement, acquiring data\n", DiffVoltage);
312 break;
313 case ResponseSecond:
314 FeedbackResponse->updateService();
315 PrintMessage("Response measurements finished, original voltages set, switching off\n");
316 SetFBMode(Off);
317 break;
318 default: break; // to suppress warning abount not handled enumeration value
319 }
320 ClearAverages();
321
322 return;
323}
324
325
326// ----- Print help
327void Feedback::cmd_help() {
328
329 char Buffer[BUF_LENGTH];
330
331 for(unsigned int i=0; i<sizeof(CommandList)/sizeof(CL_Struct); i++) {
332 snprintf(Buffer, sizeof(Buffer), "%s %s", CommandList[i].Name, CommandList[i].Parameters);
333 PrintMessage("%-28s%s\n", Buffer, CommandList[i].Help);
334 }
335}
336
337
338// ----- Exit programm
339void Feedback::cmd_exit() {
340
341 ExitRequest = true;
342}
343
344
345// ----- Clear average values and event counter
346void Feedback::ClearAverages() {
347
348 for (unsigned int i=0; i<fIDTable.size(); i++) {
349 Average[i] = 0.0;
350 Sigma[i] = 0.0;
351 }
352 Count = 0;
353 CountService->updateService();
354}
355
356
357// ----- Set feedback mode and clear averages
358void Feedback::SetFBMode(FBState Mode) {
359
360 FBMode = Mode;
361 if (Mode != ResponseFirst) PrintMessage("%s\n", FBState_Description[FBMode]);
362 else PrintMessage("%s (voltage difference %.3f)\n", FBState_Description[FBMode], DiffVoltage);
363 ClearAverages();
364
365 // Update state service
366 State.State = FBMode;
367 strncpy(State.Text, FBState_Description[FBMode], sizeof(State.Text));
368 FeedbackState->updateService(&State, sizeof(State));
369
370 // Reject feedback signals received earlier than this time
371 TimeBarrier = time(NULL) + 2;
372}
373
374
375// ----- Measure response matrix
376void Feedback::MeasureResponse(float U) {
377
378 std::stringstream Cmd;
379
380 if (U == 0) {
381 PrintMessage("Error, voltage difference must be non-zero.\n");
382 return;
383 }
384
385 // Build command
386 for (unsigned int i=0; i<fIDTable.size(); i++) {
387 Cmd << fIDTable[i] << " " << std::showpos << -U/2/Multiplicity[i] << " ";
388 }
389
390 // Send command
391 if (!Cmd.str().empty()) {
392 DimClient::sendCommand("Bias/Command", ("hv "+Cmd.str()).c_str());
393 }
394
395 DiffVoltage = U;
396 SetFBMode(ResponseFirst);
397 PrintMessage("HV Feedback: Decreasing voltages by %f for response measurement, acquiring data.\n",DiffVoltage/2);
398}
399
400
401// ----- Print usage text for command
402void Feedback::PrintUsage() {
403
404 for (unsigned int i=0; i<sizeof(CommandList)/sizeof(CL_Struct); i++) {
405 if (Match(Parameter[0], CommandList[Count].Name)) {
406 PrintMessage("Usage: %s %s\n", Parameter[0].c_str(), CommandList[Count].Parameters);
407 }
408 }
409}
410
411
412// ----- Print message to console only
413void Feedback::PrintMessage(const char *Format, ...) {
414
415 static char Error[] = "vasprintf() failed in PrintMessage()";
416 char *Text;
417
418 // Evaluate arguments
419 va_list ArgumentPointer;
420 va_start(ArgumentPointer, Format);
421 if (vasprintf(&Text, Format, ArgumentPointer) == -1) Text = Error;
422 va_end(ArgumentPointer);
423
424 // Print to console
425 if(strlen(Text)>0 && Text[strlen(Text)-1]=='\n') printf("\r%sCmd> ", Text); // New prompt
426 else printf("%s", Text);
427 fflush(stdout);
428
429 // Send to DIM text service
430 ConsoleOut->updateService(Text);
431
432 // Free old text
433 if (ConsoleText != Error) free(ConsoleText);
434 ConsoleText = Text;
435}
436
437
438// ----- DIM command handler
439void Feedback::commandHandler() {
440
441 string Command = ToString("C", getCommand()->getData(), getCommand()->getSize());
442
443 // Parse command into tokens
444 Parameter.clear();
445 Parameter = Tokenize(Command, " \t");
446 if (Parameter.empty()) return;
447
448 // Search for command
449 for (unsigned int Count=0; Count<sizeof(CommandList)/sizeof(CL_Struct); Count++) {
450 if (Match(Parameter[0], CommandList[Count].Name)) {
451 (this->*CommandList[Count].CommandPointer)();
452 return;
453 }
454 }
455
456 // Command not found
457 PrintMessage("Unknown command '%s'\n", Command.c_str());
458}
459
460
461// ----- Check if two strings match (min 1 character must match)
462bool Feedback::Match(string str, string cmd) {
463 return strncasecmp(str.c_str(),cmd.c_str(),strlen(str.c_str())==0 ? 1:strlen(str.c_str())) ? false:true;
464}
465
466
467// ================
468// Main program
469// ================
470
471int main() {
472
473 char *Command;
474
475 system("clear");
476 printf("\n*** Bias feedback (built %s, %s, revision %s) *** \n\n",__DATE__, __TIME__, REVISION);
477
478 // Readline library uses getc() (allows interruption by signal)
479 rl_getc_function = getc;
480
481 // Construct main instance (static ensures destructor is called with exit())
482 static Feedback M;
483
484 // Command loop
485 while (!M.ExitRequest) {
486 // Read Command
487 Command = readline("\rCmd> ");
488 if (Command == NULL) continue;
489 if(strlen(Command)>0) add_history(Command);
490
491 // Process command
492 DimClient::sendCommand(SERVER_NAME"/Command", Command);
493 free(Command);
494 }
495}
Note: See TracBrowser for help on using the repository browser.