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

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