source: fact/FADctrl/FADBoard.cc@ 10719

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