source: trunk/FACT++/src/EventBuilder.cc@ 16620

Last change on this file since 16620 was 16619, checked in by tbretz, 12 years ago
The incompolete event timeout can now be set as configuration value
File size: 44.0 KB
Line 
1#include <poll.h>
2#include <sys/time.h>
3#include <sys/epoll.h>
4#include <netinet/tcp.h>
5
6#include <cstring>
7#include <cstdarg>
8#include <list>
9#include <queue>
10
11#include <boost/algorithm/string/join.hpp>
12
13#include "queue.h"
14
15#include "MessageImp.h"
16#include "EventBuilder.h"
17
18using namespace std;
19
20#define MIN_LEN 32 // min #bytes needed to interpret FADheader
21#define MAX_LEN 81920 // one max evt = 1024*2*36 + 8*36 + 72 + 4 = 74092 (data+boardheader+eventheader+endflag)
22
23//#define COMPLETE_EVENTS
24//#define USE_POLL
25//#define USE_EPOLL
26//#define USE_SELECT
27//#define COMPLETE_EPOLL
28//#define PRIORITY_QUEUE
29
30// Reading only 1024: 13: 77Hz, 87%
31// Reading only 1024: 12: 78Hz, 46%
32// Reading only 300: 4: 250Hz, 92%
33// Reading only 300: 3: 258Hz, 40%
34
35// Reading only four threads 1024: 13: 77Hz, 60%
36// Reading only four threads 1024: 12: 78Hz, 46%
37// Reading only four threads 300: 4: 250Hz, 92%
38// Reading only four threads 300: 3: 258Hz, 40%
39
40// Default 300: 4: 249Hz, 92%
41// Default 300: 3: 261Hz, 40%
42// Default 1024: 13: 76Hz, 93%
43// Default 1024: 12: 79Hz, 46%
44
45// Poll [selected] 1024: 13: 63Hz, 45%
46// Poll [selected] 1024: 14: 63Hz, 63%
47// Poll [selected] 1024: 15: 64Hz, 80%
48// Poll [selected] 300: 4: 230Hz, 47%
49// Poll [selected] 300: 3: 200Hz, 94%
50
51// Poll [all] 1024: 13: 65Hz, 47%
52// Poll [all] 1024: 14: 64Hz, 59%
53// Poll [all] 1024: 15: 62Hz, 67%
54// Poll [all] 300: 4: 230Hz, 47%
55// Poll [all] 300: 3: 230Hz, 35%
56
57// ==========================================================================
58
59bool runOpen(const EVT_CTRL2 &evt);
60bool runWrite(const EVT_CTRL2 &evt);
61void runClose(RUN_CTRL2 &run);
62void applyCalib(const EVT_CTRL2 &evt, const size_t &size);
63void factOut(int severity, const char *message);
64void factReportIncomplete (uint64_t rep);
65void gotNewRun(RUN_CTRL2 &run);
66void runFinished();
67void factStat(const GUI_STAT &gj);
68bool eventCheck(const EVT_CTRL2 &evt);
69void debugHead(void *buf);
70
71// ==========================================================================
72
73int g_reset;
74
75size_t g_maxMem; //maximum memory allowed for buffer
76
77uint16_t g_evtTimeout; // timeout (sec) for one event
78
79FACT_SOCK g_port[NBOARDS]; // .addr=string of IP-addr in dotted-decimal "ddd.ddd.ddd.ddd"
80
81uint gi_NumConnect[NBOARDS]; //4 crates * 10 boards
82
83GUI_STAT gj;
84
85// ==========================================================================
86
87namespace Memory
88{
89 uint64_t inuse = 0;
90 uint64_t allocated = 0;
91
92 uint64_t max_inuse = 0;
93
94 std::mutex mtx;
95
96 std::forward_list<void*> memory;
97
98 void *malloc()
99 {
100 // No free slot available, next alloc would exceed max memory
101 if (memory.empty() && allocated+MAX_TOT_MEM>g_maxMem)
102 return NULL;
103
104 // We will return this amount of memory
105 // This is not 100% thread safe, but it is not a super accurate measure anyway
106 inuse += MAX_TOT_MEM;
107 if (inuse>max_inuse)
108 max_inuse = inuse;
109
110 if (memory.empty())
111 {
112 // No free slot available, allocate a new one
113 allocated += MAX_TOT_MEM;
114 return new char[MAX_TOT_MEM];
115 }
116
117 // Get the next free slot from the stack and return it
118 const std::lock_guard<std::mutex> lock(mtx);
119
120 void *mem = memory.front();
121 memory.pop_front();
122 return mem;
123 };
124
125 void free(void *mem)
126 {
127 if (!mem)
128 return;
129
130 // Decrease the amont of memory in use accordingly
131 inuse -= MAX_TOT_MEM;
132
133 // If the maximum memory has changed, we might be over the limit.
134 // In this case: free a slot
135 if (allocated>g_maxMem)
136 {
137 delete [] (char*)mem;
138 allocated -= MAX_TOT_MEM;
139 return;
140 }
141
142 const std::lock_guard<std::mutex> lock(mtx);
143 memory.push_front(mem);
144 }
145
146};
147
148// ==========================================================================
149
150void factPrintf(int severity, const char *fmt, ...)
151{
152 char str[1000];
153
154 va_list ap;
155 va_start(ap, fmt);
156 vsnprintf(str, 1000, fmt, ap);
157 va_end(ap);
158
159 factOut(severity, str);
160}
161
162// ==========================================================================
163
164struct READ_STRUCT
165{
166 enum buftyp_t
167 {
168 kStream,
169 kHeader,
170 kData,
171#ifdef COMPLETE_EVENTS
172 kWait
173#endif
174 };
175
176 // ---------- connection ----------
177
178 static uint activeSockets;
179
180 int sockId; // socket id (board number)
181 int socket; // socket handle
182 bool connected; // is this socket connected?
183
184 struct sockaddr_in SockAddr; // Socket address copied from wrapper during socket creation
185
186 // ------------ epoll -------------
187
188 static int fd_epoll;
189 static epoll_event events[NBOARDS];
190
191 static void init();
192 static void close();
193 static int wait();
194 static READ_STRUCT *get(int i) { return reinterpret_cast<READ_STRUCT*>(events[i].data.ptr); }
195
196 // ------------ buffer ------------
197
198 buftyp_t bufTyp; // what are we reading at the moment: 0=header 1=data -1=skip ...
199
200 uint32_t bufLen; // number of bytes left to read
201 uint8_t *bufPos; // next byte to read to the buffer next
202
203 union
204 {
205 uint8_t B[MAX_LEN];
206 uint16_t S[MAX_LEN / 2];
207 uint32_t I[MAX_LEN / 4];
208 uint64_t L[MAX_LEN / 8];
209 PEVNT_HEADER H;
210 };
211
212 timeval time;
213 uint64_t totBytes; // total received bytes
214 uint64_t relBytes; // total released bytes
215 uint32_t skip; // number of bytes skipped before start of event
216
217 uint32_t len() const { return uint32_t(H.package_length)*2; }
218
219 void swapHeader();
220 void swapData();
221
222 // --------------------------------
223
224 READ_STRUCT() : socket(-1), connected(false), totBytes(0), relBytes(0)
225 {
226 if (fd_epoll<0)
227 init();
228 }
229 ~READ_STRUCT()
230 {
231 destroy();
232 }
233
234 void destroy();
235 bool create(sockaddr_in addr);
236 bool check(int, sockaddr_in addr);
237 bool read();
238
239};
240
241#ifdef PRIORITY_QUEUE
242struct READ_STRUCTcomp
243{
244 bool operator()(const READ_STRUCT *r1, const READ_STRUCT *r2)
245 {
246 const int64_t rel1 = r1->totBytes - r1->relBytes;
247 const int64_t rel2 = r2->totBytes - r2->relBytes;
248 return rel1 > rel2;
249 }
250};
251#endif
252
253int READ_STRUCT::wait()
254{
255 // wait for something to do...
256 const int rc = epoll_wait(fd_epoll, events, NBOARDS, 100); // max, timeout[ms]
257 if (rc>=0)
258 return rc;
259
260 if (errno==EINTR) // timout or signal interruption
261 return 0;
262
263 factPrintf(MessageImp::kError, "epoll_wait failed: %m (rc=%d)", errno);
264 return -1;
265}
266
267uint READ_STRUCT::activeSockets = 0;
268int READ_STRUCT::fd_epoll = -1;
269epoll_event READ_STRUCT::events[NBOARDS];
270
271void READ_STRUCT::init()
272{
273 if (fd_epoll>=0)
274 return;
275
276#ifdef USE_EPOLL
277 fd_epoll = epoll_create(NBOARDS);
278 if (fd_epoll<0)
279 {
280 factPrintf(MessageImp::kError, "Waiting for data failed: %d (epoll_create,rc=%d)", errno);
281 return;
282 }
283#endif
284}
285
286void READ_STRUCT::close()
287{
288#ifdef USE_EPOLL
289 if (fd_epoll>=0 && ::close(fd_epoll)>0)
290 factPrintf(MessageImp::kFatal, "Closing epoll failed: %m (close,rc=%d)", errno);
291#endif
292
293 fd_epoll = -1;
294}
295
296bool READ_STRUCT::create(sockaddr_in sockAddr)
297{
298 if (socket>=0)
299 return false;
300
301 const int port = ntohs(sockAddr.sin_port) + 1;
302
303 SockAddr.sin_family = sockAddr.sin_family;
304 SockAddr.sin_addr = sockAddr.sin_addr;
305 SockAddr.sin_port = htons(port);
306
307 if ((socket = ::socket(PF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0)) <= 0)
308 {
309 factPrintf(MessageImp::kFatal, "Generating socket %d failed: %m (socket,rc=%d)", sockId, errno);
310 socket = -1;
311 return false;
312 }
313
314 int optval = 1;
315 if (setsockopt (socket, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(int)) < 0)
316 factPrintf(MessageImp::kInfo, "Setting SO_KEEPALIVE for socket %d failed: %m (setsockopt,rc=%d)", sockId, errno);
317
318 optval = 10; //start after 10 seconds
319 if (setsockopt (socket, SOL_TCP, TCP_KEEPIDLE, &optval, sizeof(int)) < 0)
320 factPrintf(MessageImp::kInfo, "Setting TCP_KEEPIDLE for socket %d failed: %m (setsockopt,rc=%d)", sockId, errno);
321
322 optval = 10; //do every 10 seconds
323 if (setsockopt (socket, SOL_TCP, TCP_KEEPINTVL, &optval, sizeof(int)) < 0)
324 factPrintf(MessageImp::kInfo, "Setting TCP_KEEPINTVL for socket %d failed: %m (setsockopt,rc=%d)", sockId, errno);
325
326 optval = 2; //close after 2 unsuccessful tries
327 if (setsockopt (socket, SOL_TCP, TCP_KEEPCNT, &optval, sizeof(int)) < 0)
328 factPrintf(MessageImp::kInfo, "Setting TCP_KEEPCNT for socket %d failed: %m (setsockopt,rc=%d)", sockId, errno);
329
330 factPrintf(MessageImp::kInfo, "Generated socket %d (%d)", sockId, socket);
331
332 //connected = false;
333 activeSockets++;
334
335 return true;
336}
337
338void READ_STRUCT::destroy()
339{
340 if (socket<0)
341 return;
342
343#ifdef USE_EPOLL
344 // strictly speaking this should not be necessary
345 if (fd_epoll>=0 && connected && epoll_ctl(fd_epoll, EPOLL_CTL_DEL, socket, NULL)<0)
346 factPrintf(MessageImp::kError, "epoll_ctrl failed: %m (EPOLL_CTL_DEL,rc=%d)", errno);
347#endif
348
349 if (::close(socket) > 0)
350 factPrintf(MessageImp::kFatal, "Closing socket %d failed: %m (close,rc=%d)", sockId, errno);
351 else
352 factPrintf(MessageImp::kInfo, "Closed socket %d (%d)", sockId, socket);
353
354 socket = -1;
355 connected = false;
356 activeSockets--;
357}
358
359bool READ_STRUCT::check(int sockDef, sockaddr_in addr)
360{
361 // Continue in the most most likely case (performance)
362 //if (socket>=0 && sockDef!=0 && connected)
363 // return;
364 const int old = socket;
365
366 // socket open, but should not be open
367 if (socket>=0 && sockDef==0)
368 destroy();
369
370 // Socket closed, but should be open
371 if (socket<0 && sockDef!=0)
372 create(addr); //generate address and socket
373
374 const bool retval = old!=socket;
375
376 // Socket closed
377 if (socket<0)
378 return retval;
379
380 // Socket open and connected: Nothing to do
381 if (connected)
382 return retval;
383
384 //try to connect if not yet done
385 const int rc = connect(socket, (struct sockaddr *) &SockAddr, sizeof(SockAddr));
386 if (rc == -1)
387 return retval;
388
389 connected = true;
390
391 if (sockDef<0)
392 {
393 bufTyp = READ_STRUCT::kStream; // full data to be skipped
394 bufLen = MAX_LEN; // huge for skipping
395 }
396 else
397 {
398 bufTyp = READ_STRUCT::kHeader; // expect a header
399 bufLen = sizeof(PEVNT_HEADER); // max size to read at begining
400 }
401
402 bufPos = B; // no byte read so far
403 skip = 0; // start empty
404 totBytes = 0;
405 relBytes = 0;
406
407 factPrintf(MessageImp::kInfo, "Connected socket %d (%d)", sockId, socket);
408
409#ifdef USE_EPOLL
410 epoll_event ev;
411 ev.events = EPOLLIN;
412 ev.data.ptr = this; // user data (union: ev.ptr)
413 if (epoll_ctl(fd_epoll, EPOLL_CTL_ADD, socket, &ev)<0)
414 factPrintf(MessageImp::kError, "epoll_ctl failed: %m (EPOLL_CTL_ADD,rc=%d)", errno);
415#endif
416
417 return retval;
418}
419
420bool READ_STRUCT::read()
421{
422 if (!connected)
423 return false;
424
425 if (bufLen==0)
426 return true;
427
428 const int32_t jrd = recv(socket, bufPos, bufLen, MSG_DONTWAIT);
429 // recv failed
430 if (jrd<0)
431 {
432 // There was just nothing waiting
433 if (errno==EWOULDBLOCK || errno==EAGAIN)
434 return false;
435
436 factPrintf(MessageImp::kError, "Reading from socket %d failed: %m (recv,rc=%d)", sockId, errno);
437 return false;
438 }
439
440 // connection was closed ...
441 if (jrd==0)
442 {
443 factPrintf(MessageImp::kInfo, "Socket %d closed by FAD", sockId);
444
445 destroy();//DestroySocket(rd[i]); //generate address and socket
446 return false;
447 }
448
449 totBytes += jrd;
450
451 // are we skipping this board ...
452 if (bufTyp==kStream)
453 return false;
454
455 if (bufPos==B)
456 gettimeofday(&time, NULL);
457
458 bufPos += jrd; //==> prepare for continuation
459 bufLen -= jrd;
460
461 // not yet all read
462 return bufLen==0;
463}
464
465void READ_STRUCT::swapHeader()
466{
467 S[1] = ntohs(S[1]); // package_length (bytes not swapped!)
468 S[2] = ntohs(S[2]); // version_no
469 S[3] = ntohs(S[3]); // PLLLCK
470 S[4] = ntohs(S[4]); // trigger_crc
471 S[5] = ntohs(S[5]); // trigger_type
472
473 I[3] = ntohl(I[3]); // trigger_id
474 I[4] = ntohl(I[4]); // fad_evt_counter
475 I[5] = ntohl(I[5]); // REFCLK_frequency
476
477 S[12] = ntohs(S[12]); // board id
478 S[13] = ntohs(S[13]); // adc_clock_phase_shift
479 S[14] = ntohs(S[14]); // number_of_triggers_to_generate
480 S[15] = ntohs(S[15]); // trigger_generator_prescaler
481
482 I[10] = ntohl(I[10]); // runnumber;
483 I[11] = ntohl(I[11]); // time;
484
485 // Use back inserter??
486 for (int s=24; s<24+NTemp+NDAC; s++)
487 S[s] = ntohs(S[s]); // drs_temperature / dac
488}
489
490void READ_STRUCT::swapData()
491{
492 // swapEventHeaderBytes: End of the header. to channels now
493
494 int i = 36;
495 for (int ePatchesCount = 0; ePatchesCount<4*9; ePatchesCount++)
496 {
497 S[i+0] = ntohs(S[i+0]);//id
498 S[i+1] = ntohs(S[i+1]);//start_cell
499 S[i+2] = ntohs(S[i+2]);//roi
500 S[i+3] = ntohs(S[i+3]);//filling
501
502 i += 4+S[i+2];//skip the pixel data
503 }
504}
505
506// ==========================================================================
507
508bool checkRoiConsistency(const READ_STRUCT &rd, uint16_t roi[])
509{
510 int xjr = -1;
511 int xkr = -1;
512
513 //points to the very first roi
514 int roiPtr = sizeof(PEVNT_HEADER)/2 + 2;
515
516 roi[0] = ntohs(rd.S[roiPtr]);
517
518 for (int jr = 0; jr < 9; jr++)
519 {
520 roi[jr] = ntohs(rd.S[roiPtr]);
521
522 if (roi[jr]>1024)
523 {
524 factPrintf(MessageImp::kError, "Illegal roi in channel %d (allowed: roi<=1024)", jr, roi[jr]);
525 return false;
526 }
527
528 // Check that the roi of pixels jr are compatible with the one of pixel 0
529 if (jr!=8 && roi[jr]!=roi[0])
530 {
531 xjr = jr;
532 break;
533 }
534
535 // Check that the roi of all other DRS chips on boards are compatible
536 for (int kr = 1; kr < 4; kr++)
537 {
538 const int kroi = ntohs(rd.S[roiPtr]);
539 if (kroi != roi[jr])
540 {
541 xjr = jr;
542 xkr = kr;
543 break;
544 }
545 roiPtr += kroi+4;
546 }
547 }
548
549 if (xjr>=0)
550 {
551 if (xkr<0)
552 factPrintf(MessageImp::kFatal, "Inconsistent Roi accross chips [DRS=%d], expected %d, got %d", xjr, roi[0], roi[xjr]);
553 else
554 factPrintf(MessageImp::kFatal, "Inconsistent Roi accross channels [DRS=%d Ch=%d], expected %d, got %d", xjr, xkr, roi[xjr], ntohs(rd.S[roiPtr]));
555
556 return false;
557 }
558
559 if (roi[8] < roi[0])
560 {
561 factPrintf(MessageImp::kError, "Mismatch of roi (%d) in channel 8. Should be larger or equal than the roi (%d) in channel 0.", roi[8], roi[0]);
562 return false;
563 }
564
565 return true;
566}
567
568list<shared_ptr<EVT_CTRL2>> evtCtrl;
569
570shared_ptr<EVT_CTRL2> mBufEvt(const READ_STRUCT &rd, shared_ptr<RUN_CTRL2> &actrun)
571{
572 /*
573 checkroi consistence
574 find existing entry
575 if no entry, try to allocate memory
576 if entry and memory, init event structure
577 */
578
579 uint16_t nRoi[9];
580 if (!checkRoiConsistency(rd, nRoi))
581 return shared_ptr<EVT_CTRL2>();
582
583 for (auto it=evtCtrl.rbegin(); it!=evtCtrl.rend(); it++)
584 {
585 // A reference is enough because the evtCtrl holds the shared_ptr anyway
586 const shared_ptr<EVT_CTRL2> &evt = *it;
587
588 // If the run is different, go on searching.
589 // We cannot stop searching if a lower run-id is found as in
590 // the case of the events, because theoretically, there
591 // can be the same run on two different days.
592 if (rd.H.runnumber != evt->runNum)
593 continue;
594
595 // If the ID of the new event if higher than the last one stored
596 // in that run, we have to assign a new slot (leave the loop)
597 if (rd.H.fad_evt_counter > evt->evNum/* && runID == evtCtrl[k].runNum*/)
598 break;
599
600 if (rd.H.fad_evt_counter != evt->evNum/* || runID != evtCtrl[k].runNum*/)
601 continue;
602
603 // We have found an entry with the same runID and evtID
604 // Check if ROI is consistent
605 if (evt->nRoi != nRoi[0] || evt->nRoiTM != nRoi[8])
606 {
607 factPrintf(MessageImp::kError, "Mismatch of roi within event. Expected roi=%d and roi_tm=%d, got %d and %d.",
608 evt->nRoi, evt->nRoiTM, nRoi[0], nRoi[8]);
609 return shared_ptr<EVT_CTRL2>();
610 }
611
612 // It is maybe not likely, but the header of this board might have
613 // arrived earlier. (We could also update the run-info, but
614 // this should not make a difference here)
615 if ((rd.time.tv_sec==evt->time.tv_sec && rd.time.tv_usec<evt->time.tv_usec) ||
616 rd.time.tv_sec<evt->time.tv_sec)
617 evt->time = rd.time;
618
619 //everything seems fine so far ==> use this slot ....
620 return evt;
621 }
622
623 if (actrun->runId==rd.H.runnumber && (actrun->roi0 != nRoi[0] || actrun->roi8 != nRoi[8]))
624 {
625 factPrintf(MessageImp::kError, "Mismatch of roi within run. Expected roi=%d and roi_tm=%d, got %d and %d (runID=%d, evID=%d)",
626 actrun->roi0, actrun->roi8, nRoi[0], nRoi[8], rd.H.runnumber, rd.H.fad_evt_counter);
627 return shared_ptr<EVT_CTRL2>();
628 }
629
630 EVT_CTRL2 *evt = new EVT_CTRL2;
631
632 evt->time = rd.time;
633
634 evt->runNum = rd.H.runnumber;
635 evt->evNum = rd.H.fad_evt_counter;
636
637 evt->trgNum = rd.H.trigger_id;
638 evt->trgTyp = rd.H.trigger_type;
639
640 evt->nRoi = nRoi[0];
641 evt->nRoiTM = nRoi[8];
642
643 const bool newrun = actrun->runId != rd.H.runnumber;
644 if (newrun)
645 {
646 // Since we have started a new run, we know already when to close the
647 // previous run in terms of number of events
648 actrun->maxEvt = actrun->lastEvt;
649
650 factPrintf(MessageImp::kInfo, "New run %d (evt=%d) registered with roi=%d(%d), prev=%d",
651 rd.H.runnumber, rd.H.fad_evt_counter, nRoi[0], nRoi[8], actrun->runId);
652
653 // The new run is the active run now
654 actrun = shared_ptr<RUN_CTRL2>(new RUN_CTRL2);
655
656 const time_t &tsec = evt->time.tv_sec;
657
658 actrun->openTime = tsec;
659 actrun->closeTime = tsec + 3600 * 24; // max time allowed
660 actrun->runId = rd.H.runnumber;
661 actrun->roi0 = nRoi[0]; // FIXME: Make obsolete!
662 actrun->roi8 = nRoi[8]; // FIXME: Make obsolete!
663
664 // Signal the fadctrl that a new run has been started
665 // Note this is the only place at which we can ensure that
666 // gotnewRun is called only once
667 gotNewRun(*actrun);
668 }
669
670 // Keep pointer to run of this event
671 evt->runCtrl = actrun;
672
673 // Increase the number of events we have started to receive in this run
674 actrun->lastTime = evt->time.tv_sec; // Time when the last event was received
675 actrun->lastEvt++;
676
677 // An event can be the first and the last, but not the last and the first.
678 // Therefore gotNewRun is called before runFinished.
679 // runFinished signals that the last event of a run was just received. Processing
680 // might still be ongoing, but we can start a new run.
681 const bool cond1 = actrun->lastEvt < actrun->maxEvt; // max number of events not reached
682 const bool cond2 = actrun->lastTime < actrun->closeTime; // max time not reached
683 if (!cond1 || !cond2)
684 runFinished();
685
686 // We don't mind here that this is not common to all events,
687 // because every coming event will fullfil the condition as well.
688 if (!cond1)
689 evt->closeRequest |= kRequestMaxEvtsReached;
690 if (!cond2)
691 evt->closeRequest |= kRequestMaxTimeReached;
692
693 // Secure access to evtCtrl against access in CloseRunFile
694 // This should be the last... otherwise we can run into threading issues
695 // if the event is accessed before it is fully initialized.
696 evtCtrl.emplace_back(evt);
697 return evtCtrl.back();
698}
699
700
701void copyData(const READ_STRUCT &rBuf, EVT_CTRL2 *evt)
702{
703 const int i = rBuf.sockId;
704
705 memcpy(evt->FADhead+i, &rBuf.H, sizeof(PEVNT_HEADER));
706
707 int src = sizeof(PEVNT_HEADER) / 2; // Header is 72 byte = 36 shorts
708
709 // consistency of ROIs have been checked already (is it all correct?)
710 const uint16_t &roi = rBuf.S[src+2];
711
712 // different sort in FAD board.....
713 EVENT *event = evt->fEvent;
714 for (int px = 0; px < 9; px++)
715 {
716 for (int drs = 0; drs < 4; drs++)
717 {
718 const int16_t pixC = rBuf.S[src+1]; // start-cell
719 const int16_t pixR = rBuf.S[src+2]; // roi
720 //here we should check if pixH is correct ....
721
722 const int pixS = i*36 + drs*9 + px;
723
724 event->StartPix[pixS] = pixC;
725
726 memcpy(event->Adc_Data + pixS*roi, &rBuf.S[src+4], roi * 2);
727
728 src += 4+pixR;
729
730 // Treatment for ch 9 (TM channel)
731 if (px != 8)
732 continue;
733
734 const int tmS = i*4 + drs;
735
736 //and we have additional TM info
737 if (pixR > roi)
738 {
739 event->StartTM[tmS] = (pixC + pixR - roi) % 1024;
740
741 memcpy(event->Adc_Data + tmS*roi + NPIX*roi, &rBuf.S[src - roi], roi * 2);
742 }
743 else
744 {
745 event->StartTM[tmS] = -1;
746 }
747 }
748 }
749}
750
751// ==========================================================================
752
753uint64_t reportIncomplete(const shared_ptr<EVT_CTRL2> &evt, const char *txt)
754{
755 factPrintf(MessageImp::kWarn, "skip incomplete evt (run=%d, evt=%d, n=%d, %s)",
756 evt->runNum, evt->evNum, evtCtrl.size(), txt);
757
758 uint64_t report = 0;
759
760 char str[1000];
761
762 int ik=0;
763 for (int ib=0; ib<NBOARDS; ib++)
764 {
765 if (ib%10==0)
766 str[ik++] = '|';
767
768 const int jb = evt->board[ib];
769 if (jb>=0) // data received from that board
770 {
771 str[ik++] = '0'+(jb%10);
772 continue;
773 }
774
775 // FIXME: This is not synchronous... it reports
776 // accoridng to the current connection status, not w.r.t. to the
777 // one when the event was taken.
778 if (gi_NumConnect[ib]==0) // board not connected
779 {
780 str[ik++] = 'x';
781 continue;
782 }
783
784 // data from this board lost
785 str[ik++] = '.';
786 report |= ((uint64_t)1)<<ib;
787 }
788
789 str[ik++] = '|';
790 str[ik] = 0;
791
792 factOut(MessageImp::kWarn, str);
793
794 return report;
795}
796
797// ==========================================================================
798// ==========================================================================
799
800void proc1(const shared_ptr<EVT_CTRL2> &);
801
802Queue<shared_ptr<EVT_CTRL2>> processingQueue1(bind(&proc1, placeholders::_1));
803
804void proc1(const shared_ptr<EVT_CTRL2> &evt)
805{
806 applyCalib(*evt, processingQueue1.size());
807}
808
809// If this is not convenient anymore, it could be replaced by
810// a command queue, to which command+data is posted,
811// (e.g. runOpen+runInfo, runClose+runInfo, evtWrite+evtInfo)
812void writeEvt(const shared_ptr<EVT_CTRL2> &evt)
813{
814 //const shared_ptr<RUN_CTRL2> &run = evt->runCtrl;
815 RUN_CTRL2 &run = *evt->runCtrl;
816
817 // Is this a valid event or just an empty event to trigger run close?
818 // If this is not an empty event open the new run-file
819 // Empty events are there to trigger run-closing conditions
820 if (evt->valid())
821 {
822 // File not yet open
823 if (run.fileStat==kFileNotYetOpen)
824 {
825 // runOpen will close a previous run, if still open
826 if (!runOpen(*evt))
827 {
828 factPrintf(MessageImp::kError, "Could not open new file for run %d (evt=%d, runOpen failed)", evt->runNum, evt->evNum);
829 run.fileStat = kFileClosed;
830 return;
831 }
832
833 factPrintf(MessageImp::kInfo, "Opened new file for run %d (evt=%d)", evt->runNum, evt->evNum);
834 run.fileStat = kFileOpen;
835 }
836
837 // Here we have a valid calibration and can go on with that.
838 // It is important that _all_ events are sent for calibration (except broken ones)
839 processingQueue1.post(evt);
840 }
841
842 // File already closed
843 if (run.fileStat==kFileClosed)
844 return;
845
846 bool rc1 = true;
847 if (evt->valid())
848 {
849 rc1 = runWrite(*evt);
850 if (!rc1)
851 factPrintf(MessageImp::kError, "Writing event %d for run %d failed (runWrite)", evt->evNum, evt->runNum);
852 }
853
854 // File not open... no need to close or to check for close
855 // ... this is the case if CloseRunFile was called before any file was opened.
856 if (run.fileStat!=kFileOpen)
857 return;
858
859 // File is not yet to be closed.
860 if (rc1 && evt->closeRequest==kRequestNone)
861 return;
862
863 runClose(run);
864 run.fileStat = kFileClosed;
865
866 vector<string> reason;
867 if (evt->closeRequest&kRequestManual)
868 reason.emplace_back("close requested");
869 if (evt->closeRequest&kRequestTimeout)
870 reason.emplace_back("receive timeout");
871 if (evt->closeRequest&kRequestConnectionChange)
872 reason.emplace_back("connection changed");
873 if (evt->closeRequest&kRequestEventCheckFailed)
874 reason.emplace_back("event check failed");
875 if (evt->closeRequest&kRequestMaxTimeReached)
876 reason.push_back(to_string(run.closeTime-run.openTime)+"s reached");
877 if (evt->closeRequest&kRequestMaxEvtsReached)
878 reason.push_back(to_string(run.maxEvt)+" evts reached");
879 if (!rc1)
880 reason.emplace_back("runWrite failed");
881
882 const string str = boost::algorithm::join(reason, ", ");
883 factPrintf(MessageImp::kInfo, "File closed because %s", str.c_str());
884}
885
886Queue<shared_ptr<EVT_CTRL2>> secondaryQueue(bind(&writeEvt, placeholders::_1));
887
888void procEvt(const shared_ptr<EVT_CTRL2> &evt)
889{
890 if (evt->valid())
891 {
892 EVENT *event = evt->fEvent;
893
894 // This is already done in initMemory()
895 //event->Roi = evt->runCtrl->roi0;
896 //event->RoiTM = evt->runCtrl->roi8;
897 //event->EventNum = evt->evNum;
898 //event->TriggerNum = evt->trgNum;
899 //event->TriggerType = evt->trgTyp;
900
901 event->NumBoards = evt->nBoard;
902
903 event->PCTime = evt->time.tv_sec;
904 event->PCUsec = evt->time.tv_usec;
905
906 for (int ib=0; ib<NBOARDS; ib++)
907 event->BoardTime[ib] = evt->FADhead[ib].time;
908
909 if (!eventCheck(*evt))
910 {
911 secondaryQueue.emplace(new EVT_CTRL2(kRequestEventCheckFailed, evt->runCtrl));
912 return;
913 }
914 }
915
916 // If file is open post the event for being written
917 secondaryQueue.post(evt);
918}
919
920// ==========================================================================
921// ==========================================================================
922
923/*
924 task 1-4:
925
926 lock1()-lock4();
927 while (1)
928 {
929 wait for signal [lockN]; // unlocked
930
931 while (n!=10)
932 wait sockets;
933 read;
934
935 lockM();
936 finished[n] = true;
937 signal(mainloop);
938 unlockM();
939 }
940
941
942 mainloop:
943
944 while (1)
945 {
946 lockM();
947 while (!finished[0] || !finished[1] ...)
948 wait for signal [lockM]; // unlocked... signals can be sent
949 finished[0-1] = false;
950 unlockM()
951
952 copy data to queue // locked
953
954 lockN[0-3];
955 signalN[0-3];
956 unlockN[0-3];
957 }
958
959
960 */
961
962/*
963 while (g_reset)
964 {
965 shared_ptr<EVT_CTRL2> evt = new shared_ptr<>;
966
967 // Check that all sockets are connected
968
969 for (int i=0; i<40; i++)
970 if (rd[i].connected && epoll_ctl(fd_epoll, EPOLL_CTL_ADD, socket, NULL)<0)
971 factPrintf(kError, "epoll_ctrl failed: %m (EPOLL_CTL_ADD,rc=%d)", errno);
972
973 while (g_reset)
974 {
975 if (READ_STRUCT::wait()<0)
976 break;
977
978 if (rc_epoll==0)
979 break;
980
981 for (int jj=0; jj<rc_epoll; jj++)
982 {
983 READ_STRUCT *rs = READ_STRUCT::get(jj);
984 if (!rs->connected)
985 continue;
986
987 const bool rc_read = rs->read();
988 if (!rc_read)
989 continue;
990
991 if (rs->bufTyp==READ_STRUCT::kHeader)
992 {
993 [...]
994 }
995
996 [...]
997
998 if (epoll_ctl(fd_epoll, EPOLL_CTL_DEL, socket, NULL)<0)
999 factPrintf(kError, "epoll_ctrl failed: %m (EPOLL_CTL_DEL,rc=%d)", errno);
1000 }
1001
1002 if (once_a_second)
1003 {
1004 if (evt==timeout)
1005 break;
1006 }
1007 }
1008
1009 if (evt.nBoards==actBoards)
1010 primaryQueue.post(evt);
1011 }
1012*/
1013
1014Queue<shared_ptr<EVT_CTRL2>> primaryQueue(bind(&procEvt, placeholders::_1));
1015
1016// This corresponds more or less to fFile... should we merge both?
1017shared_ptr<RUN_CTRL2> actrun;
1018
1019void CloseRunFile()
1020{
1021 // Currently we need actrun here, to be able to set kFileClosed.
1022 // Apart from that we have to ensure that there is an open file at all
1023 // which we can close.
1024 // Submission to the primary queue ensures that the event
1025 // is placed at the right place in the processing chain.
1026 // (Corresponds to the correct run)
1027 primaryQueue.emplace(new EVT_CTRL2(kRequestManual, actrun));
1028}
1029
1030bool mainloop(READ_STRUCT *rd)
1031{
1032 factPrintf(MessageImp::kInfo, "Starting EventBuilder main loop");
1033
1034 primaryQueue.start();
1035 secondaryQueue.start();
1036 processingQueue1.start();;
1037
1038 actrun = shared_ptr<RUN_CTRL2>(new RUN_CTRL2);
1039
1040 //time in seconds
1041 time_t gi_SecTime = time(NULL)-1;
1042
1043 //loop until global variable g_runStat claims stop
1044 g_reset = 0;
1045 while (g_reset == 0)
1046 {
1047#ifdef USE_POLL
1048 int pp[40];
1049 int nn = 0;
1050 pollfd fds[40];
1051 for (int i=0; i<40; i++)
1052 {
1053 if (rd[i].socket>=0 && rd[i].connected && rd[i].bufLen>0)
1054 {
1055 fds[nn].fd = rd[i].socket;
1056 fds[nn].events = POLLIN;
1057 pp[nn] = i;
1058 nn++;
1059 }
1060 }
1061
1062 const int rc_epoll = poll(fds, nn, 100);
1063 if (rc_epoll<0)
1064 break;
1065#endif
1066
1067#ifdef USE_SELECT
1068 fd_set readfs;
1069 FD_ZERO(&readfs);
1070 int nfsd = 0;
1071 for (int i=0; i<NBOARDS; i++)
1072 if (rd[i].socket>=0 && rd[i].connected && rd[i].bufLen>0)
1073 {
1074 FD_SET(rd[i].socket, &readfs);
1075 if (rd[i].socket>nfsd)
1076 nfsd = rd[i].socket;
1077 }
1078
1079 timeval tv;
1080 tv.tv_sec = 0;
1081 tv.tv_usec = 100000;
1082 const int rc_select = select(nfsd+1, &readfs, NULL, NULL, &tv);
1083 // 0: timeout
1084 // -1: error
1085 if (rc_select<0)
1086 {
1087 factPrintf(MessageImp::kError, "Waiting for data failed: %d (select,rc=%d)", errno);
1088 continue;
1089 }
1090#endif
1091
1092#ifdef USE_EPOLL
1093 const int rc_epoll = READ_STRUCT::wait();
1094 if (rc_epoll<0)
1095 break;
1096#endif
1097
1098#ifdef PRIORITY_QUEUE
1099 priority_queue<READ_STRUCT*, vector<READ_STRUCT*>, READ_STRUCTcomp> prio;
1100
1101 for (int i=0; i<NBOARDS; i++)
1102 if (rd[i].connected)
1103 prio.push(rd+i);
1104
1105 if (!prio.empty()) do
1106#endif
1107
1108
1109#ifdef USE_POLL
1110 for (int jj=0; jj<nn; jj++)
1111#endif
1112#ifdef USE_EPOLL
1113 for (int jj=0; jj<rc_epoll; jj++)
1114#endif
1115#if !defined(USE_EPOLL) && !defined(USE_POLL) && !defined(PRIORITY_QUEUE)
1116 for (int jj=0; jj<NBOARDS; jj++)
1117#endif
1118 {
1119#ifdef PRIORITY_QUEUE
1120 READ_STRUCT *rs = prio.top();
1121#endif
1122#ifdef USE_SELECT
1123 if (!FD_ISSET(rs->socket, &readfs))
1124 continue;
1125#endif
1126
1127#ifdef USE_POLL
1128 if ((fds[jj].revents&POLLIN)==0)
1129 continue;
1130#endif
1131
1132#ifdef USE_EPOLL
1133 // FIXME: How to get i?
1134 READ_STRUCT *rs = READ_STRUCT::get(jj);
1135#endif
1136
1137#ifdef USE_POLL
1138 // FIXME: How to get i?
1139 READ_STRUCT *rs = &rd[pp[jj]];
1140#endif
1141
1142#if !defined(USE_POLL) && !defined(USE_EPOLL) && !defined(PRIORITY_QUEUE)
1143 const int i = (jj%4)*10 + (jj/4);
1144 READ_STRUCT *rs = &rd[i];
1145#endif
1146
1147#ifdef COMPLETE_EVENTS
1148 if (rs->bufTyp==READ_STRUCT::kWait)
1149 continue;
1150#endif
1151
1152 // ==================================================================
1153
1154 const bool rc_read = rs->read();
1155
1156 // Connect might have gotten closed during read
1157 gi_NumConnect[rs->sockId] = rs->connected;
1158 gj.numConn[rs->sockId] = rs->connected;
1159
1160 // Read either failed or disconnected, or the buffer is not yet full
1161 if (!rc_read)
1162 continue;
1163
1164 // ==================================================================
1165
1166 if (rs->bufTyp==READ_STRUCT::kHeader)
1167 {
1168 //check if startflag correct; else shift block ....
1169 // FIXME: This is not enough... this combination of
1170 // bytes can be anywhere... at least the end bytes
1171 // must be checked somewhere, too.
1172 uint k;
1173 for (k=0; k<sizeof(PEVNT_HEADER)-1; k++)
1174 {
1175 //if (rs->B[k]==0xfb && rs->B[k+1] == 0x01)
1176 if (*reinterpret_cast<uint16_t*>(rs->B+k) == 0x01fb)
1177 break;
1178 }
1179 rs->skip += k;
1180
1181 //no start of header found
1182 if (k==sizeof(PEVNT_HEADER)-1)
1183 {
1184 rs->B[0] = rs->B[sizeof(PEVNT_HEADER)-1];
1185 rs->bufPos = rs->B+1;
1186 rs->bufLen = sizeof(PEVNT_HEADER)-1;
1187 continue;
1188 }
1189
1190 if (k > 0)
1191 {
1192 memmove(rs->B, rs->B+k, sizeof(PEVNT_HEADER)-k);
1193
1194 rs->bufPos -= k;
1195 rs->bufLen += k;
1196
1197 continue; // We need to read more (bufLen>0)
1198 }
1199
1200 if (rs->skip>0)
1201 {
1202 factPrintf(MessageImp::kInfo, "Skipped %d bytes on port %d", rs->skip, rs->sockId);
1203 rs->skip = 0;
1204 }
1205
1206 // Swap the header entries from network to host order
1207 rs->swapHeader();
1208
1209 rs->bufTyp = READ_STRUCT::kData;
1210 rs->bufLen = rs->len() - sizeof(PEVNT_HEADER);
1211
1212 debugHead(rs->B); // i and fadBoard not used
1213
1214 continue;
1215 }
1216
1217 const uint16_t &end = *reinterpret_cast<uint16_t*>(rs->bufPos-2);
1218 if (end != 0xfe04)
1219 {
1220 factPrintf(MessageImp::kError, "End-of-event flag wrong on socket %2d for event %d (len=%d), got %04x",
1221 rs->sockId, rs->H.fad_evt_counter, rs->len(), end);
1222
1223 // ready to read next header
1224 rs->bufTyp = READ_STRUCT::kHeader;
1225 rs->bufLen = sizeof(PEVNT_HEADER);
1226 rs->bufPos = rs->B;
1227 // FIXME: What to do with the validity flag?
1228 continue;
1229 }
1230
1231 // get index into mBuffer for this event (create if needed)
1232 const shared_ptr<EVT_CTRL2> evt = mBufEvt(*rs, actrun);
1233
1234 // We have a valid entry, but no memory has yet been allocated
1235 if (evt && !evt->initMemory())
1236 {
1237 const time_t tm = time(NULL);
1238 if (evt->runCtrl->reportMem==tm)
1239 continue;
1240
1241 factPrintf(MessageImp::kError, "No free memory left for %d (run=%d)", evt->evNum, evt->runNum);
1242 evt->runCtrl->reportMem = tm;
1243 continue;
1244 }
1245
1246 // ready to read next header
1247 rs->bufTyp = READ_STRUCT::kHeader;
1248 rs->bufLen = sizeof(PEVNT_HEADER);
1249 rs->bufPos = rs->B;
1250
1251 // Fatal error occured. Event cannot be processed. Skip it. Start reading next header.
1252 if (!evt)
1253 continue;
1254
1255 // This should never happen
1256 if (evt->board[rs->sockId] != -1)
1257 {
1258 factPrintf(MessageImp::kError, "Got event %5d from board %3d (i=%3d, len=%5d) twice.",
1259 evt->evNum, rs->sockId, rs->sockId, rs->len());
1260 // FIXME: What to do with the validity flag?
1261 continue; // Continue reading next header
1262 }
1263
1264 // Swap the data entries (board headers) from network to host order
1265 rs->swapData();
1266
1267 // Copy data from rd[i] to mBuffer[evID]
1268 copyData(*rs, evt.get());
1269
1270#ifdef COMPLETE_EVENTS
1271 // Do not read anmymore from this board until the whole event has been received
1272 rs->bufTyp = READ_STRUCT::kWait;
1273#endif
1274 // now we have stored a new board contents into Event structure
1275 evt->board[rs->sockId] = rs->sockId;
1276 evt->header = evt->FADhead+rs->sockId;
1277 evt->nBoard++;
1278
1279#ifdef COMPLETE_EPOLL
1280 if (epoll_ctl(READ_STRUCT::fd_epoll, EPOLL_CTL_DEL, rs->socket, NULL)<0)
1281 {
1282 factPrintf(MessageImp::kError, "epoll_ctrl failed: %m (EPOLL_CTL_DEL,rc=%d)", errno);
1283 break;
1284 }
1285#endif
1286 // event not yet complete
1287 if (evt->nBoard < READ_STRUCT::activeSockets)
1288 continue;
1289
1290 // All previous events are now flagged as incomplete ("expired")
1291 // and will be removed. (This is a bit tricky, because pop_front()
1292 // would invalidate the current iterator if not done _after_ the increment)
1293 for (auto it=evtCtrl.begin(); it!=evtCtrl.end(); )
1294 {
1295 const bool found = it->get()==evt.get();
1296 if (!found)
1297 reportIncomplete(*it, "expired");
1298 else
1299 primaryQueue.post(evt);
1300
1301 // package_len is 0 if nothing was received.
1302 for (int ib=0; ib<40; ib++)
1303 rd[ib].relBytes += (*it)->FADhead[ib].package_length;
1304
1305 it++;
1306 evtCtrl.pop_front();
1307
1308 // We reached the current event, so we are done
1309 if (found)
1310 break;
1311 }
1312
1313#ifdef COMPLETE_EPOLL
1314 for (int j=0; j<40; j++)
1315 {
1316 epoll_event ev;
1317 ev.events = EPOLLIN;
1318 ev.data.ptr = &rd[j]; // user data (union: ev.ptr)
1319 if (epoll_ctl(READ_STRUCT::fd_epoll, EPOLL_CTL_ADD, rd[j].socket, &ev)<0)
1320 {
1321 factPrintf(MessageImp::kError, "epoll_ctl failed: %m (EPOLL_CTL_ADD,rc=%d)", errno);
1322 return;
1323 }
1324 }
1325#endif
1326
1327#ifdef COMPLETE_EVENTS
1328 for (int j=0; j<40; j++)
1329 {
1330 //if (rs->bufTyp==READ_STRUCT::kWait)
1331 {
1332 rs->bufTyp = READ_STRUCT::kHeader;
1333 rs->bufLen = sizeof(PEVNT_HEADER);
1334 rs->bufPos = rs->B;
1335 }
1336 }
1337#endif
1338 } // end for loop over all sockets
1339#ifdef PRIORITY_QUEUE
1340 while (0); // convert continue into break ;)
1341#endif
1342
1343 // ==================================================================
1344
1345 const time_t actTime = time(NULL);
1346 if (actTime == gi_SecTime)
1347 {
1348#if !defined(USE_SELECT) && !defined(USE_EPOLL) && !defined(USE_POLL)
1349 if (evtCtrl.empty())
1350 usleep(1);
1351#endif
1352 continue;
1353 }
1354 gi_SecTime = actTime;
1355
1356 // ==================================================================
1357 //loop over all active events and flag those older than read-timeout
1358 //delete those that are written to disk ....
1359
1360 // This could be improved having the pointer which separates the queue with
1361 // the incomplete events from the queue with the complete events
1362 for (auto it=evtCtrl.begin(); it!=evtCtrl.end(); )
1363 {
1364 // A reference is enough because the shared_ptr is hold by the evtCtrl
1365 const shared_ptr<EVT_CTRL2> &evt = *it;
1366
1367 // The first event is the oldest. If the first event within the
1368 // timeout window was received, we can stop searchinf further.
1369 if (evt->time.tv_sec+g_evtTimeout>=actTime)
1370 break;
1371
1372 // This will result in the emission of a dim service.
1373 // It doesn't matter if that takes comparably long,
1374 // because we have to stop the run anyway.
1375 const uint64_t rep = reportIncomplete(evt, "timeout");
1376 factReportIncomplete(rep);
1377
1378 // package_len is 0 when nothing was received from this board
1379 for (int ib=0; ib<40; ib++)
1380 rd[ib].relBytes += (*it)->FADhead[ib].package_length;
1381
1382 it++;
1383 evtCtrl.pop_front();
1384 }
1385
1386 // =================================================================
1387
1388 gj.bufNew = evtCtrl.size(); //# incomplete events in buffer
1389 gj.bufEvt = primaryQueue.size(); //# complete events in buffer
1390 gj.bufWrite = secondaryQueue.size(); //# complete events in buffer
1391 gj.bufProc = processingQueue1.size(); //# complete events in buffer
1392 gj.bufTot = Memory::max_inuse/MAX_TOT_MEM;
1393 gj.usdMem = Memory::max_inuse;
1394 gj.totMem = Memory::allocated;
1395 gj.maxMem = g_maxMem;
1396
1397 gj.deltaT = 1000; // temporary, must be improved
1398
1399 bool changed = false;
1400
1401 static vector<uint64_t> store(NBOARDS);
1402
1403 for (int ib=0; ib<NBOARDS; ib++)
1404 {
1405 gj.rateBytes[ib] = store[ib]>rd[ib].totBytes ? rd[ib].totBytes : rd[ib].totBytes-store[ib];
1406 gj.relBytes[ib] = rd[ib].totBytes-rd[ib].relBytes;
1407
1408 store[ib] = rd[ib].totBytes;
1409
1410 if (rd[ib].check(g_port[ib].sockDef, g_port[ib].sockAddr))
1411 changed = true;
1412
1413 gi_NumConnect[ib] = rd[ib].connected;
1414 gj.numConn[ib] = rd[ib].connected;
1415 }
1416
1417 factStat(gj);
1418
1419 Memory::max_inuse = 0;
1420
1421 // =================================================================
1422
1423 // This is a fake event to trigger possible run-closing conditions once a second
1424 // FIXME: This is not yet ideal because a file would never be closed
1425 // if a new file has been started and no events of the new file
1426 // have been received yet
1427 int request = kRequestNone;
1428
1429 // If nothing was received for more than 5min, close file
1430 if (actTime-actrun->lastTime>300)
1431 request |= kRequestTimeout;
1432
1433 // If connection status has changed
1434 if (changed)
1435 request |= kRequestConnectionChange;
1436
1437 if (request!=kRequestNone)
1438 runFinished();
1439
1440 if (actrun->fileStat==kFileOpen)
1441 primaryQueue.emplace(new EVT_CTRL2(request, actrun));
1442 }
1443
1444 // 1: Stop, wait for event to get processed
1445 // 2: Stop, finish immediately
1446 // 101: Restart, wait for events to get processed
1447 // 101: Restart, finish immediately
1448 //
1449 const int gi_reset = g_reset;
1450
1451 const bool abort = gi_reset%100==2;
1452
1453 factPrintf(MessageImp::kInfo, "Stop reading ... RESET=%d (%s threads)", gi_reset, abort?"abort":"join");
1454
1455 primaryQueue.wait(abort);
1456 secondaryQueue.wait(abort);
1457 processingQueue1.wait(abort);
1458
1459 // Here we also destroy all runCtrl structures and hence close all open files
1460 evtCtrl.clear();
1461 actrun.reset();
1462
1463 factPrintf(MessageImp::kInfo, "Exit read Process...");
1464 factPrintf(MessageImp::kInfo, "%ld Bytes flagged as in-use.", Memory::inuse);
1465
1466 factStat(gj);
1467
1468 return gi_reset>=100;
1469}
1470
1471// ==========================================================================
1472// ==========================================================================
1473
1474void StartEvtBuild()
1475{
1476 factPrintf(MessageImp::kInfo, "Starting EventBuilder++");
1477
1478 memset(gi_NumConnect, 0, NBOARDS*sizeof(*gi_NumConnect));
1479
1480 memset(&gj, 0, sizeof(GUI_STAT));
1481
1482 gj.usdMem = Memory::inuse;
1483 gj.totMem = Memory::allocated;
1484 gj.maxMem = g_maxMem;
1485
1486
1487 READ_STRUCT rd[NBOARDS];
1488
1489 // This is only that every socket knows its id (maybe we replace that by arrays instead of an array of sockets)
1490 for (int i=0; i<NBOARDS; i++)
1491 rd[i].sockId = i;
1492
1493 while (mainloop(rd));
1494
1495 //must close all open sockets ...
1496 factPrintf(MessageImp::kInfo, "Close all sockets...");
1497
1498 READ_STRUCT::close();
1499
1500 // Now all sockets get closed. This is not reflected in gi_NumConnect
1501 // The current workaround is to count all sockets as closed when the thread is not running
1502}
Note: See TracBrowser for help on using the repository browser.