source: fact/FADctrl/FADBoard.cc@ 10788

Last change on this file since 10788 was 10757, checked in by ogrimm, 14 years ago
Added thread cancellation handler to ensure mutex gets unlocked
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};
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 Send(CMD_TRIGGERS_OFF);
186 usleep(500000);
187
188 for (unsigned int i=0; i<NChips*NChannels; i++) {
189 ROICmd.push_back(htons(CMD_Write | (BADDR_ROI + i)));
190 ROICmd.push_back(htons(NBins));
191 }
192 Send(&ROICmd[0], ROICmd.size()*sizeof(unsigned short));
193
194 DACCmd[1] = htons(0);
195 DACCmd[3] = htons(0);
196 DACCmd[5] = htons(0);
197 Send(DACCmd, sizeof(DACCmd));
198
199 Send(CMD_TRIGGERS_ON);
200
201 // Clear sum vector and set state to accumulate
202 memset(Sum, 0, sizeof(Sum));
203 State = baseline;
204 SetStatus("Starting calilbration");
205 break;
206
207 // ====== Part B: Baseline calibration =====
208 case baseline:
209 // Check for stopping
210 if (m->Mode != m->acalib) {
211 State = cleanup;
212 break;
213 }
214
215 // Average
216 for (unsigned int Chip=0; Chip<NChips; Chip++) {
217 for (unsigned int Chan=0; Chan<NChannels; Chan++) {
218 for (int i=0; i<Status.ROI[Chip][Chan]; i++) {
219 Sum[Chip][Chan][(i+Status.TriggerCell[Chip]) % NBins] += Data[Chip][Chan][i];
220 }
221 }
222 }
223 Count++;
224
225 // Determine baseline if integration finished
226 if (Count < m->NumEventsRequested) break;
227
228 for (unsigned int i=0; i<NChips; i++) {
229 for (unsigned int j=0; j<NChannels; j++) {
230 for (unsigned int k=0; k<NBins; k++) {
231 ACalib.Baseline[i][j][k] = Sum[i][j][k] / m->NumEventsRequested;
232 }
233 }
234 }
235
236 // Set new DAC values and start accumulation
237 DACCmd[1] = htons(50000);
238 DACCmd[3] = htons(50000);
239 DACCmd[5] = htons(50000);
240 Send(DACCmd, sizeof(DACCmd));
241
242 // Clear sum vector and set state to accumulate
243 memset(Sum, 0, sizeof(Sum));
244 Count = 0;
245 State = gain;
246 break;
247
248 // ====== Part C: Gain calibration =====
249 case gain:
250 // Check for stopping
251 if (m->Mode != m->acalib) {
252 State = cleanup;
253 break;
254 }
255
256 // Average
257 for (unsigned int Chip=0; Chip<NChips; Chip++) {
258 for (unsigned int Chan=0; Chan<NChannels; Chan++) {
259 for (int i=0; i<Status.ROI[Chip][Chan]; i++) {
260 Sum[Chip][Chan][(i+Status.TriggerCell[Chip]) % NBins] += Data[Chip][Chan][i];
261 }
262 }
263 }
264 Count++;
265
266 // Determine gain if integration finished
267 if (Count < m->NumEventsRequested) break;
268
269 for (unsigned int i=0; i<NChips; i++) {
270 for (unsigned int j=0; j<NChannels; j++) {
271 for (unsigned int k=0; k<NBins; k++) {
272 ACalib.Gain[i][j][k] = (Sum[i][j][k] / m->NumEventsRequested) - ACalib.Baseline[i][j][k];
273 }
274 }
275 }
276
277 // Set new DAC values and start accumulation
278 DACCmd[1] = htons(0);
279 DACCmd[3] = htons(0);
280 DACCmd[5] = htons(0);
281 Send(DACCmd, sizeof(DACCmd));
282
283 // Clear sum vector and set state to accumulate
284 memset(Sum, 0, sizeof(Sum));
285 Count = 0;
286 State = secondary;
287 break;
288
289 // ====== Part D: Secondary calibration =====
290 case secondary:
291 // Check for stopping
292 if (m->Mode != m->acalib) {
293 State = cleanup;
294 break;
295 }
296
297 // Average
298 for (unsigned int Chip=0; Chip<NChips; Chip++) {
299 for (unsigned int Chan=0; Chan<NChannels; Chan++) {
300 for (int i=0; i<Status.ROI[Chip][Chan]; i++) {
301 Sum[Chip][Chan][i] = Data[Chip][Chan][i] - ACalib.Baseline[Chip][Chan][(i-Status.TriggerCell[Chip]) % NBins];
302 }
303 }
304 }
305 Count++;
306
307 // Determine secondary baseline if integration finished
308 if (Count < m->NumEventsRequested) break;
309
310 for (unsigned int i=0; i<NChips; i++) {
311 for (unsigned int j=0; j<NChannels; j++) {
312 for (unsigned int k=0; k<NBins; k++) {
313 ACalib.Secondary[i][j][k] = Sum[i][j][k] / (double) m->NumEventsRequested;
314 }
315 }
316 }
317
318 // Store calibration time and temperature
319 ACalib.DNA = Status.DNA;
320 ACalib.Frequency = Status.Frequency;
321 ACalib.Time = time(NULL);
322 ACalib.Temp = 0;
323 for (unsigned int i=0; i<NTemp; i++) ACalib.Temp += Status.Temp[i] / NTemp;
324
325 // Inform event thread that calibration is finished for this board
326 if (write(m->Pipe[1], Message.data(), Message.size()) == -1) {
327 m->Message(m->ERROR, "write() to Pipe[1] failed in class FADBoard::AmplitudeCalibration (%s)", strerror(errno));
328 }
329
330 SetStatus("Finished calibration");
331 State = cleanup;
332 break;
333
334 // ====== Part E: Write back original ROI and DAC settings =====
335 case cleanup:
336 // ROI values
337 Send(CMD_TRIGGERS_OFF);
338 usleep(100000);
339
340 ROICmd.clear();
341 for (unsigned int i=0; i<NChips*NChannels; i++) {
342 ROICmd.push_back(htons(CMD_Write | (BADDR_ROI + i)));
343 ROICmd.push_back(htons(InitialStatus.ROI[i/NChannels][i%NChannels]));
344 }
345 Send(&ROICmd[0], ROICmd.size()*sizeof(unsigned short));
346
347 Send(CMD_TRIGGERS_ON);
348
349 // DAC values
350 DACCmd[1] = htons(InitialStatus.DAC[1]);
351 DACCmd[3] = htons(InitialStatus.DAC[2]);
352 DACCmd[5] = htons(InitialStatus.DAC[3]);
353 Send(DACCmd, sizeof(DACCmd));
354
355 // Update DIM service with calibration information
356 for (unsigned int i=0; i<NChips; i++) {
357 for (unsigned int j=0; j<NChannels; j++) {
358 for (unsigned int k=0; k<NBins; k++) {
359 ACalData[0][i][j][k] = ACalib.Baseline[i][j][k];
360 ACalData[1][i][j][k] = ACalib.Gain[i][j][k];
361 ACalData[2][i][j][k] = ACalib.Secondary[i][j][k];
362 }
363 }
364 }
365 DIM_ACalData->updateService(ACalData, 3*NChips*NChannels*NBins*sizeof(float));
366
367 State = wait;
368 break;
369
370 // ====== Wait for Mode not being idle =====
371 case wait:
372 if (m->Mode == m->idle) State = standbye;
373 break;
374 }
375}
376
377//
378// Connect to board and read data
379//
380void FADBoard::ReadLoop() {
381
382 char Buffer[READ_BUFFER_SIZE];
383 unsigned int Pos = 0, Count = 0;
384 const PEVNT_HEADER *Header = (PEVNT_HEADER *) Buffer;
385 ssize_t Result;
386 struct sockaddr_in SocketAddress;
387 struct BoardStatus PrevStatus;
388 int Ret;
389
390 // Resolve hostname
391 struct hostent *Host = gethostbyname(Name);
392 if (Host == 0) {
393 SetStatus("Could not resolve host name '%s'", Name);
394 return;
395 }
396
397 SocketAddress.sin_family = PF_INET;
398 SocketAddress.sin_port = htons(Port);
399 SocketAddress.sin_addr = *(struct in_addr*) Host->h_addr;
400
401 // Open socket descriptor
402 if ((Socket = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
403 m->Message(m->ERROR, "Could not open socket for %s (%s)\n", Name, strerror(errno));
404 return;
405 }
406
407 // Connect to server
408 if (connect(Socket, (struct sockaddr *) &SocketAddress, sizeof(SocketAddress)) == -1) {
409 SetStatus("Could not connect to port %hu (%s)", Port, strerror(errno));
410 }
411 else {
412 CommOK = true;
413 Active = true;
414 SetStatus("Connected");
415 }
416
417 memset(&PrevStatus, 0, sizeof(PrevStatus));
418
419 // Leave loop if program termination requested or board communication not OK
420 while (!m->ExitRequest && CommOK) {
421 // Read data from socket
422 Result = read(Socket, Buffer + Pos, sizeof(Buffer)-Pos);
423
424 // Check result of read
425 if (Result == -1) {
426 m->Message(m->ERROR, "Could not read from socket for %s, exiting read loop (%s)\n", Name, strerror(errno));
427 CommOK = false;
428 break;
429 }
430 else if (Result == 0) {
431 SetStatus("Server not existing anymore, exiting read loop");
432 CommOK = false;
433 break;
434 }
435
436 // If not active, discard incoming data
437 if (!Active) continue;
438
439 // Advance write pointer
440 Pos += Result;
441
442 // Check if internal buffer full
443 if (Pos == sizeof(Buffer)) {
444 SetStatus("Internal buffer full, deleting all data in buffer");
445 Pos = 0;
446 continue;
447 }
448
449 // Check if buffer starts with start_package_flag, remove data if not
450 unsigned int Temp = 0;
451 while (ntohs(*((unsigned short *) (Buffer+Temp))) != 0xfb01 && Temp<Pos) Temp++;
452 if (Temp != 0) {
453 memmove(Buffer, Buffer+Temp, Pos-Temp);
454 Pos -= Temp;
455 SetStatus("Removed %d bytes because of start_package_flag not found", Temp);
456 continue;
457 }
458
459 // Wait until the buffer contains at least enough bytes to potentially hold a PEVNT_HEADER
460 if (Pos < sizeof(PEVNT_HEADER)) continue;
461
462 unsigned int Length = ntohs(Header->package_length)*2*sizeof(char);
463 if (Pos < Length) continue;
464
465 // Extract data if event end package flag correct
466 if (ntohs(*(unsigned short *) (Buffer+Length-sizeof(unsigned short))) == 0x04FE) {
467
468 // Prepare pointers to channel data (channels stored in order 0,9,18,27 - 1,10,19,28 - ... - 8,17,26,35)
469 PCHANNEL *Channel[NChips*NChannels], *Pnt=(PCHANNEL *) (Header+1);
470 for(unsigned int i=0; i<NChips*NChannels; i++) {
471 Channel[i] = Pnt;
472 Pnt = (PCHANNEL *) ((short *) (Channel[i] + 1) + ntohs(Channel[i]->roi));
473 }
474
475 // Wait until event thread processed the previous data and lock to avoid concurrent access in GetStatus()
476 Lock();
477 while (!Continue) {
478 struct timespec Wakeup;
479 Wakeup.tv_sec = time(NULL)+5;
480 Wakeup.tv_nsec = 0;
481 if ((Ret = pthread_cond_timedwait(&CondVar, &Mutex, &Wakeup)) != 0) {
482 if (Ret == ETIMEDOUT) printf("Board %s timed out (5 s) waiting for condition\n", Name);
483 else m->Message(m->ERROR, "pthread_cond_wait() failed (%s)", strerror(Ret));
484 }
485 }
486 gettimeofday(&Status.Update, NULL);
487
488 // Extract board and trigger information
489 Status.BoardID = ntohs(Header->board_id);
490 Status.FirmwareRevision = ntohs(Header->version_no);
491 Status.BoardTime = ntohl(Header->time);
492 Status.EventCounter = ntohl(Header->fad_evt_counter);
493 Status.TriggerNum = ntohl(Header->trigger_id);
494 Status.Runnumber = ntohl(Header->runnumber);
495 Status.TriggerType = ntohs(Header->trigger_type);
496 Status.TriggerCRC = ntohs(Header->trigger_crc);
497 Status.DNA = Header->DNA;
498
499 // Extract frequency related information
500 Status.Frequency = ntohl(Header->REFCLK_frequency)/1.0e3*2.048;
501 Status.PhaseShift = Header->adc_clock_phase_shift;
502 for (unsigned int i=0; i<NChips; i++) {
503 if ((ntohs(Header->PLLLCK)>>12 & (1<<i)) != 0) Status.Lock[i] = true;
504 else Status.Lock[i] = false;
505 }
506
507 // Extract Firmware status info
508 Status.denable = (bool) ( ntohs(Header->PLLLCK) & (1<<11) );
509 Status.dwrite = (bool) ( ntohs(Header->PLLLCK) & (1<<10) );
510 Status.DCM_lock = (bool) ( ntohs(Header->PLLLCK) & (1<<9) );
511 Status.DCM_ready = (bool) ( ntohs(Header->PLLLCK) & (1<<8) );
512 Status.spi_clk = (bool) ( ntohs(Header->PLLLCK) & (1<<7) );
513
514 // Extract temperatures (MSB indicates if temperature is positive or negative)
515 for (unsigned int i=0; i<NTemp; i++) {
516 if ((ntohs(Header->drs_temperature[i]) & 0x8000) == 0) Status.Temp[i] = float(ntohs(Header->drs_temperature[i]) >> 3)/16;
517 else Status.Temp[i] = float(0xE000 | (ntohs(Header->drs_temperature[i])) >> 3)/16;
518 }
519
520 // Extract DAC channels
521 for (unsigned int i=0; i<NDAC; i++) Status.DAC[i] = ntohs(Header->dac[i]);
522
523 short Buf;
524 for (unsigned int Chip=0; Chip<NChips; Chip++) {
525 // Extract trigger cells
526 Status.TriggerCell[Chip] = (int) ntohs(Channel[Chip]->start_cell);
527
528 for (unsigned int Chan=0; Chan<NChannels; Chan++) {
529 // Extract ROI
530 Status.ROI[Chip][Chan] = ntohs(Channel[Chip+NChips*Chan]->roi);
531
532 // Extract ADC data (stored in 12 bit signed twis complement with out-of-range-bit and leading zeroes)
533 for (int i=0; i<Status.ROI[Chip][Chan]; i++) {
534 Buf = (Channel[Chip+NChips*Chan]->adc_data[i]);
535 (Buf <<= 4) >>= 4; //delete the sign-bit by shifting left and shift back
536 Data[Chip][Chan][i] = Buf;
537 }
538 }
539 }
540
541 // Prepare predicate for condition variable
542 Continue = false;
543 Count++;
544 Unlock();
545
546 // Amplitude calibration (will check if Mode is acalib)
547 AmplitudeCalibration();
548
549 // Update DIM services if necessary
550 if (Status.Update.tv_sec - PrevStatus.Update.tv_sec > m->EventUpdateDelay) {
551
552 // Determine event rate
553 Status.Rate =
554 Count / (double(Status.Update.tv_sec-PrevStatus.Update.tv_sec) + (Status.Update.tv_usec-PrevStatus.Update.tv_usec)/1000000.0);
555 Count = 0;
556
557 if (PrevStatus.Frequency != Status.Frequency) DIM_Frequency->updateService();
558 if (PrevStatus.TriggerNum != Status.TriggerNum) DIM_TriggerNum->updateService();
559 if (PrevStatus.Rate != Status.Rate) DIM_Rate->updateService();
560
561 if (memcmp(PrevStatus.Temp, Status.Temp, sizeof(Status.Temp)) != 0) {
562 DIM_Temp->updateService(Status.Temp, sizeof(Status.Temp));
563 }
564 if (memcmp(PrevStatus.DAC, Status.DAC, sizeof(Status.DAC)) != 0) {
565 DIM_DAC->updateService(Status.DAC, sizeof(Status.DAC));
566 }
567 if (memcmp(PrevStatus.ROI, Status.ROI, sizeof(Status.ROI)) != 0) {
568 DIM_ROI->updateService(Status.ROI, sizeof(Status.ROI));
569 }
570 if (PrevStatus.BoardID != Status.BoardID) {
571 DIM_ID->updateService(&Status.BoardID, sizeof(Status.BoardID));
572 }
573
574 PrevStatus = Status;
575 }
576
577 // Inform event thread of new data
578 string Message = string("EVENT")+Name+"\n";
579 if (write(m->Pipe[1], Message.data(), Message.size()) == -1) {
580 m->Message(m->ERROR, "write() to Pipe[1] failed in class FADBoard (%s)", strerror(errno));
581 break;
582 }
583 }
584 else SetStatus("End package flag incorrect, removing corrupt event");
585
586 // Remove event data from internal buffer
587 memmove(Buffer, Buffer+Length, Pos-Length);
588 Pos = Pos-Length;
589 } // while()
590
591 // Set inactive and close socket descriptor
592 Active = false;
593
594 if (close(Socket) == -1) {
595 m->Message(m->ERROR, "Could not close socket descriptor for board %s (%s)", Name, strerror(errno));
596 }
597
598}
599
600//
601// Install cleanup handler and launch read thread inside class
602//
603void FADBoard::LaunchThread(class FADBoard *m) {
604
605 pthread_cleanup_push((void (*)(void *)) FADBoard::ThreadCleanup, (void *) m);
606 m->ReadLoop();
607 pthread_cleanup_pop(0);
608}
609
610
611//
612// Set status message
613//
614void FADBoard::SetStatus(const char *Format, ...) {
615
616 int Ret;
617
618 // Assemble message
619 va_list ArgumentPointer;
620 va_start(ArgumentPointer, Format);
621 Lock();
622 Ret = vsnprintf(Status.Message, sizeof(Status.Message), Format, ArgumentPointer);
623 Unlock();
624 va_end(ArgumentPointer);
625
626 if (Ret == -1) m->Message(m->FATAL, "snprintf() in FADBoard::SetStatus() failed (%s)", strerror(errno));
627
628 // Update status service
629 DIM_Status->updateService(Status.Message);
630}
631
632
633//
634// Lock and unlock mutex
635//
636void FADBoard::Lock() {
637
638 int Ret;
639
640 if ((Ret = pthread_mutex_lock(&Mutex)) != 0) {
641 m->Message(m->FATAL, "pthread_mutex_lock() failed in class FADBoard (%s)", strerror(Ret));
642 }
643}
644
645void FADBoard::Unlock() {
646
647 int Ret;
648
649 if ((Ret = pthread_mutex_unlock(&Mutex)) != 0) {
650 m->Message(m->FATAL, "pthread_mutex_unlock() failed in class FADBoard (%s)", strerror(Ret));
651 }
652}
653
654// Ensure that mutex is unlocked when before cancelling thread
655void FADBoard::ThreadCleanup(class FADBoard *This) {
656
657 int Ret;
658
659 if ((Ret = pthread_mutex_trylock(&This->Mutex)) != 0) {
660 if (Ret != EBUSY) This->m->Message(This->m->FATAL, "pthread_mutex_trylock() failed in FADBoard::ThreadCleanup (%s)", strerror(Ret));
661 }
662 This->Unlock();
663}
664
665//
666// Open other sockets
667//
668// Error reporting is limited as this function is expected to be removed when firmware allows single socket
669//
670void FADBoard::threadHandler() {
671
672 int List[] = {5001, 5002, 5003, 5004, 5005, 5006, 5007};
673 int Socket[sizeof(List)/sizeof(int)], MaxSocketNum, Ret;
674 fd_set DescriptorList;
675 char Buffer[1000000];
676
677 // Resolve hostname
678 struct hostent *Host = gethostbyname(Name);
679 if (Host == 0) return;
680
681 // Connect to server
682 struct sockaddr_in SocketAddress;
683 SocketAddress.sin_family = PF_INET;
684 SocketAddress.sin_addr = *(struct in_addr*) Host->h_addr;
685
686 for (unsigned int i=0; i<sizeof(List)/sizeof(int); i++) {
687 // Open socket descriptor
688 if ((Socket[i] = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
689 m->Message(m->ERROR, "OtherSockets: Could not open socket for port %d (%s)\n", List[i], strerror(errno));
690 return;
691 }
692 MaxSocketNum = *max_element(Socket, Socket+sizeof(List)/sizeof(int));
693
694 // Connect to server
695 SocketAddress.sin_port = htons((unsigned short) List[i]);
696 if (connect(Socket[i], (struct sockaddr *) &SocketAddress, sizeof(SocketAddress)) == -1) return;
697 }
698
699 while(true) {
700 // Wait for data from sockets
701 FD_ZERO(&DescriptorList);
702 for (unsigned int i=0; i<sizeof(List)/sizeof(int); i++) FD_SET(Socket[i], &DescriptorList);
703 if (select(MaxSocketNum+1, &DescriptorList, NULL, NULL, NULL) == -1) {
704 m->Message(m->ERROR, "OtherSockets: Error with select() (%s)\n", strerror(errno));
705 break;
706 }
707
708 // Data from socket
709 for (unsigned int i=0; i<sizeof(List)/sizeof(int); i++) if (FD_ISSET(Socket[i], &DescriptorList)) {
710 Ret = read(Socket[i], Buffer, sizeof(Buffer));
711 if (Ret == -1) m->Message(m->ERROR, "OtherSockets: Error reading from port %d (%s)\n", List[i], strerror(errno));
712 }
713 }
714
715 // Close all sockets
716 for (unsigned int i=0; i<sizeof(List)/sizeof(int); i++) {
717 if ((Socket[i] != -1) && (close(Socket[i]) == -1)) {
718 m->Message(m->ERROR, "OtherSockets: Could not close socket of port %d (%s)", List[i], strerror(errno));
719 }
720 }
721}
Note: See TracBrowser for help on using the repository browser.