source: trunk/FACT++/src/EventBuilderWrapper.h@ 15286

Last change on this file since 15286 was 15286, checked in by tbretz, 11 years ago
Fixed the description of FILE_FORMAT and INCOMPLETE
File size: 49.6 KB
Line 
1#ifndef FACT_EventBuilderWrapper
2#define FACT_EventBuilderWrapper
3
4#include <sstream>
5
6#if BOOST_VERSION < 104400
7#if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 4))
8#undef BOOST_HAS_RVALUE_REFS
9#endif
10#endif
11#include <boost/thread.hpp>
12#include <boost/filesystem.hpp>
13#include <boost/date_time/posix_time/posix_time_types.hpp>
14
15#include "DimWriteStatistics.h"
16
17#include "DataCalib.h"
18#include "DataWriteRaw.h"
19
20#ifdef HAVE_FITS
21#include "DataWriteFits.h"
22#else
23#define DataWriteFits DataWriteFits2
24#endif
25
26#include "DataWriteFits2.h"
27
28namespace ba = boost::asio;
29namespace bs = boost::system;
30namespace fs = boost::filesystem;
31
32using ba::ip::tcp;
33
34using namespace std;
35
36// ========================================================================
37
38#include "EventBuilder.h"
39
40extern "C" {
41 extern void StartEvtBuild();
42 extern int CloseRunFile(uint32_t runId, uint32_t closeTime, uint32_t maxEvt);
43}
44
45// ========================================================================
46
47class EventBuilderWrapper
48{
49public:
50 // FIXME
51 static EventBuilderWrapper *This;
52
53 MessageImp &fMsg;
54
55private:
56 boost::thread fThread;
57
58 enum CommandStates_t // g_runStat
59 {
60 kAbort = -2, // quit as soon as possible ('abort')
61 kExit = -1, // stop reading, quit when buffered events done ('exit')
62 kInitialize = 0, // 'initialize' (e.g. dim not yet started)
63 kHybernate = 1, // do nothing for long time ('hybernate') [wakeup within ~1sec]
64 kSleep = 2, // do nothing ('sleep') [wakeup within ~10msec]
65 kModeFlush = 10, // read data from camera, but skip them ('flush')
66 kModeTest = 20, // read data and process them, but do not write to disk ('test')
67 kModeFlag = 30, // read data, process and write all to disk ('flag')
68 kModeRun = 40, // read data, process and write selected to disk ('run')
69 };
70
71 enum
72 {
73 kCurrent = 0,
74 kTotal = 1,
75 kEventId = 2,
76 kTriggerId = 3,
77 };
78
79 FAD::FileFormat_t fFileFormat;
80
81 uint32_t fMaxRun;
82 uint32_t fLastOpened;
83 uint32_t fLastClosed;
84 uint32_t fNumEvts[4];
85
86 DimWriteStatistics fDimWriteStats;
87 DimDescribedService fDimRuns;
88 DimDescribedService fDimEvents;
89 DimDescribedService fDimRawData;
90 DimDescribedService fDimEventData;
91 DimDescribedService fDimFeedbackData;
92 DimDescribedService fDimFwVersion;
93 DimDescribedService fDimRunNumber;
94 DimDescribedService fDimStatus;
95 DimDescribedService fDimDNA;
96 DimDescribedService fDimTemperature;
97 DimDescribedService fDimPrescaler;
98 DimDescribedService fDimRefClock;
99 DimDescribedService fDimRoi;
100 DimDescribedService fDimDac;
101 DimDescribedService fDimDrsRuns;
102 DimDescribedService fDimDrsCalibration;
103 DimDescribedService fDimStatistics1;
104 DimDescribedService fDimStatistics2;
105 DimDescribedService fDimFileFormat;
106 DimDescribedService fDimIncomplete;
107
108 bool fDebugStream;
109 bool fDebugRead;
110 bool fDebugLog;
111
112 string fPath;
113 uint64_t fNightAsInt;
114 uint32_t fRunNumber;
115
116protected:
117 bool InitRunNumber(const string &path="")
118 {
119 if (!path.empty())
120 {
121 if (!DimWriteStatistics::DoesPathExist(path, fMsg))
122 {
123 fMsg.Error("Data path "+path+" does not exist!");
124 return false;
125 }
126
127 fPath = path;
128 fDimWriteStats.SetCurrentFolder(fPath);
129
130 fMsg.Info("Data path set to "+path+".");
131 }
132
133 // Get current night
134 const uint64_t night = Time().NightAsInt();
135 if (night==fNightAsInt)
136 return true;
137
138 // Check for run numbers
139 fRunNumber = 1000;
140
141 while (--fRunNumber>0)
142 {
143 const string name = DataProcessorImp::FormFileName(fPath, night, fRunNumber, "");
144
145 if (access((name+"bin").c_str(), F_OK) == 0)
146 break;
147 if (access((name+"fits").c_str(), F_OK) == 0)
148 break;
149 if (access((name+"drs.fits").c_str(), F_OK) == 0)
150 break;
151 }
152
153 // This is now the first file which does not exist
154 fRunNumber++;
155 fLastOpened = 0;
156
157 // Check if we have exceeded the maximum
158 if (fRunNumber==1000)
159 {
160 fMsg.Error("You have a file with run-number 1000 in "+fPath+" ["+to_string(night)+"]");
161 return false;
162 }
163
164 ostringstream str;
165 if (fNightAsInt==0)
166 str << "First night...";
167 else
168 str << "Night has changd from " << fNightAsInt << "... new";
169 str << " run-number is " << night << "-" << setfill('0') << setw(3) << fRunNumber << " [" << (fPath.empty()?".":fPath) << "]";
170 fMsg.Message(str);
171
172 fNightAsInt = night;
173
174 return true;
175 }
176
177public:
178 EventBuilderWrapper(MessageImp &imp) : fMsg(imp),
179 fFileFormat(FAD::kNone), fMaxRun(0), fLastOpened(0), fLastClosed(0),
180 fDimWriteStats ("FAD_CONTROL", imp),
181 fDimRuns ("FAD_CONTROL/RUNS", "I:5;C",
182 "Run files statistics"
183 "|stats[int]:num of open files, min/max run no, last opened or closed run"
184 "|file[string]:filename of last opened file"),
185 fDimEvents ("FAD_CONTROL/EVENTS", "I:4",
186 "Event counts"
187 "|evtsCount[int]:Num evts cur. run, total (all run), evt ID, trig. Num"),
188 fDimRawData ("FAD_CONTROL/RAW_DATA", "S:1;S:1;I:1;I:1;S:1;I:1;C:4;I:1;I:2;I:40;S:1440;S:160;F",
189 "|roi[uint16]:number of samples per pixel"
190 "|roi_tm[uint16]:number of samples per time-marker channel"
191 "|num_fad[uint32]:event number from FADs"
192 "|num_ftm[uint32]:trigger number from FTM"
193 "|type[uint16]:trigger type from FTM"
194 "|num_boards[uint32]:number of active boards"
195 "|error[uint8]:event builder error counters"
196 "|dummy[]:"
197 "|time[uint32]:PC time as unix time stamp"
198 "|time_board[uint32]:Time stamp of FAD boards"
199 "|start_pix[int16]:start sample of pixels"
200 "|start_tm[int16]:start sample of time marker channels"
201 "|adc[int16]:adc data"),
202 fDimEventData ("FAD_CONTROL/EVENT_DATA", "F:1440;F:1440;F:1440;F:1440", "|avg:|rms:|max:|pos"),
203 fDimFeedbackData("FAD_CONTROL/FEEDBACK_DATA", "F:1440", ""),
204 fDimFwVersion ("FAD_CONTROL/FIRMWARE_VERSION", "F:42",
205 "Firmware version number of fad boards"
206 "|firmware[float]:Version number of firmware, for each board. 40=min, 41=max"),
207 fDimRunNumber ("FAD_CONTROL/RUN_NUMBER", "I:42",
208 "Run numbers coming from FAD boards"
209 "|runNumbers[int]:current run number of each FAD board. 40=min, 41=max"),
210 fDimStatus ("FAD_CONTROL/STATUS", "S:42",
211 "Status of FAD boards"
212 "|status[bitpattern]:Status of each FAD board. Maybe buggy"),
213 fDimDNA ("FAD_CONTROL/DNA", "X:40",
214 "DNA of FAD boards"
215 "|DNA[hex]:Hex identifier of each FAD board"),
216 fDimTemperature ("FAD_CONTROL/TEMPERATURE", "F:82",
217 "FADs temperatures"
218 "|temp[deg. C]:0 global min, 1-40 min, 41 global max, 42-81 max"),
219 fDimPrescaler ("FAD_CONTROL/PRESCALER", "S:42",
220 "Trigger generator prescaler of fad boards"
221 "|prescaler[int]:Trigger generator prescaler value, for each board"),
222 fDimRefClock ("FAD_CONTROL/REFERENCE_CLOCK", "I:42",
223 "Reference clock of FAD boards"
224 "|refClocks[t]:ref clocks of FAD boards. 40=min, 41=max"),
225 fDimRoi ("FAD_CONTROL/REGION_OF_INTEREST", "S:2", "roi:|roi_rm:"),
226 fDimDac ("FAD_CONTROL/DAC", "S:336",
227 "DAC settings of each FAD board"
228 "|DAC[int]:DAC counts, sequentially DAC 0 board 0, 0/1, 0/2... (plus min max)"),
229 fDimDrsRuns ("FAD_CONTROL/DRS_RUNS", "I:1;I:3",
230 "|roi:Region of interest of secondary baseline"
231 "|run:Run numbers of DRS runs (0=none)"),
232 fDimDrsCalibration("FAD_CONTROL/DRS_CALIBRATION", "I:1;I:3;F:1474560;F:1474560;F:1474560;F:1474560;F:1474560;F:1474560;F:163840;F:163840",
233 "|roi:Region of interest of secondary baseline"
234 "|run:Run numbers of DRS runs (0=none)"),
235 fDimStatistics1 ("FAD_CONTROL/STATISTICS1", "I:3;I:5;X:4;I:3;I:3;I:40;I:1;I:2;C:40;I:40;I:40;X:40",
236 "Event Builder status for GUI display"
237 "|threadInfo[int]:Number of read, proc and writes"
238 "|bufferInfo[int]:Events in buffer, incomp., comp., tot., max past cycle, total"
239 "|memInfo[int]:total buf. mem, used mem, max used, max past cycle"
240 "|EvtCnt[int]:Number of events skipped, written, with errors"
241 "|badRoi[int]:Num boards with wrong ROI in event, run or board"
242 "|badRoiBoard[int]:Num boards with wrong ROI"
243 "|deltaT[ms]:Time in ms for rates"
244 "|rateNew[int]:Number of new start events received"
245 "|numConn[int]:Number of connections per board"
246 "|errConn[int]:IO errors per board"
247 "|rateBytes[int]:Bytes read this cycle"
248 "|totBytes[int]:Bytes read (counter)"),
249 fDimStatistics2 ("FAD_CONTROL/STATISTICS2", "I:1;I:280;X:40;I:40;I:4;I:4;I:2;I:2;I:3;C:40",
250 "Event Builder status, events oriented"
251 "|reset[int]:If increased, reset all counters"
252 "|numRead[int]:How often sucessful read from N sockets per loop"
253 "|gotByte[int]:number of bytes read per board"
254 "|gotErr[int]:number of com. errors per board"
255 "|evtStat[int]:number of evts read, completed, with errors, incomplete"
256 "|procStat[int]:num. of evts proc., w probs, acc. or rej. by SW trigger"
257 "|feedStat[int]:number of evts used or rejected by feedback system"
258 "|wrtStat[int]:number of evts written to disk, with errors"
259 "|runStat[int]:number of run opened, closed, with open or close errors"
260 "|numConn[int]:number of sockets successfully opened per board"),
261 fDimFileFormat("FAD_CONTROL/FILE_FORMAT", "S:1", "|format[int]:Current file format"),
262 fDimIncomplete("FAD_CONTROL/INCOMPLETE", "X:1", "|incomplete[bits]:One bit per board"),
263 fDebugStream(false), fDebugRead(false), fDebugLog(false), fNightAsInt(0)
264 {
265 if (This)
266 throw logic_error("EventBuilderWrapper cannot be instantiated twice.");
267
268 This = this;
269
270 memset(fNumEvts, 0, sizeof(fNumEvts));
271 fDimEvents.Update(fNumEvts);
272
273 for (size_t i=0; i<40; i++)
274 ConnectSlot(i, tcp::endpoint());
275 }
276 virtual ~EventBuilderWrapper()
277 {
278 Abort();
279
280 // FIXME: Used timed_join and abort afterwards
281 // What's the maximum time the eb need to abort?
282 fThread.join();
283 //ffMsg.Info("EventBuilder stopped.");
284
285 for (vector<DataProcessorImp*>::iterator it=fFiles.begin(); it!=fFiles.end(); it++)
286 delete *it;
287 }
288
289 set<uint32_t> fIsRunStarted;
290 map<uint32_t, FAD::RunDescription> fExpectedRuns;
291
292 uint32_t StartNewRun(int64_t maxtime, int64_t maxevt, const pair<string, FAD::Configuration> &ref)
293 {
294 if (maxtime<=0 || maxtime>24*60*60)
295 maxtime = 24*60*60;
296 if (maxevt<=0 || maxevt>INT32_MAX)
297 maxevt = INT32_MAX;
298
299 const FAD::RunDescription descr =
300 {
301 uint32_t(maxtime),
302 uint32_t(maxevt),
303 ref.first,
304 ref.second,
305 };
306
307 if (!InitRunNumber())
308 return 0;
309
310 // FIMXE: Maybe reset an event counter so that the mcp can count events?
311
312 //fMsg.Info(" ==> TODO: Set a limit on the size of fExpectedRuns!");
313
314 fExpectedRuns[fRunNumber] = descr;
315 fIsRunStarted.insert(fRunNumber);
316 return fRunNumber++;
317 }
318
319 bool IsThreadRunning()
320 {
321 return !fThread.timed_join(boost::posix_time::microseconds(0));
322 }
323
324 void SetMaxMemory(unsigned int mb) const
325 {
326 /*
327 if (mb*1000000<GetUsedMemory())
328 {
329 // ffMsg.Warn("...");
330 return;
331 }*/
332
333 g_maxMem = size_t(mb)*1000000;
334 }
335
336 void StartThread(const vector<tcp::endpoint> &addr)
337 {
338 if (IsThreadRunning())
339 {
340 fMsg.Warn("Start - EventBuilder still running");
341 return;
342 }
343
344 fLastMessage.clear();
345
346 for (size_t i=0; i<40; i++)
347 ConnectSlot(i, addr[i]);
348
349 g_runStat = kModeRun;
350 g_maxProc = 3;
351
352 fMsg.Message("Starting EventBuilder thread");
353
354 fThread = boost::thread(StartEvtBuild);
355 }
356 void ConnectSlot(unsigned int i, const tcp::endpoint &addr)
357 {
358 if (i>39)
359 return;
360
361 if (addr==tcp::endpoint())
362 {
363 DisconnectSlot(i);
364 return;
365 }
366
367 g_port[i].sockAddr.sin_family = AF_INET;
368 g_port[i].sockAddr.sin_addr.s_addr = htonl(addr.address().to_v4().to_ulong());
369 g_port[i].sockAddr.sin_port = htons(addr.port());
370 // In this order
371 g_port[i].sockDef = 1;
372 }
373 void DisconnectSlot(unsigned int i)
374 {
375 if (i>39)
376 return;
377
378 g_port[i].sockDef = 0;
379 // In this order
380 g_port[i].sockAddr.sin_family = AF_INET;
381 g_port[i].sockAddr.sin_addr.s_addr = 0;
382 g_port[i].sockAddr.sin_port = 0;
383 }
384 void IgnoreSlot(unsigned int i)
385 {
386 if (i>39)
387 return;
388 if (g_port[i].sockAddr.sin_port==0)
389 return;
390
391 g_port[i].sockDef = -1;
392 }
393
394
395 void Abort()
396 {
397 fMsg.Message("Signal abort to EventBuilder thread...");
398 g_runStat = kAbort;
399 }
400
401 void ResetThread(bool soft)
402 {
403 /*
404 if (g_reset > 0)
405
406 * suspend reading
407 * reset = g_reset;
408 * g_reset=0
409
410 * reset% 10
411 == 0 leave event Buffers as they are
412 == 1 let all buffers drain (write (incomplete) events)
413 > 1 flush all buffers (do not write buffered events)
414
415 * (reset/10)%10
416 > 0 close all sockets and destroy them (also free the
417 allocated read-buffers)
418 recreate before resuming operation
419 [ this is more than just close/open that can be
420 triggered by e.g. close/open the base-socket ]
421
422 * (reset/100)%10
423 > 0 close all open run-files
424
425 * (reset/1000)
426 sleep so many seconds before resuming operation
427 (does not (yet) take into account time left when waiting
428 for buffers getting empty ...)
429
430 * resume_reading
431
432 */
433 fMsg.Message("Signal reset to EventBuilder thread...");
434 g_reset = soft ? 101 : 102;
435 }
436
437 void Exit()
438 {
439 fMsg.Message("Signal exit to EventBuilder thread...");
440 g_runStat = kExit;
441 }
442
443 /*
444 void Wait()
445 {
446 fThread.join();
447 ffMsg.Message("EventBuilder stopped.");
448 }*/
449
450 void Hybernate() const { g_runStat = kHybernate; }
451 void Sleep() const { g_runStat = kSleep; }
452 void FlushMode() const { g_runStat = kModeFlush; }
453 void TestMode() const { g_runStat = kModeTest; }
454 void FlagMode() const { g_runStat = kModeFlag; }
455 void RunMode() const { g_runStat = kModeRun; }
456
457 // FIXME: To be removed
458 //void SetMode(int mode) const { g_runStat = mode; }
459
460 bool IsConnected(int i) const { return gi_NumConnect[i]==7; }
461 bool IsConnecting(int i) const { return !IsConnected(i) && !IsDisconnected(i); }
462 bool IsDisconnected(int i) const { return gi_NumConnect[i]<=0 && g_port[i].sockDef==0; }
463 int GetNumConnected(int i) const { return gi_NumConnect[i]; }
464 int GetNumFilesOpen() const { return fFiles.size(); }
465
466 /*
467 bool IsConnected(int i) const { return gi_NumConnect[i]>0; }
468 bool IsConnecting(int i) const { return !IsConnected(i) && !IsDisconnected(i); }
469 bool IsDisconnected(int i) const { return gi_NumConnect[i]<=0 && g_port[i].sockDef==0; }
470 int GetNumConnected(int i) const { return gi_NumConnect[i]; }
471 */
472
473 void SetIgnore(int i, bool b) const { if (g_port[i].sockDef!=0) g_port[i].sockDef=b?-1:1; }
474 bool IsIgnored(int i) const { return g_port[i].sockDef==-1; }
475
476 void SetOutputFormat(FAD::FileFormat_t f)
477 {
478 const bool changed = f!=fFileFormat;
479
480 fFileFormat = f;
481 fDimFileFormat.Update(uint16_t(f));
482
483 string msg = "File format set to: ";
484 switch (f)
485 {
486 case FAD::kNone: msg += "kNone."; break;
487 case FAD::kDebug: msg += "kDebug."; break;
488 case FAD::kFits: msg += "kFits."; break;
489 case FAD::kCfitsio: msg += "kCfitsio"; break;
490 case FAD::kRaw: msg += "kRaw"; break;
491 case FAD::kCalib:
492 DataCalib::Restart();
493 DataCalib::Update(fDimDrsCalibration, fDimDrsRuns);
494 fMsg.Message("Resetted DRS calibration.");
495 return;
496 }
497
498 if (changed)
499 fMsg.Message(msg);
500 }
501
502 virtual int ResetSecondaryDrsBaseline()
503 {
504 if (DataCalib::ResetTrgOff(fDimDrsCalibration, fDimDrsRuns))
505 {
506 fFileFormat = FAD::kCalib;
507 fDimFileFormat.Update(uint16_t(fFileFormat));
508 fMsg.Message("Resetted DRS calibration for secondary baseline.");
509 }
510 else
511 fMsg.Warn("Could not reset DRS calibration of secondary baseline.");
512
513 return 0;
514 }
515
516 void SetDebugLog(bool b) { fDebugLog = b; }
517
518 void SetDebugStream(bool b)
519 {
520 fDebugStream = b;
521 if (b)
522 return;
523
524 for (int i=0; i<40; i++)
525 {
526 if (!fDumpStream[i].is_open())
527 continue;
528
529 fDumpStream[i].close();
530
531 ostringstream name;
532 name << "socket_dump-" << setfill('0') << setw(2) << i << ".bin";
533 fMsg.Message("Closed file '"+name.str()+"'");
534 }
535 }
536
537 void SetDebugRead(bool b)
538 {
539 fDebugRead = b;
540 if (b || !fDumpRead.is_open())
541 return;
542
543 fDumpRead.close();
544 fMsg.Message("Closed file 'socket_events.txt'");
545 }
546
547// size_t GetUsedMemory() const { return gi_usedMem; }
548
549 void LoadDrsCalibration(const char *fname)
550 {
551 if (!DataCalib::ReadFits(fname, fMsg))
552 return;
553 fMsg.Info("Successfully loaded DRS calibration from "+string(fname));
554 DataCalib::Update(fDimDrsCalibration, fDimDrsRuns);
555 }
556
557 virtual int CloseOpenFiles() { CloseRunFile(0, 0, 0); return 0; }
558
559
560 /*
561 struct OpenFileToDim
562 {
563 int code;
564 char fileName[FILENAME_MAX];
565 };
566
567 SignalRunOpened(runid, filename);
568 // Send num open files
569 // Send runid, (more info about the run?), filename via dim
570
571 SignalEvtWritten(runid);
572 // Send num events written of newest file
573
574 SignalRunClose(runid);
575 // Send new num open files
576 // Send empty file-name if no file is open
577
578 */
579
580 // -------------- Mapped event builder callbacks ------------------
581
582 void UpdateRuns(const string &fname="")
583 {
584 uint32_t values[5] =
585 {
586 static_cast<uint32_t>(fFiles.size()),
587 0xffffffff,
588 0,
589 fLastOpened,
590 fLastClosed
591 };
592
593 for (vector<DataProcessorImp*>::const_iterator it=fFiles.begin();
594 it!=fFiles.end(); it++)
595 {
596 const DataProcessorImp *file = *it;
597
598 if (file->GetRunId()<values[1])
599 values[1] = file->GetRunId();
600
601 if (file->GetRunId()>values[2])
602 values[2] = file->GetRunId();
603 }
604
605 fMaxRun = values[2];
606
607 vector<char> data(sizeof(values)+fname.size()+1);
608 memcpy(data.data(), values, sizeof(values));
609 strcpy(data.data()+sizeof(values), fname.c_str());
610
611 fDimRuns.Update(data);
612 }
613
614 vector<DataProcessorImp*> fFiles;
615
616 FileHandle_t runOpen(uint32_t runid, RUN_HEAD *h, size_t)
617 {
618 //fMsg.Info(" ==> TODO: Update run configuration in database!");
619
620 map<uint32_t,FAD::RunDescription>::iterator it = fExpectedRuns.begin();
621 while (it!=fExpectedRuns.end())
622 {
623 if (it->first<runid)
624 {
625 ostringstream str;
626 str << "runOpen - Missed run " << it->first << ".";
627 fMsg.Info(str);
628
629 fExpectedRuns.erase(it++);
630 continue;
631 }
632 if (it->first==runid)
633 break;
634 it++;
635 }
636
637 FAD::RunDescription desc;
638
639 if (it==fExpectedRuns.end())
640 {
641 ostringstream str;
642 str << "runOpen - Run " << runid << " wasn't expected (maybe manual triggers)";
643 fMsg.Warn(str);
644 }
645 else
646 {
647 desc = it->second;
648 fExpectedRuns.erase(it);
649 }
650
651 // Check if file already exists...
652 DataProcessorImp *file = 0;
653 switch (fFileFormat)
654 {
655 case FAD::kNone: file = new DataDump(fPath, fNightAsInt, runid, fMsg); break;
656 case FAD::kDebug: file = new DataDebug(fPath, fNightAsInt, runid, fMsg); break;
657 case FAD::kCfitsio: file = new DataWriteFits(fPath, fNightAsInt, runid, fMsg); break;
658 case FAD::kFits: file = new DataWriteFits2(fPath, fNightAsInt, runid, fMsg); break;
659 case FAD::kRaw: file = new DataWriteRaw(fPath, fNightAsInt, runid, fMsg); break;
660 case FAD::kCalib: file = new DataCalib(fPath, fNightAsInt, runid, fDimDrsCalibration, fDimDrsRuns, fMsg); break;
661 }
662
663 try
664 {
665 if (!file->Open(h, desc))
666 return 0;
667 }
668 catch (const exception &e)
669 {
670 fMsg.Error("Exception trying to open file: "+string(e.what()));
671 return 0;
672 }
673
674 fFiles.push_back(file);
675
676 ostringstream str;
677 str << "Opened: " << file->GetFileName() << " (" << file->GetRunId() << ")";
678 fMsg.Info(str);
679
680 fDimWriteStats.FileOpened(file->GetFileName());
681
682 fLastOpened = runid;
683 UpdateRuns(file->GetFileName());
684
685 fNumEvts[kEventId] = 0;
686 fNumEvts[kTriggerId] = 0;
687
688 fNumEvts[kCurrent] = 0;
689 fDimEvents.Update(fNumEvts);
690 // fDimCurrentEvent.Update(uint32_t(0));
691
692 return reinterpret_cast<FileHandle_t>(file);
693 }
694
695 int runWrite(FileHandle_t handler, EVENT *e, size_t /*sz*/)
696 {
697 DataProcessorImp *file = reinterpret_cast<DataProcessorImp*>(handler);
698
699 if (!file->WriteEvt(e))
700 return -1;
701
702 if (file->GetRunId()==fMaxRun)
703 {
704 fNumEvts[kCurrent]++;
705 fNumEvts[kEventId] = e->EventNum;
706 fNumEvts[kTriggerId] = e->TriggerNum;
707 }
708
709 fNumEvts[kTotal]++;
710
711 static Time oldt(boost::date_time::neg_infin);
712 Time newt;
713 if (newt>oldt+boost::posix_time::seconds(1))
714 {
715 fDimEvents.Update(fNumEvts);
716 oldt = newt;
717 }
718
719
720 // ===> SignalEvtWritten(runid);
721 // Send num events written of newest file
722
723 /* close run runId (all all runs if runId=0) */
724 /* return: 0=close scheduled / >0 already closed / <0 does not exist */
725 //CloseRunFile(file->GetRunId(), time(NULL)+2) ;
726
727 return 0;
728 }
729
730 virtual void CloseRun(uint32_t /*runid*/) { }
731
732 int runClose(FileHandle_t handler, RUN_TAIL *tail, size_t)
733 {
734 //fMsg.Info(" ==> TODO: Update run configuration in database!");
735
736 DataProcessorImp *file = reinterpret_cast<DataProcessorImp*>(handler);
737
738 const vector<DataProcessorImp*>::iterator it = find(fFiles.begin(), fFiles.end(), file);
739 if (it==fFiles.end())
740 {
741 ostringstream str;
742 str << "File handler (" << handler << ") requested to close by event builder doesn't exist.";
743 fMsg.Fatal(str);
744 return -1;
745 }
746
747 fFiles.erase(it);
748
749 fLastClosed = file->GetRunId();
750 CloseRun(fLastClosed);
751 UpdateRuns();
752
753 fDimEvents.Update(fNumEvts);
754
755 const bool rc = file->Close(tail);
756 if (!rc)
757 {
758 // Error message
759 }
760
761 ostringstream str;
762 str << "Closed: " << file->GetFileName() << " (" << file->GetRunId() << ")";
763 fMsg.Info(str);
764
765 delete file;
766
767 // ==> SignalRunClose(runid);
768 // Send new num open files
769 // Send empty file-name if no file is open
770
771 return rc ? 0 : -1;
772 }
773
774 ofstream fDumpStream[40];
775
776 void debugStream(int isock, void *buf, int len)
777 {
778 if (!fDebugStream)
779 return;
780
781 const int slot = isock/7;
782 if (slot<0 || slot>39)
783 return;
784
785 if (!fDumpStream[slot].is_open())
786 {
787 ostringstream name;
788 name << "socket_dump-" << setfill('0') << setw(2) << slot << ".bin";
789
790 fDumpStream[slot].open(name.str().c_str(), ios::app);
791 if (!fDumpStream[slot])
792 {
793 ostringstream str;
794 str << "Open file '" << name << "': " << strerror(errno) << " (errno=" << errno << ")";
795 fMsg.Error(str);
796
797 return;
798 }
799
800 fMsg.Message("Opened file '"+name.str()+"' for writing.");
801 }
802
803 fDumpStream[slot].write(reinterpret_cast<const char*>(buf), len);
804 }
805
806 ofstream fDumpRead; // Stream to possibly dump docket events
807
808 void debugRead(int isock, int ibyte, uint32_t event, uint32_t ftmevt, uint32_t runno, int state, uint32_t tsec, uint32_t tusec)
809 {
810 // isock = socketID (0-279)
811 // ibyte = #bytes gelesen
812 // event = eventId (oder 0 wenn noch nicht bekannt)
813 // state : 1=finished reading data
814 // 0=reading data
815 // -1=start reading data (header)
816 // -2=start reading data,
817 // eventId not known yet (too little data)
818 // tsec, tusec = time when reading seconds, microseconds
819 //
820 if (!fDebugRead || ibyte==0)
821 return;
822
823 if (!fDumpRead.is_open())
824 {
825 fDumpRead.open("socket_events.txt", ios::app);
826 if (!fDumpRead)
827 {
828 ostringstream str;
829 str << "Open file 'socket_events.txt': " << strerror(errno) << " (errno=" << errno << ")";
830 fMsg.Error(str);
831
832 return;
833 }
834
835 fMsg.Message("Opened file 'socket_events.txt' for writing.");
836
837 fDumpRead << "# START: " << Time().GetAsStr() << endl;
838 fDumpRead << "# state time_sec time_usec socket slot runno event_id trigger_id bytes_received" << endl;
839 }
840
841 fDumpRead
842 << setw(2) << state << " "
843 << setw(8) << tsec << " "
844 << setw(9) << tusec << " "
845 << setw(3) << isock << " "
846 << setw(2) << isock/7 << " "
847 << runno << " "
848 << event << " "
849 << ftmevt << " "
850 << ibyte << endl;
851 }
852
853 array<uint16_t,2> fVecRoi;
854
855 int eventCheck(uint32_t runNr, PEVNT_HEADER *fadhd, EVENT *event, int /*iboard*/)
856 {
857 /*
858 fadhd[i] ist ein array mit den 40 fad-headers
859 (falls ein board nicht gelesen wurde, ist start_package_flag =0 )
860
861 event ist die Struktur, die auch die write routine erhaelt;
862 darin sind im header die 'soll-werte' fuer z.B. eventID
863 als auch die ADC-Werte (falls Du die brauchst)
864
865 Wenn die routine einen negativen Wert liefert, wird das event
866 geloescht (nicht an die write-routine weitergeleitet [mind. im Prinzip]
867 */
868
869 const array<uint16_t,2> roi = {{ event->Roi, event->RoiTM }};
870
871 if (roi!=fVecRoi)
872 {
873 Update(fDimRoi, roi);
874 fVecRoi = roi;
875 }
876
877 const FAD::EventHeader *beg = reinterpret_cast<FAD::EventHeader*>(fadhd);
878 const FAD::EventHeader *end = reinterpret_cast<FAD::EventHeader*>(fadhd)+40;
879
880 // FIMXE: Compare with target configuration
881
882 for (const FAD::EventHeader *ptr=beg; ptr!=end; ptr++)
883 {
884 // FIXME: Compare with expectations!!!
885 if (ptr->fStartDelimiter==0)
886 {
887 if (ptr==beg)
888 beg++;
889 continue;
890 }
891
892 if (beg->fStatus != ptr->fStatus)
893 {
894 fMsg.Error("Inconsistency in FAD status detected.... closing run.");
895 CloseRunFile(runNr, 0, 0);
896 return -1;
897 }
898
899 if (beg->fRunNumber != ptr->fRunNumber)
900 {
901 fMsg.Error("Inconsistent run number detected.... closing run.");
902 CloseRunFile(runNr, 0, 0);
903 return -1;
904 }
905
906 /*
907 if (beg->fVersion != ptr->fVersion)
908 {
909 Error("Inconsist firmware version detected.... closing run.");
910 CloseRunFile(runNr, 0, 0);
911 break;
912 }
913 */
914 if (beg->fEventCounter != ptr->fEventCounter)
915 {
916 fMsg.Error("Inconsistent FAD event number detected.... closing run.");
917 CloseRunFile(runNr, 0, 0);
918 return -1;
919 }
920
921 if (beg->fTriggerCounter != ptr->fTriggerCounter)
922 {
923 fMsg.Error("Inconsistent FTM trigger number detected.... closing run.");
924 CloseRunFile(runNr, 0, 0);
925 return -1;
926 }
927
928 if (beg->fAdcClockPhaseShift != ptr->fAdcClockPhaseShift)
929 {
930 fMsg.Error("Inconsistent phase shift detected.... closing run.");
931 CloseRunFile(runNr, 0, 0);
932 return -1;
933 }
934
935 if (memcmp(beg->fDac, ptr->fDac, sizeof(beg->fDac)))
936 {
937 fMsg.Error("Inconsistent DAC values detected.... closing run.");
938 CloseRunFile(runNr, 0, 0);
939 return -1;
940 }
941
942 if (beg->fTriggerType != ptr->fTriggerType)
943 {
944 fMsg.Error("Inconsistent trigger type detected.... closing run.");
945 CloseRunFile(runNr, 0, 0);
946 return -1;
947 }
948 }
949
950 // check REFCLK_frequency
951 // check consistency with command configuration
952 // how to log errors?
953 // need gotNewRun/closedRun to know it is finished
954
955 return 0;
956 }
957
958 void SendRawData(PEVNT_HEADER *fadhd, EVENT *event)
959 {
960 // Currently we send any event no matter what its trigger id is...
961 // To be changed.
962 static Time oldt(boost::date_time::neg_infin);
963 Time newt;
964
965 static int skip = 0;
966
967 // FIXME: Only send events if the have newer run-numbers
968 if (newt<oldt+boost::posix_time::milliseconds(skip>0 ? 100 : 1000))
969 return;
970 oldt = newt;
971
972 // Workaround to find a valid header.....
973 const FAD::EventHeader *beg = reinterpret_cast<FAD::EventHeader*>(fadhd);
974 const FAD::EventHeader *end = reinterpret_cast<FAD::EventHeader*>(fadhd)+40;
975
976 // FIMXE: Compare with target configuration
977 const FAD::EventHeader *ptr=beg;
978 for (; ptr!=end; ptr++)
979 {
980 if (ptr->fStartDelimiter!=0)
981 break;
982 }
983 if (ptr==end)
984 return;
985
986
987 vector<char> data(sizeof(EVENT)+event->Roi*sizeof(float)*(1440+160));
988 memcpy(data.data(), event, sizeof(EVENT));
989
990 float *vec = reinterpret_cast<float*>(data.data()+sizeof(EVENT));
991
992 DataCalib::Apply(vec, event->Adc_Data, event->StartPix, event->Roi);
993 DrsCalibrate::RemoveSpikes(vec, event->Roi);
994
995 vector<float> data2(1440*4); // Mean, RMS, Max, Pos
996 const double max = DrsCalibrate::GetPixelStats(data2.data(), vec, event->Roi);
997
998 // Maximum above roughly 5pe
999 if (ptr->IsTriggerPhys() && max<100 && skip<10)
1000 {
1001 skip++;
1002 return;
1003 }
1004
1005 skip = 0;
1006
1007 fDimRawData.setQuality(ptr->fTriggerType);
1008 fDimRawData.Update(data);
1009
1010 fDimEventData.setQuality(ptr->fTriggerType);
1011 fDimEventData.Update(data2);
1012 }
1013
1014 void SendFeedbackData(PEVNT_HEADER *fadhd, EVENT *event)
1015 {
1016 /*
1017 if (!DataCalib::IsValid())
1018 return;
1019
1020 // Workaround to find a valid header.....
1021 const FAD::EventHeader *beg = reinterpret_cast<FAD::EventHeader*>(fadhd);
1022 const FAD::EventHeader *end = reinterpret_cast<FAD::EventHeader*>(fadhd)+40;
1023
1024 // FIMXE: Compare with target configuration
1025
1026 const FAD::EventHeader *ptr=beg;
1027 for (; ptr<end; ptr++)
1028 {
1029 if (ptr->fStartDelimiter!=0)
1030 break;
1031 }
1032
1033 if (ptr==end)
1034 return;
1035
1036 if (!ptr->HasTriggerLPext() && !ptr->HasTriggerLPint())
1037 return;
1038
1039 vector<float> data(event->Roi*1440);
1040 DataCalib::Apply(data.data(), event->Adc_Data, event->StartPix, event->Roi);
1041
1042 DrsCalibrate::RemoveSpikes(data.data(), event->Roi);
1043
1044 vector<float> data2(1440); // Mean, RMS, Max, Pos, first, last
1045 DrsCalibrate::GetPixelMax(data2.data(), data.data(), event->Roi, 0, event->Roi-1);
1046
1047 fDimFeedbackData.Update(data2);
1048 */
1049 }
1050
1051 int subProcEvt(int threadID, PEVNT_HEADER *fadhd, EVENT *event, int16_t /*iboard*/, void */*buffer*/)
1052 {
1053 switch (threadID)
1054 {
1055 case 0:
1056 SendRawData(fadhd, event);
1057 return 1;
1058 case 1:
1059 SendFeedbackData(fadhd, event);
1060 return 2;
1061 }
1062 return 100;
1063 }
1064
1065
1066 bool IsRunStarted() const
1067 {
1068 const set<uint32_t>::const_iterator it = fIsRunStarted.find(fRunNumber-1);
1069 return it==fIsRunStarted.end();// ? true : it->second.started;
1070 }
1071
1072 uint32_t GetRunNumber() const
1073 {
1074 return fRunNumber;
1075 }
1076
1077 bool IsRunFileOpen()
1078 {
1079 return fLastOpened==fRunNumber-1;
1080 }
1081
1082 bool IncreaseRunNumber(uint32_t run)
1083 {
1084 if (!InitRunNumber())
1085 return false;
1086
1087 if (run<fRunNumber)
1088 {
1089 ostringstream msg;
1090 msg <<
1091 "Run number " << run << " smaller than next available "
1092 "run number " << fRunNumber << " in " << fPath << " [" << fNightAsInt << "]";
1093 fMsg.Error(msg);
1094 return false;
1095 }
1096
1097 fRunNumber = run;
1098
1099 return true;
1100 }
1101
1102 void gotNewRun(uint32_t runnr, PEVNT_HEADER */*headers*/)
1103 {
1104 // This function is called even when writing is switched off
1105 set<uint32_t>::iterator it = fIsRunStarted.begin();
1106 while (it!=fIsRunStarted.end())
1107 {
1108 if (*it<runnr)
1109 {
1110 ostringstream str;
1111 str << "gotNewRun - Missed run " << *it << ".";
1112 fMsg.Info(str);
1113
1114 fIsRunStarted.erase(it++);
1115 continue;
1116 }
1117 if (*it==runnr)
1118 break;
1119 it++;
1120 }
1121 if (it==fIsRunStarted.end())
1122 {
1123 ostringstream str;
1124 str << "gotNewRun - Not waiting for run " << runnr << ".";
1125 fMsg.Warn(str);
1126 return;
1127 }
1128
1129 map<uint32_t,FAD::RunDescription>::iterator i2 = fExpectedRuns.find(runnr);
1130 if (i2==fExpectedRuns.end())
1131 {
1132 ostringstream str;
1133 str << "gotNewRun - Run " << runnr << " wasn't expected.";
1134 fMsg.Warn(str);
1135 return;
1136 }
1137
1138 CloseRunFile(runnr, time(NULL)+i2->second.maxtime, i2->second.maxevt);
1139 // return: 0=close scheduled / >0 already closed / <0 does not exist
1140
1141 // FIXME: Move configuration from expected runs to runs which will soon
1142 // be opened/closed
1143
1144 fIsRunStarted.erase(it);
1145 }
1146
1147 map<boost::thread::id, string> fLastMessage;
1148
1149 void factOut(int severity, int err, const char *message)
1150 {
1151 if (!fDebugLog && severity==99)
1152 return;
1153
1154 ostringstream str;
1155 //str << boost::this_thread::get_id() << " ";
1156 str << "EventBuilder(";
1157 if (err<0)
1158 str << "---";
1159 else
1160 str << err;
1161 str << "): " << message;
1162
1163 string &old = fLastMessage[boost::this_thread::get_id()];
1164
1165 if (str.str()==old)
1166 return;
1167 old = str.str();
1168
1169 fMsg.Update(str, severity);
1170 }
1171
1172/*
1173 void factStat(int64_t *stat, int len)
1174 {
1175 if (len!=7)
1176 {
1177 fMsg.Warn("factStat received unknown number of values.");
1178 return;
1179 }
1180
1181 vector<int64_t> data(1, g_maxMem);
1182 data.insert(data.end(), stat, stat+len);
1183
1184 static vector<int64_t> last(8);
1185 if (data==last)
1186 return;
1187 last = data;
1188
1189 fDimStatistics.Update(data);
1190
1191 // len ist die Laenge des arrays.
1192 // array[4] enthaelt wieviele bytes im Buffer aktuell belegt sind; daran
1193 // kannst Du pruefen, ob die 100MB voll sind ....
1194
1195 ostringstream str;
1196 str
1197 << "Wait=" << stat[0] << " "
1198 << "Skip=" << stat[1] << " "
1199 << "Del=" << stat[2] << " "
1200 << "Tot=" << stat[3] << " "
1201 << "Mem=" << stat[4] << "/" << g_maxMem << " "
1202 << "Read=" << stat[5] << " "
1203 << "Conn=" << stat[6];
1204
1205 fMsg.Info(str);
1206 }
1207 */
1208
1209 void factStat(const EVT_STAT &stat)
1210 {
1211 fDimStatistics2.Update(stat);
1212 }
1213
1214 void factStat(const GUI_STAT &stat)
1215 {
1216 fDimStatistics1.Update(stat);
1217 }
1218
1219 void factReportIncomplete(uint64_t rep)
1220 {
1221 fDimIncomplete.Update(rep);
1222 }
1223
1224 array<FAD::EventHeader, 40> fVecHeader;
1225
1226 template<typename T, class S>
1227 array<T, 42> Compare(const S *vec, const T *t)
1228 {
1229 const int offset = reinterpret_cast<const char *>(t) - reinterpret_cast<const char *>(vec);
1230
1231 const T *min = NULL;
1232 const T *val = NULL;
1233 const T *max = NULL;
1234
1235 array<T, 42> arr;
1236
1237 // bool rc = true;
1238 for (int i=0; i<40; i++)
1239 {
1240 const char *base = reinterpret_cast<const char*>(vec+i);
1241 const T *ref = reinterpret_cast<const T*>(base+offset);
1242
1243 arr[i] = *ref;
1244
1245 if (gi_NumConnect[i]!=7)
1246 {
1247 arr[i] = 0;
1248 continue;
1249 }
1250
1251 if (!val)
1252 {
1253 min = ref;
1254 val = ref;
1255 max = ref;
1256 }
1257
1258 if (*ref<*min)
1259 min = ref;
1260
1261 if (*ref>*max)
1262 max = ref;
1263
1264 // if (*val!=*ref)
1265 // rc = false;
1266 }
1267
1268 arr[40] = val ? *min : 1;
1269 arr[41] = val ? *max : 0;
1270
1271 return arr;
1272 }
1273
1274 template<typename T>
1275 array<T, 42> CompareBits(const FAD::EventHeader *h, const T *t)
1276 {
1277 const int offset = reinterpret_cast<const char *>(t) - reinterpret_cast<const char *>(h);
1278
1279 T val = 0;
1280 T rc = 0;
1281
1282 array<T, 42> vec;
1283
1284 bool first = true;
1285
1286 for (int i=0; i<40; i++)
1287 {
1288 const char *base = reinterpret_cast<const char*>(&fVecHeader[i]);
1289 const T *ref = reinterpret_cast<const T*>(base+offset);
1290
1291 vec[i+2] = *ref;
1292
1293 if (gi_NumConnect[i]!=7)
1294 {
1295 vec[i+2] = 0;
1296 continue;
1297 }
1298
1299 if (first)
1300 {
1301 first = false;
1302 val = *ref;
1303 rc = 0;
1304 }
1305
1306 rc |= val^*ref;
1307 }
1308
1309 vec[0] = rc;
1310 vec[1] = val;
1311
1312 return vec;
1313 }
1314
1315 template<typename T, size_t N>
1316 void Update(DimDescribedService &svc, const array<T, N> &data, int n=N)
1317 {
1318// svc.setQuality(vec[40]<=vec[41]);
1319 svc.setData(const_cast<T*>(data.data()), sizeof(T)*n);
1320 svc.Update();
1321 }
1322
1323 template<typename T>
1324 void Print(const char *name, const pair<bool,array<T, 43>> &data)
1325 {
1326 cout << name << "|" << data.first << "|" << data.second[1] << "|" << data.second[0] << "<x<" << data.second[1] << ":";
1327 for (int i=0; i<40;i++)
1328 cout << " " << data.second[i+3];
1329 cout << endl;
1330 }
1331
1332 vector<uint> fNumConnected;
1333
1334 void debugHead(int /*socket*/, const FAD::EventHeader &h)
1335 {
1336 const uint16_t id = h.Id();
1337 if (id>39)
1338 return;
1339
1340 if (fNumConnected.size()!=40)
1341 fNumConnected.resize(40);
1342
1343 const vector<uint> con(gi_NumConnect, gi_NumConnect+40);
1344
1345 const bool changed = con!=fNumConnected || !IsThreadRunning();
1346
1347 fNumConnected = con;
1348
1349 const FAD::EventHeader old = fVecHeader[id];
1350 fVecHeader[id] = h;
1351
1352 if (old.fVersion != h.fVersion || changed)
1353 {
1354 const array<uint16_t,42> ver = Compare(&fVecHeader[0], &fVecHeader[0].fVersion);
1355
1356 array<float,42> data;
1357 for (int i=0; i<42; i++)
1358 {
1359 ostringstream str;
1360 str << (ver[i]>>8) << '.' << (ver[i]&0xff);
1361 data[i] = stof(str.str());
1362 }
1363 Update(fDimFwVersion, data);
1364 }
1365
1366 if (old.fRunNumber != h.fRunNumber || changed)
1367 {
1368 const array<uint32_t,42> run = Compare(&fVecHeader[0], &fVecHeader[0].fRunNumber);
1369 fDimRunNumber.Update(run);
1370 }
1371
1372 if (old.fTriggerGeneratorPrescaler != h.fTriggerGeneratorPrescaler || changed)
1373 {
1374 const array<uint16_t,42> pre = Compare(&fVecHeader[0], &fVecHeader[0].fTriggerGeneratorPrescaler);
1375 fDimPrescaler.Update(pre);
1376 }
1377
1378 if (old.fDNA != h.fDNA || changed)
1379 {
1380 const array<uint64_t,42> dna = Compare(&fVecHeader[0], &fVecHeader[0].fDNA);
1381 Update(fDimDNA, dna, 40);
1382 }
1383
1384 if (old.fStatus != h.fStatus || changed)
1385 {
1386 const array<uint16_t,42> sts = CompareBits(&fVecHeader[0], &fVecHeader[0].fStatus);
1387 Update(fDimStatus, sts);
1388 }
1389
1390 if (memcmp(old.fDac, h.fDac, sizeof(h.fDac)) || changed)
1391 {
1392 array<uint16_t, FAD::kNumDac*42> dacs;
1393
1394 for (int i=0; i<FAD::kNumDac; i++)
1395 {
1396 const array<uint16_t, 42> dac = Compare(&fVecHeader[0], &fVecHeader[0].fDac[i]);
1397 memcpy(&dacs[i*42], &dac[0], sizeof(uint16_t)*42);
1398 }
1399
1400 Update(fDimDac, dacs);
1401 }
1402
1403 // -----------
1404
1405 static Time oldt(boost::date_time::neg_infin);
1406 Time newt;
1407
1408 if (newt>oldt+boost::posix_time::seconds(1))
1409 {
1410 oldt = newt;
1411
1412 // --- RefClock
1413
1414 const array<uint32_t,42> clk = Compare(&fVecHeader[0], &fVecHeader[0].fFreqRefClock);
1415 Update(fDimRefClock, clk);
1416
1417 // --- Temperatures
1418
1419 const array<int16_t,42> tmp[4] =
1420 {
1421 Compare(&fVecHeader[0], &fVecHeader[0].fTempDrs[0]), // 0-39:val, 40:min, 41:max
1422 Compare(&fVecHeader[0], &fVecHeader[0].fTempDrs[1]), // 0-39:val, 40:min, 41:max
1423 Compare(&fVecHeader[0], &fVecHeader[0].fTempDrs[2]), // 0-39:val, 40:min, 41:max
1424 Compare(&fVecHeader[0], &fVecHeader[0].fTempDrs[3]) // 0-39:val, 40:min, 41:max
1425 };
1426
1427 vector<int16_t> data;
1428 data.reserve(82);
1429 data.push_back(tmp[0][40]); // min: 0
1430 data.insert(data.end(), tmp[0].data(), tmp[0].data()+40); // val: 1-40
1431 data.push_back(tmp[0][41]); // max: 41
1432 data.insert(data.end(), tmp[0].data(), tmp[0].data()+40); // val: 42-81
1433
1434 for (int j=1; j<=3; j++)
1435 {
1436 const array<int16_t,42> &ref = tmp[j];
1437
1438 // Gloabl min
1439 if (ref[40]<data[0]) // 40=min
1440 data[0] = ref[40];
1441
1442 // Global max
1443 if (ref[41]>data[41]) // 41=max
1444 data[41] = ref[41];
1445
1446 for (int i=0; i<40; i++)
1447 {
1448 // min per board
1449 if (ref[i]<data[i+1]) // data: 1-40
1450 data[i+1] = ref[i]; // ref: 0-39
1451
1452 // max per board
1453 if (ref[i]>data[i+42]) // data: 42-81
1454 data[i+42] = ref[i]; // ref: 0-39
1455 }
1456
1457
1458 }
1459
1460 vector<float> deg(82); // 0: global min, 1-40: min
1461 for (int i=0; i<82; i++) // 41: global max, 42-81: max
1462 deg[i] = data[i]/16.;
1463 fDimTemperature.Update(deg);
1464 }
1465 }
1466};
1467
1468EventBuilderWrapper *EventBuilderWrapper::This = 0;
1469
1470// ----------- Event builder callbacks implementation ---------------
1471extern "C"
1472{
1473 FileHandle_t runOpen(uint32_t irun, RUN_HEAD *runhd, size_t len)
1474 {
1475 return EventBuilderWrapper::This->runOpen(irun, runhd, len);
1476 }
1477
1478 int runWrite(FileHandle_t fileId, EVENT *event, size_t len)
1479 {
1480 return EventBuilderWrapper::This->runWrite(fileId, event, len);
1481 }
1482
1483 int runClose(FileHandle_t fileId, RUN_TAIL *runth, size_t len)
1484 {
1485 return EventBuilderWrapper::This->runClose(fileId, runth, len);
1486 }
1487
1488 // -----
1489
1490 //void *runStart(uint32_t /*irun*/, RUN_HEAD */*runhd*/, size_t /*len*/)
1491 //{
1492 // return NULL;
1493 //}
1494
1495 int subProcEvt(int threadID, PEVNT_HEADER *fadhd, EVENT *event, int16_t mboard, void *runPtr)
1496 {
1497 return EventBuilderWrapper::This->subProcEvt(threadID, fadhd, event, mboard, runPtr);
1498 }
1499
1500 int runEnd(uint32_t, void */*runPtr*/)
1501 {
1502 return 0;
1503 }
1504
1505 // -----
1506
1507 int eventCheck(uint32_t runNr, PEVNT_HEADER *fadhd, EVENT *event, int mboard)
1508 {
1509 return EventBuilderWrapper::This->eventCheck(runNr, fadhd, event, mboard);
1510 }
1511
1512 void gotNewRun(uint32_t runnr, PEVNT_HEADER *headers)
1513 {
1514 return EventBuilderWrapper::This->gotNewRun(runnr, headers);
1515 }
1516
1517 // -----
1518
1519 void factOut(int severity, int err, const char *message)
1520 {
1521 EventBuilderWrapper::This->factOut(severity, err, message);
1522 }
1523
1524 void factStat(GUI_STAT stat)
1525 {
1526 EventBuilderWrapper::This->factStat(stat);
1527 }
1528
1529 void factStatNew(EVT_STAT stat)
1530 {
1531 EventBuilderWrapper::This->factStat(stat);
1532 }
1533
1534 void factReportIncomplete (uint64_t rep)
1535 {
1536 EventBuilderWrapper::This->factReportIncomplete(rep);
1537 }
1538
1539 // ------
1540
1541 void debugHead(int socket, int/*board*/, void *buf)
1542 {
1543 const FAD::EventHeader &h = *reinterpret_cast<FAD::EventHeader*>(buf);
1544 EventBuilderWrapper::This->debugHead(socket, h);
1545 }
1546
1547 void debugStream(int isock, void *buf, int len)
1548 {
1549 return EventBuilderWrapper::This->debugStream(isock, buf, len);
1550 }
1551
1552 void debugRead(int isock, int ibyte, int32_t event, int32_t ftmevt, int32_t runno, int state, uint32_t tsec, uint32_t tusec)
1553 {
1554 EventBuilderWrapper::This->debugRead(isock, ibyte, event, ftmevt, runno, state, tsec, tusec);
1555 }
1556}
1557
1558#endif
Note: See TracBrowser for help on using the repository browser.