source: fact/FADctrl/FADBoard.cc@ 11014

Last change on this file since 11014 was 10980, checked in by ogrimm, 13 years ago
DIM event service contains active boards only
File size: 21.5 KB
Line 
1/********************************************************************\
2
3 Class interfacing to FAD board
4
5\********************************************************************/
6
7#include "FADBoard.h"
8using namespace std;
9
10//
11// Constructor
12//
13FADBoard::FADBoard(string Server, unsigned short ServerPort, class FAD *Parent, unsigned int Num) {
14
15 int Ret;
16
17 // Initialization
18 m = Parent;
19 Active = false;
20 Continue = true;
21 CommOK = false;
22 ACalib.Time = -1;
23 Status.Update.tv_sec = -1;
24 Port = ServerPort;
25 Status.Frequency = 0;
26 Status.Rate = 0;
27 Status.BoardID = 0;
28
29 Name = new char [Server.size()+1]; // Name in permanent memory for DIM service
30 strcpy(Name, Server.c_str());
31
32 // Initialise mutex for synchronization
33 pthread_mutexattr_t Attr;
34
35 if ((Ret = pthread_mutexattr_init(&Attr)) != 0) {
36 m->Message(m->ERROR, "pthread_mutex_init() failed in FADBoard constructor (%s)", strerror(Ret));
37 }
38 if ((Ret = pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_ERRORCHECK)) != 0) {
39 m->Message(m->ERROR, "pthread_mutex_settype() failed in FADBoard constructor (%s)", strerror(Ret));
40 }
41 if ((Ret = pthread_mutex_init(&Mutex, &Attr)) != 0) {
42 m->Message(m->FATAL, "pthread_mutex_init() failed in FADBoard constructor (%s)", strerror(Ret));
43 }
44
45 // Initialise condition variable for synchronization
46 if ((Ret = pthread_cond_init(&CondVar, NULL)) != 0) {
47 m->Message(m->FATAL, "pthread_cond_init() failed in FADBoard constructor (%s)", strerror(Ret));
48 }
49
50 // Construct DIM service name prefix
51 stringstream ID;
52 ID << SERVER_NAME"/Board" << setfill('0') << setw(2) << Num << "/";
53
54 DIM_Name = new DimService((ID.str()+"Server").c_str(), Name);
55 DIM_Status = new DimService((ID.str()+"Status").c_str(), (char *) "");
56 DIM_ID = new DimService((ID.str()+"BoardID").c_str(), (char *) "S", NULL, 0);
57 DIM_Rate = new DimService((ID.str()+"RateHz").c_str(), Status.Rate);
58 DIM_Frequency = new DimService((ID.str()+"Frequency").c_str(), Status.Frequency);
59 DIM_TriggerNum = new DimService((ID.str()+"TriggerNum").c_str(), (char *) "I", &Status.TriggerNum, sizeof(Status.TriggerNum));
60 DIM_Temp = new DimService((ID.str()+"Temperature").c_str(), (char *) "F", NULL, 0);
61 DIM_DAC = new DimService((ID.str()+"DAC").c_str(), (char *) "S", NULL, 0);
62 DIM_ROI = new DimService((ID.str()+"ROI").c_str(), (char *) "S", NULL, 0);
63 DIM_ACalData = new DimService((ID.str()+"ACalData").c_str(), (char *) "F", NULL, 0);
64
65 // Create thread that connects and receives data
66 SetStatus("Trying to connect...");
67
68 if ((Ret = pthread_create(&Thread, NULL, (void * (*)(void *)) LaunchThread, (void *) this)) != 0) {
69 m->Message(m->FATAL, "pthread_create() failed in FADBoard() (%s)", strerror(Ret));
70 }
71
72 // Start thread to connect to other sockets
73 DimThread::start();
74}
75
76//
77// Destructor
78//
79FADBoard::~FADBoard() {
80
81 int Ret;
82
83 // Cancel thread (if it did not quit already) and wait for it to quit
84 if ((Ret = pthread_cancel(Thread)) != 0 && Ret != ESRCH) {
85 m->Message(m->ERROR, "pthread_cancel() failed in ~FADBoard() (%s)", strerror(Ret));
86 }
87 if ((Ret = pthread_join(Thread, NULL)) != 0) {
88 m->Message(m->ERROR, "pthread_join() failed in ~FADBoard (%s)", strerror(Ret));
89 }
90
91 // Delete condition variable
92 if ((Ret = pthread_cond_destroy(&CondVar)) != 0) {
93 m->Message(m->ERROR, "pthread_cond_destroy() failed for %s in ~FADBoard (%s)", Name, strerror(Ret));
94 }
95
96 // Delete mutex
97 if ((Ret = pthread_mutex_destroy(&Mutex)) != 0) {
98 m->Message(m->ERROR, "pthread_mutex_destroy() failed for %s in ~FADBoard (%s)", Name, strerror(Ret));
99 }
100
101 delete DIM_Name;
102 delete DIM_Status;
103 delete DIM_ID;
104 delete DIM_Rate;
105 delete DIM_Frequency;
106 delete DIM_TriggerNum;
107 delete DIM_Temp;
108 delete DIM_DAC;
109 delete DIM_ROI;
110 delete DIM_ACalData;
111 delete[] Name;
112}
113
114
115//
116// Send data to board
117//
118void FADBoard::Send(const void *Data, size_t Bytes) {
119
120 // Do not send if not active or communication problem
121 if (!Active || !CommOK) return;
122
123 // Write data
124 ssize_t Result = write(Socket, Data, Bytes);
125
126 // Check result
127 if (Result == -1) m->PrintMessage("Error: Could not write to socket (%s)\n", strerror(errno));
128 else if ((size_t) Result < Bytes) m->PrintMessage("Error: Could only write %d bytes out of %d to socket\n", Result, Bytes);
129}
130
131void FADBoard::Send(unsigned short Data) {
132
133 unsigned short Buffer = htons(Data);
134
135 Send(&Buffer, sizeof(unsigned short));
136}
137
138
139//
140// Get board status (mutex protected to avoid concurrent access in ReadLoop)
141//
142struct FADBoard::BoardStatus FADBoard::GetStatus() {
143
144 int Ret;
145 struct BoardStatus S;
146
147 // Lock
148 if ((Ret = pthread_mutex_lock(&Mutex)) != 0) {
149 m->Message(m->FATAL, "pthread_mutex_lock() failed in ReadLoop() (%s)", strerror(Ret));
150 }
151
152 S = Status;
153
154 // Unlock
155 if ((Ret = pthread_mutex_unlock(&Mutex)) != 0) {
156 m->Message(m->FATAL, "pthread_mutex_unlock() failed in Unlock() (%s)", strerror(Ret));
157 }
158
159 return S;
160}
161
162
163//
164// Perform amplitude calibration in steps
165//
166// The steps are intended to assure that up to date data is available
167void FADBoard::AmplitudeCalibration() {
168
169 vector<unsigned short> ROICmd;
170 unsigned short DACCmd[] = {htons(CMD_Write | (BADDR_DAC + 1)), 0, htons(CMD_Write | (BADDR_DAC + 2)), 0, htons(CMD_Write | (BADDR_DAC + 3)), 0, htons(CMD_Execute) };
171 string Message = string("ACALIBDONE")+Name+"\n";
172
173 switch (State) {
174 // ====== Part A: Check if amplitude calibration should start and initialise =====
175 case standbye:
176 if (m->Mode != m->acalib) break;
177
178 // Invalidate current calibration
179 ACalib.Time = -1;
180 Count = 0;
181
182 // Save initial board status, set all ROIs to 1024 and set DAC values (no triggers while setting ROI)
183 InitialStatus = GetStatus();
184
185 for (unsigned int i=0; i<NChips*NChannels; i++) {
186 ROICmd.push_back(htons(CMD_Write | (BADDR_ROI + i)));
187 ROICmd.push_back(htons(NBins));
188 }
189 ROICmd.push_back(htons(CMD_Execute));
190 Send(&ROICmd[0], ROICmd.size()*sizeof(unsigned short));
191
192 DACCmd[1] = htons(0);
193 DACCmd[3] = htons(0);
194 DACCmd[5] = htons(0);
195 Send(DACCmd, sizeof(DACCmd));
196
197 // Clear sum vector and set state to accumulate
198 memset(Sum, 0, sizeof(Sum));
199 State = baseline;
200 SetStatus("Starting calilbration");
201 break;
202
203 // ====== Part B: Baseline calibration =====
204 case baseline:
205 // Check for stopping
206 if (m->Mode != m->acalib) {
207 State = cleanup;
208 break;
209 }
210
211 // Average
212 for (unsigned int Chip=0; Chip<NChips; Chip++) {
213 for (unsigned int Chan=0; Chan<NChannels; Chan++) {
214 for (int i=0; i<Status.ROI[Chip][Chan]; i++) {
215 Sum[Chip][Chan][(i+Status.TriggerCell[Chip]) % NBins] += Data[Chip][Chan][i];
216 }
217 }
218 }
219 Count++;
220
221 // Determine baseline if integration finished
222 if (Count < m->NumEventsRequested) break;
223
224 for (unsigned int i=0; i<NChips; i++) {
225 for (unsigned int j=0; j<NChannels; j++) {
226 for (unsigned int k=0; k<NBins; k++) {
227 ACalib.Baseline[i][j][k] = Sum[i][j][k] / m->NumEventsRequested;
228 }
229 }
230 }
231
232 // Set new DAC values and start accumulation
233 DACCmd[1] = htons(50000);
234 DACCmd[3] = htons(50000);
235 DACCmd[5] = htons(50000);
236 Send(DACCmd, sizeof(DACCmd));
237
238 // Clear sum vector and set state to accumulate
239 memset(Sum, 0, sizeof(Sum));
240 Count = 0;
241 State = gain;
242 break;
243
244 // ====== Part C: Gain calibration =====
245 case gain:
246 // Check for stopping
247 if (m->Mode != m->acalib) {
248 State = cleanup;
249 break;
250 }
251
252 // Average
253 for (unsigned int Chip=0; Chip<NChips; Chip++) {
254 for (unsigned int Chan=0; Chan<NChannels; Chan++) {
255 for (int i=0; i<Status.ROI[Chip][Chan]; i++) {
256 Sum[Chip][Chan][(i+Status.TriggerCell[Chip]) % NBins] += Data[Chip][Chan][i];
257 }
258 }
259 }
260 Count++;
261
262 // Determine gain if integration finished
263 if (Count < m->NumEventsRequested) break;
264
265 for (unsigned int i=0; i<NChips; i++) {
266 for (unsigned int j=0; j<NChannels; j++) {
267 for (unsigned int k=0; k<NBins; k++) {
268 ACalib.Gain[i][j][k] = (Sum[i][j][k] / m->NumEventsRequested) - ACalib.Baseline[i][j][k];
269 }
270 }
271 }
272
273 // Set new DAC values and start accumulation
274 DACCmd[1] = htons(0);
275 DACCmd[3] = htons(0);
276 DACCmd[5] = htons(0);
277 Send(DACCmd, sizeof(DACCmd));
278
279 // Clear sum vector and set state to accumulate
280 memset(Sum, 0, sizeof(Sum));
281 Count = 0;
282 State = secondary;
283 break;
284
285 // ====== Part D: Secondary calibration =====
286 case secondary:
287 // Check for stopping
288 if (m->Mode != m->acalib) {
289 State = cleanup;
290 break;
291 }
292
293 // Average
294 for (unsigned int Chip=0; Chip<NChips; Chip++) {
295 for (unsigned int Chan=0; Chan<NChannels; Chan++) {
296 for (int i=0; i<Status.ROI[Chip][Chan]; i++) {
297 Sum[Chip][Chan][i] = Data[Chip][Chan][i] - ACalib.Baseline[Chip][Chan][(i-Status.TriggerCell[Chip]) % NBins];
298 }
299 }
300 }
301 Count++;
302
303 // Determine secondary baseline if integration finished
304 if (Count < m->NumEventsRequested) break;
305
306 for (unsigned int i=0; i<NChips; i++) {
307 for (unsigned int j=0; j<NChannels; j++) {
308 for (unsigned int k=0; k<NBins; k++) {
309 ACalib.Secondary[i][j][k] = Sum[i][j][k] / (double) m->NumEventsRequested;
310 }
311 }
312 }
313
314 // Store calibration time and temperature
315 ACalib.DNA = Status.DNA;
316 ACalib.Frequency = Status.Frequency;
317 ACalib.Time = time(NULL);
318 ACalib.Temp = 0;
319 for (unsigned int i=0; i<NTemp; i++) ACalib.Temp += Status.Temp[i] / NTemp;
320
321 // Inform event thread that calibration is finished for this board
322 if (write(m->Pipe[1], Message.data(), Message.size()) == -1) {
323 m->Message(m->ERROR, "write() to Pipe[1] failed in class FADBoard::AmplitudeCalibration (%s)", strerror(errno));
324 }
325
326 SetStatus("Finished calibration");
327 State = cleanup;
328 break;
329
330 // ====== Part E: Write back original ROI and DAC settings =====
331 case cleanup:
332 // ROI values
333
334 ROICmd.clear();
335 for (unsigned int i=0; i<NChips*NChannels; i++) {
336 ROICmd.push_back(htons(CMD_Write | (BADDR_ROI + i)));
337 ROICmd.push_back(htons(InitialStatus.ROI[i/NChannels][i%NChannels]));
338 }
339 ROICmd.push_back(htons(CMD_Execute));
340 Send(&ROICmd[0], ROICmd.size()*sizeof(unsigned short));
341
342 // DAC values
343 DACCmd[1] = htons(InitialStatus.DAC[1]);
344 DACCmd[3] = htons(InitialStatus.DAC[2]);
345 DACCmd[5] = htons(InitialStatus.DAC[3]);
346 Send(DACCmd, sizeof(DACCmd));
347
348 // Update DIM service with calibration information
349 for (unsigned int i=0; i<NChips; i++) {
350 for (unsigned int j=0; j<NChannels; j++) {
351 for (unsigned int k=0; k<NBins; k++) {
352 ACalData[0][i][j][k] = ACalib.Baseline[i][j][k];
353 ACalData[1][i][j][k] = ACalib.Gain[i][j][k];
354 ACalData[2][i][j][k] = ACalib.Secondary[i][j][k];
355 }
356 }
357 }
358 DIM_ACalData->updateService(ACalData, 3*NChips*NChannels*NBins*sizeof(float));
359
360 State = wait;
361 break;
362
363 // ====== Wait for Mode not being idle =====
364 case wait:
365 if (m->Mode == m->idle) State = standbye;
366 break;
367 }
368}
369
370//
371// Connect to board and read data
372//
373void FADBoard::ReadLoop() {
374
375 char Buffer[READ_BUFFER_SIZE];
376 unsigned int Pos = 0, Count = 0;
377 const PEVNT_HEADER *Header = (PEVNT_HEADER *) Buffer;
378 ssize_t Result;
379 struct sockaddr_in SocketAddress;
380 struct BoardStatus PrevStatus;
381 int Ret;
382
383 // Resolve hostname
384 struct hostent *Host = gethostbyname(Name);
385 if (Host == 0) {
386 SetStatus("Could not resolve host name '%s'", Name);
387 return;
388 }
389
390 SocketAddress.sin_family = PF_INET;
391 SocketAddress.sin_port = htons(Port);
392 SocketAddress.sin_addr = *(struct in_addr*) Host->h_addr;
393
394 // Open socket descriptor
395 if ((Socket = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
396 m->Message(m->ERROR, "Could not open socket for %s (%s)\n", Name, strerror(errno));
397 return;
398 }
399
400 // Connect to server
401 if (connect(Socket, (struct sockaddr *) &SocketAddress, sizeof(SocketAddress)) == -1) {
402 SetStatus("Could not connect to port %hu (%s)", Port, strerror(errno));
403 }
404 else {
405 CommOK = true;
406 Active = true;
407 SetStatus("Connected");
408 }
409
410 memset(&PrevStatus, 0, sizeof(PrevStatus));
411
412 // Leave loop if program termination requested or board communication not OK
413 while (!m->ExitRequest && CommOK) {
414 // Read data from socket
415 Result = read(Socket, Buffer + Pos, sizeof(Buffer)-Pos);
416
417 // Check result of read
418 if (Result == -1) {
419 m->Message(m->ERROR, "Could not read from socket for %s, exiting read loop (%s)\n", Name, strerror(errno));
420 CommOK = false;
421 break;
422 }
423 else if (Result == 0) {
424 SetStatus("Server not existing anymore, exiting read loop");
425 CommOK = false;
426 break;
427 }
428
429 // If not active, discard incoming data
430 if (!Active) continue;
431
432 // Advance write pointer
433 Pos += Result;
434
435 // Check if internal buffer full
436 if (Pos == sizeof(Buffer)) {
437 SetStatus("Internal buffer full, deleting all data in buffer");
438 Pos = 0;
439 continue;
440 }
441
442 // Check if buffer starts with start_package_flag, remove data if not
443 unsigned int Temp = 0;
444 while (ntohs(*((unsigned short *) (Buffer+Temp))) != 0xfb01 && Temp<Pos) Temp++;
445 if (Temp != 0) {
446 memmove(Buffer, Buffer+Temp, Pos-Temp);
447 Pos -= Temp;
448 SetStatus("Removed %d bytes because of start_package_flag not found", Temp);
449 continue;
450 }
451
452 // Wait until the buffer contains at least enough bytes to potentially hold a PEVNT_HEADER
453 if (Pos < sizeof(PEVNT_HEADER)) continue;
454
455 unsigned int Length = ntohs(Header->package_length)*2*sizeof(char);
456 if (Pos < Length) continue;
457
458 // Extract data if event end package flag correct
459 if (ntohs(*(unsigned short *) (Buffer+Length-sizeof(unsigned short))) == 0x04FE) {
460
461 // Prepare pointers to channel data (channels stored in order 0,9,18,27 - 1,10,19,28 - ... - 8,17,26,35)
462 PCHANNEL *Channel[NChips*NChannels], *Pnt=(PCHANNEL *) (Header+1);
463 for(unsigned int i=0; i<NChips*NChannels; i++) {
464 Channel[i] = Pnt;
465 Pnt = (PCHANNEL *) ((short *) (Channel[i] + 1) + ntohs(Channel[i]->roi));
466 }
467
468 // Wait until event thread processed the previous data and lock to avoid concurrent access in GetStatus()
469 Lock();
470 while (!Continue) {
471 struct timespec Wakeup;
472 Wakeup.tv_sec = time(NULL)+MAX_WAIT_FOR_CONDITION;
473 Wakeup.tv_nsec = 0;
474 if ((Ret = pthread_cond_timedwait(&CondVar, &Mutex, &Wakeup)) != 0) {
475 if (Ret == ETIMEDOUT) SetStatus("Board %s timed out (%d s) waiting for condition\n", Name, MAX_WAIT_FOR_CONDITION);
476 else m->Message(m->ERROR, "pthread_cond_wait() failed (%s)", strerror(Ret));
477 }
478 }
479 gettimeofday(&Status.Update, NULL);
480
481 // Extract board and trigger information
482 Status.BoardID = ntohs(Header->board_id);
483 Status.FirmwareRevision = ntohs(Header->version_no);
484 Status.BoardTime = ntohl(Header->time);
485 Status.EventCounter = ntohl(Header->fad_evt_counter);
486 Status.TriggerNum = ntohl(Header->trigger_id);
487 Status.Runnumber = ntohl(Header->runnumber);
488 Status.TriggerType = ntohs(Header->trigger_type);
489 Status.TriggerCRC = ntohs(Header->trigger_crc);
490 Status.DNA = Header->DNA;
491
492 // Extract frequency related information
493 Status.Frequency = ntohl(Header->REFCLK_frequency)/1.0e3*2.048;
494 Status.PhaseShift = Header->adc_clock_phase_shift;
495 for (unsigned int i=0; i<NChips; i++) {
496 if ((ntohs(Header->PLLLCK)>>12 & (1<<i)) != 0) Status.Lock[i] = true;
497 else Status.Lock[i] = false;
498 }
499
500 // Extract Firmware status info
501 Status.denable = (bool) ( ntohs(Header->PLLLCK) & (1<<11) );
502 Status.dwrite = (bool) ( ntohs(Header->PLLLCK) & (1<<10) );
503 Status.DCM_lock = (bool) ( ntohs(Header->PLLLCK) & (1<<7) );
504 Status.DCM_ready = (bool) ( ntohs(Header->PLLLCK) & (1<<6) );
505 Status.spi_clk = (bool) ( ntohs(Header->PLLLCK) & (1<<5) );
506 Status.RefClk_low = (bool) ( ntohs(Header->PLLLCK) & (1<<8) );
507
508 // Extract temperatures (MSB indicates if temperature is positive or negative)
509 for (unsigned int i=0; i<NTemp; i++) {
510 if ((ntohs(Header->drs_temperature[i]) & 0x8000) == 0) Status.Temp[i] = float(ntohs(Header->drs_temperature[i]) >> 3)/16;
511 else Status.Temp[i] = float(0xE000 | (ntohs(Header->drs_temperature[i])) >> 3)/16;
512 }
513
514 // Extract DAC channels
515 for (unsigned int i=0; i<NDAC; i++) Status.DAC[i] = ntohs(Header->dac[i]);
516
517 short Buf;
518 for (unsigned int Chip=0; Chip<NChips; Chip++) {
519 // Extract trigger cells
520 Status.TriggerCell[Chip] = (int) ntohs(Channel[Chip]->start_cell);
521
522 for (unsigned int Chan=0; Chan<NChannels; Chan++) {
523 // Extract ROI
524 Status.ROI[Chip][Chan] = ntohs(Channel[Chip+NChips*Chan]->roi);
525
526 // Extract ADC data (stored in 12 bit signed twis complement with out-of-range-bit and leading zeroes)
527 for (int i=0; i<Status.ROI[Chip][Chan]; i++) {
528 Buf = (Channel[Chip+NChips*Chan]->adc_data[i]);
529 (Buf <<= 4) >>= 4; //delete the sign-bit by shifting left and shift back
530 Data[Chip][Chan][i] = Buf;
531 }
532 }
533 }
534
535 // Prepare predicate for condition variable
536 Continue = false;
537 Count++;
538 Unlock();
539
540 // Amplitude calibration (will check if Mode is acalib)
541 AmplitudeCalibration();
542
543 // Update DIM services if necessary
544 if (Status.Update.tv_sec - PrevStatus.Update.tv_sec > m->EventUpdateDelay) {
545
546 // Determine event rate
547 Status.Rate =
548 Count / (double(Status.Update.tv_sec-PrevStatus.Update.tv_sec) + (Status.Update.tv_usec-PrevStatus.Update.tv_usec)/1000000.0);
549 Count = 0;
550
551 if (PrevStatus.Frequency != Status.Frequency) DIM_Frequency->updateService();
552 if (PrevStatus.TriggerNum != Status.TriggerNum) DIM_TriggerNum->updateService();
553 if (PrevStatus.Rate != Status.Rate) DIM_Rate->updateService();
554
555 if (memcmp(PrevStatus.Temp, Status.Temp, sizeof(Status.Temp)) != 0) {
556 DIM_Temp->updateService(Status.Temp, sizeof(Status.Temp));
557 }
558 if (memcmp(PrevStatus.DAC, Status.DAC, sizeof(Status.DAC)) != 0) {
559 DIM_DAC->updateService(Status.DAC, sizeof(Status.DAC));
560 }
561 if (memcmp(PrevStatus.ROI, Status.ROI, sizeof(Status.ROI)) != 0) {
562 DIM_ROI->updateService(Status.ROI, sizeof(Status.ROI));
563 }
564 if (PrevStatus.BoardID != Status.BoardID) {
565 DIM_ID->updateService(&Status.BoardID, sizeof(Status.BoardID));
566 }
567
568 PrevStatus = Status;
569 }
570
571 // Inform event thread of new data
572 string Message = string("EVENT")+Name+"\n";
573 if (write(m->Pipe[1], Message.data(), Message.size()) == -1) {
574 m->Message(m->ERROR, "write() to Pipe[1] failed in class FADBoard (%s)", strerror(errno));
575 break;
576 }
577 }
578 else SetStatus("End package flag incorrect, removing corrupt event");
579
580 // Remove event data from internal buffer
581 memmove(Buffer, Buffer+Length, Pos-Length);
582 Pos = Pos-Length;
583 } // while()
584
585 // Set inactive and close socket descriptor
586 Active = false;
587
588 if (close(Socket) == -1) {
589 m->Message(m->ERROR, "Could not close socket descriptor for board %s (%s)", Name, strerror(errno));
590 }
591
592}
593
594//
595// Install cleanup handler and launch read thread inside class
596//
597void FADBoard::LaunchThread(class FADBoard *m) {
598
599 pthread_cleanup_push((void (*)(void *)) FADBoard::ThreadCleanup, (void *) m);
600 m->ReadLoop();
601 pthread_cleanup_pop(0);
602}
603
604
605//
606// Set status message
607//
608void FADBoard::SetStatus(const char *Format, ...) {
609
610 int Ret;
611
612 // Assemble message
613 va_list ArgumentPointer;
614 va_start(ArgumentPointer, Format);
615 Lock();
616 Ret = vsnprintf(Status.Message, sizeof(Status.Message), Format, ArgumentPointer);
617 Unlock();
618 va_end(ArgumentPointer);
619
620 if (Ret == -1) m->Message(m->FATAL, "snprintf() in FADBoard::SetStatus() failed (%s)", strerror(errno));
621
622 // Update status service
623 DIM_Status->updateService(Status.Message);
624}
625
626
627//
628// Lock and unlock mutex
629//
630void FADBoard::Lock() {
631
632 int Ret;
633
634 if ((Ret = pthread_mutex_lock(&Mutex)) != 0) {
635 m->Message(m->FATAL, "pthread_mutex_lock() failed in class FADBoard (%s)", strerror(Ret));
636 }
637}
638
639void FADBoard::Unlock() {
640
641 int Ret;
642
643 if ((Ret = pthread_mutex_unlock(&Mutex)) != 0) {
644 m->Message(m->FATAL, "pthread_mutex_unlock() failed in class FADBoard (%s)", strerror(Ret));
645 }
646}
647
648// Ensure that mutex is unlocked when before cancelling thread
649void FADBoard::ThreadCleanup(class FADBoard *This) {
650
651 int Ret;
652
653 if ((Ret = pthread_mutex_trylock(&This->Mutex)) != 0) {
654 if (Ret != EBUSY) This->m->Message(This->m->FATAL, "pthread_mutex_trylock() failed in FADBoard::ThreadCleanup (%s)", strerror(Ret));
655 }
656 This->Unlock();
657}
658
659//
660// Open other sockets
661//
662// Error reporting is limited as this function is expected to be removed when firmware allows single socket
663//
664void FADBoard::threadHandler() {
665
666 int List[] = {5001, 5002, 5003, 5004, 5005, 5006, 5007};
667 int Socket[sizeof(List)/sizeof(int)], MaxSocketNum, Ret;
668 fd_set DescriptorList;
669 char Buffer[1000000];
670
671 // Resolve hostname
672 struct hostent *Host = gethostbyname(Name);
673 if (Host == 0) return;
674
675 // Connect to server
676 struct sockaddr_in SocketAddress;
677 SocketAddress.sin_family = PF_INET;
678 SocketAddress.sin_addr = *(struct in_addr*) Host->h_addr;
679
680 for (unsigned int i=0; i<sizeof(List)/sizeof(int); i++) {
681 // Open socket descriptor
682 if ((Socket[i] = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
683 m->Message(m->ERROR, "OtherSockets: Could not open socket for port %d (%s)\n", List[i], strerror(errno));
684 return;
685 }
686 MaxSocketNum = *max_element(Socket, Socket+sizeof(List)/sizeof(int));
687
688 // Connect to server
689 SocketAddress.sin_port = htons((unsigned short) List[i]);
690 if (connect(Socket[i], (struct sockaddr *) &SocketAddress, sizeof(SocketAddress)) == -1) return;
691 }
692
693 while(true) {
694 // Wait for data from sockets
695 FD_ZERO(&DescriptorList);
696 for (unsigned int i=0; i<sizeof(List)/sizeof(int); i++) FD_SET(Socket[i], &DescriptorList);
697 if (select(MaxSocketNum+1, &DescriptorList, NULL, NULL, NULL) == -1) {
698 m->Message(m->ERROR, "OtherSockets: Error with select() (%s)\n", strerror(errno));
699 break;
700 }
701
702 // Data from socket
703 for (unsigned int i=0; i<sizeof(List)/sizeof(int); i++) if (FD_ISSET(Socket[i], &DescriptorList)) {
704 Ret = read(Socket[i], Buffer, sizeof(Buffer));
705 if (Ret == -1) m->Message(m->ERROR, "OtherSockets: Error reading from port %d (%s)\n", List[i], strerror(errno));
706 }
707 }
708
709 // Close all sockets
710 for (unsigned int i=0; i<sizeof(List)/sizeof(int); i++) {
711 if ((Socket[i] != -1) && (close(Socket[i]) == -1)) {
712 m->Message(m->ERROR, "OtherSockets: Could not close socket of port %d (%s)", List[i], strerror(errno));
713 }
714 }
715}
Note: See TracBrowser for help on using the repository browser.