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

Last change on this file since 16107 was 16107, checked in by tbretz, 12 years ago
Removed the C-interface and added the C++-interface to the event builder; added a mutex to secure fExpectedRun; fixed some potential problems erasing entries from collections within iterators; added fIsRunInProgress to signal which run data is currently received from the FADs; propagate the run-type and the night through the run-ctrl structre; removed the need for fIsRunStarted
File size: 40.2 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
28#include "queue.h"
29
30namespace ba = boost::asio;
31namespace bs = boost::system;
32namespace fs = boost::filesystem;
33
34using ba::ip::tcp;
35
36using namespace std;
37
38// ========================================================================
39
40#include "EventBuilder.h"
41
42void StartEvtBuild();
43void CloseRunFile();
44
45// ========================================================================
46
47class EventBuilderWrapper
48{
49public:
50 // FIXME
51 static EventBuilderWrapper *This;
52
53 MessageImp &fMsg;
54
55private:
56 boost::thread fThreadMain;
57
58 enum
59 {
60 kCurrent = 0,
61 kTotal = 1,
62 kEventId = 2,
63 kTriggerId = 3,
64 };
65
66 FAD::FileFormat_t fFileFormat;
67
68 //uint32_t fMaxRun;
69 uint32_t fLastOpened;
70 uint32_t fLastClosed;
71 array<uint32_t,4> fNumEvts;
72
73 DimWriteStatistics fDimWriteStats;
74 DimDescribedService fDimRuns;
75 DimDescribedService fDimEvents;
76 DimDescribedService fDimRawData;
77 DimDescribedService fDimEventData;
78 DimDescribedService fDimFeedbackData;
79 DimDescribedService fDimFwVersion;
80 DimDescribedService fDimRunNumber;
81 DimDescribedService fDimStatus;
82 DimDescribedService fDimDNA;
83 DimDescribedService fDimTemperature;
84 DimDescribedService fDimPrescaler;
85 DimDescribedService fDimRefClock;
86 DimDescribedService fDimRoi;
87 DimDescribedService fDimDac;
88 DimDescribedService fDimDrsRuns;
89 DimDescribedService fDimDrsCalibration;
90 DimDescribedService fDimStatistics1;
91 //DimDescribedService fDimStatistics2;
92 DimDescribedService fDimFileFormat;
93 DimDescribedService fDimIncomplete;
94
95 Queue<pair<Time,GUI_STAT>> fDimQueue1;
96 Queue<tuple<Time,bool,FAD::EventHeader>> fDimQueue2;
97 Queue<pair<Time,array<uint32_t,4>>> fDimQueue3;
98 Queue<pair<Time,array<uint16_t,2>>> fDimQueue4;
99
100 string fPath;
101 uint32_t fNightAsInt;
102 uint32_t fRunNumber;
103 int64_t fRunInProgress;
104
105 array<uint16_t,2> fVecRoi;
106
107protected:
108 bool InitRunNumber(const string &path="")
109 {
110 if (!path.empty())
111 {
112 if (!DimWriteStatistics::DoesPathExist(path, fMsg))
113 {
114 fMsg.Error("Data path "+path+" does not exist!");
115 return false;
116 }
117
118 fPath = path;
119 fDimWriteStats.SetCurrentFolder(fPath);
120
121 fMsg.Info("Data path set to "+path+".");
122 }
123
124 // Get current night
125 const uint32_t night = Time().NightAsInt();
126 if (night==fNightAsInt)
127 return true;
128
129 // Check for run numbers
130 fRunNumber = 1000;
131
132 while (--fRunNumber>0)
133 {
134 const string name = DataProcessorImp::FormFileName(fPath, night, fRunNumber, "");
135
136 if (access((name+"bin").c_str(), F_OK) == 0)
137 break;
138 if (access((name+"fits").c_str(), F_OK) == 0)
139 break;
140 if (access((name+"drs.fits").c_str(), F_OK) == 0)
141 break;
142 }
143
144 // This is now the first file which does not exist
145 fRunNumber++;
146 fLastOpened = 0;
147
148 // Check if we have exceeded the maximum
149 if (fRunNumber==1000)
150 {
151 fMsg.Error("You have a file with run-number 1000 in "+fPath+" ["+to_string(night)+"]");
152 return false;
153 }
154
155 ostringstream str;
156 if (fNightAsInt==0)
157 str << "First night...";
158 else
159 str << "Night has changd from " << fNightAsInt << "... new";
160 str << " run-number is " << night << "-" << setfill('0') << setw(3) << fRunNumber << " [" << (fPath.empty()?".":fPath) << "]";
161 fMsg.Message(str);
162
163 fNightAsInt = night;
164
165 return true;
166 }
167
168public:
169 EventBuilderWrapper(MessageImp &imp) : fMsg(imp),
170 fFileFormat(FAD::kNone), /*fMaxRun(0),*/ fLastOpened(0), fLastClosed(0),
171 fDimWriteStats ("FAD_CONTROL", imp),
172 fDimRuns ("FAD_CONTROL/RUNS", "I:5;C",
173 "Run files statistics"
174 "|stats[int]:num of open files, min/max run no, last opened or closed run"
175 "|file[string]:filename of last opened file"),
176 fDimEvents ("FAD_CONTROL/EVENTS", "I:4",
177 "Event counts"
178 "|evtsCount[int]:Num evts cur. run, total (all run), evt ID, trig. Num"),
179 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",
180 "|roi[uint16]:number of samples per pixel"
181 "|roi_tm[uint16]:number of samples per time-marker channel"
182 "|num_fad[uint32]:event number from FADs"
183 "|num_ftm[uint32]:trigger number from FTM"
184 "|type[uint16]:trigger type from FTM"
185 "|num_boards[uint32]:number of active boards"
186 "|error[uint8]:event builder error counters"
187 "|dummy[]:"
188 "|time[uint32]:PC time as unix time stamp"
189 "|time_board[uint32]:Time stamp of FAD boards"
190 "|start_pix[int16]:start sample of pixels"
191 "|start_tm[int16]:start sample of time marker channels"
192 "|adc[int16]:adc data"),
193 fDimEventData ("FAD_CONTROL/EVENT_DATA", "F:1440;F:1440;F:1440;F:1440", "|avg:|rms:|max:|pos"),
194 fDimFeedbackData("FAD_CONTROL/FEEDBACK_DATA", "F:1440", ""),
195 fDimFwVersion ("FAD_CONTROL/FIRMWARE_VERSION", "F:42",
196 "Firmware version number of fad boards"
197 "|firmware[float]:Version number of firmware, for each board. 40=min, 41=max"),
198 fDimRunNumber ("FAD_CONTROL/RUN_NUMBER", "I:42",
199 "Run numbers coming from FAD boards"
200 "|runNumbers[int]:current run number of each FAD board. 40=min, 41=max"),
201 fDimStatus ("FAD_CONTROL/STATUS", "S:42",
202 "Status of FAD boards"
203 "|status[bitpattern]:Status of each FAD board. Maybe buggy"),
204 fDimDNA ("FAD_CONTROL/DNA", "X:40",
205 "DNA of FAD boards"
206 "|DNA[hex]:Hex identifier of each FAD board"),
207 fDimTemperature ("FAD_CONTROL/TEMPERATURE", "F:82",
208 "FADs temperatures"
209 "|temp[deg. C]:0 global min, 1-40 min, 41 global max, 42-81 max"),
210 fDimPrescaler ("FAD_CONTROL/PRESCALER", "S:42",
211 "Trigger generator prescaler of fad boards"
212 "|prescaler[int]:Trigger generator prescaler value, for each board"),
213 fDimRefClock ("FAD_CONTROL/REFERENCE_CLOCK", "I:42",
214 "Reference clock of FAD boards"
215 "|refClocks[t]:ref clocks of FAD boards. 40=min, 41=max"),
216 fDimRoi ("FAD_CONTROL/REGION_OF_INTEREST", "S:2", "roi:|roi_rm:"),
217 fDimDac ("FAD_CONTROL/DAC", "S:336",
218 "DAC settings of each FAD board"
219 "|DAC[int]:DAC counts, sequentially DAC 0 board 0, 0/1, 0/2... (plus min max)"),
220 fDimDrsRuns ("FAD_CONTROL/DRS_RUNS", "I:1;I:3",
221 "|roi:Region of interest of secondary baseline"
222 "|run:Run numbers of DRS runs (0=none)"),
223 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",
224 "|roi:Region of interest of secondary baseline"
225 "|run:Run numbers of DRS runs (0=none)"),
226 fDimStatistics1 ("FAD_CONTROL/STATISTICS1", "I:3;I:5;X:4;I:3;I:3;I:40;I:1;I:2;C:40;I:40;X:40",
227 "Event Builder status for GUI display"
228 "|threadInfo[int]:Number of read, proc and writes"
229 "|bufferInfo[int]:Events in buffer, incomp., comp., tot., max past cycle, total"
230 "|memInfo[int]:total buf. mem, used mem, max used, max past cycle"
231 "|EvtCnt[int]:Number of events skipped, written, with errors"
232 "|badRoi[int]:Num boards with wrong ROI in event, run or board"
233 "|badRoiBoard[int]:Num boards with wrong ROI"
234 "|deltaT[ms]:Time in ms for rates"
235 "|rateNew[int]:Number of new start events received"
236 "|numConn[int]:Number of connections per board"
237 "|rateBytes[int]:Bytes read this cycle"
238 "|totBytes[int]:Bytes read (counter)"),
239 fDimFileFormat("FAD_CONTROL/FILE_FORMAT", "S:1", "|format[int]:Current file format"),
240 fDimIncomplete("FAD_CONTROL/INCOMPLETE", "X:1", "|incomplete[bits]:One bit per board"),
241 // It is important to instantiate them after the DimServices
242 fDimQueue1(std::bind(&EventBuilderWrapper::factStatSend, this, placeholders::_1)),
243 fDimQueue2(std::bind(&EventBuilderWrapper::procHeader, this, placeholders::_1)),
244 fDimQueue3(std::bind(&EventBuilderWrapper::updateEvents, this, placeholders::_1)),
245 fDimQueue4(std::bind(&EventBuilderWrapper::updateRoi, this, placeholders::_1)),
246 fNightAsInt(0), fRunInProgress(-1)
247 {
248 if (This)
249 throw logic_error("EventBuilderWrapper cannot be instantiated twice.");
250
251 This = this;
252
253 fVecRoi.fill(0);
254
255 memset(fNumEvts.data(), 0, sizeof(fNumEvts));
256 fDimEvents.Update(fNumEvts);
257
258 for (size_t i=0; i<40; i++)
259 ConnectSlot(i, tcp::endpoint());
260 }
261
262 virtual ~EventBuilderWrapper()
263 {
264 Abort();
265
266 // FIXME: Used timed_join and abort afterwards
267 // What's the maximum time the eb need to abort?
268 fThreadMain.join();
269 }
270
271 map<uint32_t, FAD::RunDescription> fExpectedRuns;
272
273 mutex mtx_newrun;
274
275 uint32_t StartNewRun(int64_t maxtime, int64_t maxevt, const pair<string, FAD::Configuration> &ref)
276 {
277 if (maxtime<=0 || maxtime>24*60*60)
278 maxtime = 24*60*60;
279 if (maxevt<=0 || maxevt>INT32_MAX)
280 maxevt = INT32_MAX;
281
282 if (!InitRunNumber())
283 return 0;
284
285 const FAD::RunDescription descr =
286 {
287 uint32_t(maxtime),
288 uint32_t(maxevt),
289 fNightAsInt,
290 ref.first,
291 ref.second,
292 };
293
294 const lock_guard<mutex> lock(mtx_newrun);
295 fExpectedRuns[fRunNumber] = descr;
296 return fRunNumber++;
297 }
298
299 bool IsThreadRunning()
300 {
301 if (fThreadMain.get_id()==boost::this_thread::get_id())
302 return true;
303 return !fThreadMain.timed_join(boost::posix_time::microseconds(0));
304 }
305
306 void SetMaxMemory(unsigned int mb) const
307 {
308 g_maxMem = size_t(mb)*1000000;
309 }
310
311 void StartThread(const vector<tcp::endpoint> &addr)
312 {
313 if (IsThreadRunning())
314 {
315 fMsg.Warn("Start - EventBuilder still running");
316 return;
317 }
318
319 //fLastMessage.clear();
320
321 for (size_t i=0; i<40; i++)
322 ConnectSlot(i, addr[i]);
323
324 fMsg.Message("Starting EventBuilder thread");
325
326 fThreadMain = boost::thread(StartEvtBuild);
327 }
328
329 void ConnectSlot(unsigned int i, const tcp::endpoint &addr)
330 {
331 if (i>39)
332 return;
333
334 if (addr==tcp::endpoint())
335 {
336 DisconnectSlot(i);
337 return;
338 }
339
340 struct sockaddr_in sockaddr; //IP for each socket
341 sockaddr.sin_family = AF_INET;
342 sockaddr.sin_addr.s_addr = htonl(addr.address().to_v4().to_ulong());
343 sockaddr.sin_port = htons(addr.port());
344 memcpy(&g_port[i].sockAddr, &sockaddr, sizeof(struct sockaddr_in));
345
346 // In this order
347 g_port[i].sockDef = 1;
348
349 fDimIncomplete.setQuality(0);
350 fDimIncomplete.Update(uint64_t(0));
351 }
352
353 void DisconnectSlot(unsigned int i)
354 {
355 if (i>39)
356 return;
357
358 g_port[i].sockDef = 0;
359 // In this order
360
361 fDimIncomplete.setQuality(0);
362 fDimIncomplete.Update(uint64_t(0));
363 }
364 void IgnoreSlot(unsigned int i)
365 {
366 if (i>39)
367 return;
368
369 if (g_port[i].sockAddr.sin_port==0)
370 return;
371
372 g_port[i].sockDef = -1;
373 }
374
375
376 void Abort()
377 {
378 fMsg.Message("Signal abort to EventBuilder thread...");
379 g_reset = 2;
380 }
381
382 void ResetThread(bool soft)
383 {
384 fMsg.Message("Signal reset to EventBuilder thread...");
385 g_reset = soft ? 101 : 102;
386 }
387
388 void Exit()
389 {
390 fMsg.Message("Signal exit to EventBuilder thread...");
391 g_reset = 1;
392 }
393
394 bool IsConnected(int i) const { return gi_NumConnect[i]==1; }
395 bool IsConnecting(int i) const { return gi_NumConnect[i]==0 && g_port[i].sockDef!=0; }
396 bool IsDisconnected(int i) const { return gi_NumConnect[i]==0 && g_port[i].sockDef==0; }
397 bool IsRunInProgress() const { return fRunInProgress>=0; }
398
399 void SetIgnore(int i, bool b) const { if (g_port[i].sockDef!=0) g_port[i].sockDef=b?-1:1; }
400 bool IsIgnored(int i) const { return g_port[i].sockDef==-1; }
401
402 void SetOutputFormat(FAD::FileFormat_t f)
403 {
404 const bool changed = f!=fFileFormat;
405
406 fFileFormat = f;
407 fDimFileFormat.Update(uint16_t(f));
408
409 string msg = "File format set to: ";
410 switch (f)
411 {
412 case FAD::kNone: msg += "kNone."; break;
413 case FAD::kDebug: msg += "kDebug."; break;
414 case FAD::kFits: msg += "kFits."; break;
415 case FAD::kCfitsio: msg += "kCfitsio"; break;
416 case FAD::kRaw: msg += "kRaw"; break;
417 case FAD::kCalib:
418 DataCalib::Restart();
419 DataCalib::Update(fDimDrsCalibration, fDimDrsRuns);
420 fMsg.Message("Resetted DRS calibration.");
421 return;
422 }
423
424 if (changed)
425 fMsg.Message(msg);
426 }
427
428 virtual int ResetSecondaryDrsBaseline()
429 {
430 if (DataCalib::ResetTrgOff(fDimDrsCalibration, fDimDrsRuns))
431 {
432 fFileFormat = FAD::kCalib;
433 fDimFileFormat.Update(uint16_t(fFileFormat));
434 fMsg.Message("Resetted DRS calibration for secondary baseline.");
435 }
436 else
437 fMsg.Warn("Could not reset DRS calibration of secondary baseline.");
438
439 return 0;
440 }
441
442 void LoadDrsCalibration(const char *fname)
443 {
444 if (!DataCalib::ReadFits(fname, fMsg))
445 return;
446 fMsg.Info("Successfully loaded DRS calibration from "+string(fname));
447 DataCalib::Update(fDimDrsCalibration, fDimDrsRuns);
448 }
449
450 virtual int CloseOpenFiles() { CloseRunFile(); return 0; }
451
452
453 // -------------- Mapped event builder callbacks ------------------
454
455 void UpdateRuns(const string &fname="")
456 {
457 uint32_t values[5] =
458 {
459 !fFile ? 0 : 1,
460 fFile ? fFile->GetRunId() : 0,
461 fFile ? fFile->GetRunId() : 0,
462 fLastOpened,
463 fLastClosed
464 };
465
466 vector<char> data(sizeof(values)+fname.size()+1);
467 memcpy(data.data(), values, sizeof(values));
468 strcpy(data.data()+sizeof(values), fname.c_str());
469 fDimRuns.Update(data);
470 }
471
472 shared_ptr<DataProcessorImp> fFile;
473
474 void updateEvents(const pair<Time,array<uint32_t,4>> &stat)
475 {
476 fDimEvents.setData(stat.second.data(), sizeof(uint32_t)*4);
477 fDimEvents.Update(stat.first);
478 }
479
480 bool runOpen(const shared_ptr<EVT_CTRL2> &evt)
481 {
482 const uint32_t night = evt->runCtrl->night;
483 const uint32_t runid = evt->runNum>0 ? evt->runNum : time(NULL);
484
485 // If there is still an open file: close it
486 if (fFile)
487 runClose();
488
489 // Keep a copy of the currently valid drs calibration
490 // and associate it to the run control structure
491 evt->runCtrl->calib = shared_ptr<DrsCalibration>(new DrsCalibration(DataCalib::GetCalibration()));
492
493 // FIMXE: Check if file already exists...
494
495 // Crate the file
496 DataProcessorImp *file = 0;
497 switch (fFileFormat)
498 {
499 case FAD::kNone: file = new DataDump(fPath, night, runid, fMsg); break;
500 case FAD::kDebug: file = new DataDebug(fPath, night, runid, fMsg); break;
501 case FAD::kCfitsio: file = new DataWriteFits(fPath, night, runid, fMsg); break;
502 case FAD::kFits: file = new DataWriteFits2(fPath, night, runid, fMsg); break;
503 case FAD::kRaw: file = new DataWriteRaw(fPath, night, runid, fMsg); break;
504 case FAD::kCalib: file = new DataCalib(fPath, night, runid, fDimDrsCalibration, fDimDrsRuns, fMsg); break;
505 }
506
507 try
508 {
509 // Try to open the file
510 FAD::RunDescription desc;
511 desc.name = evt->runCtrl->runType;
512
513 if (!file->Open(*evt, desc))
514 return false;
515 }
516 catch (const exception &e)
517 {
518 fMsg.Error("Exception trying to open file: "+string(e.what()));
519 return false;
520 }
521
522 fLastOpened = runid;
523
524 // Signal that a file is open
525 fFile = shared_ptr<DataProcessorImp>(file);
526
527 // Now do all the calls which potentially block (dim)
528
529 // Time for update runs before time for update events
530 UpdateRuns(file->GetFileName());
531 fNumEvts[kEventId] = 0;
532 fNumEvts[kTriggerId] = 0;
533 fNumEvts[kCurrent] = 0;
534 fDimQueue3.post(make_pair(Time(), fNumEvts));
535
536 fDimWriteStats.FileOpened(file->GetFileName());
537
538 ostringstream str;
539 str << "Opened: " << file->GetFileName() << " (" << file->GetRunId() << ")";
540 fMsg.Info(str);
541
542 return true;
543 }
544
545 bool runWrite(const shared_ptr<EVT_CTRL2> &e)
546 {
547 const EVENT &evt = *e->fEvent;
548 if (!fFile->WriteEvt(evt))
549 return false;
550
551 fNumEvts[kCurrent]++;
552 fNumEvts[kEventId] = evt.EventNum;
553 fNumEvts[kTriggerId] = evt.TriggerNum;
554 fNumEvts[kTotal]++;
555
556 static Time oldt(boost::date_time::neg_infin);
557 Time newt;
558 if (newt>oldt+boost::posix_time::seconds(1))
559 {
560 fDimQueue3.post(make_pair(Time(), fNumEvts));
561 oldt = newt;
562 }
563
564 return true;
565 }
566
567 void runClose()
568 {
569 if (!fFile)
570 return;
571
572 // It can happen that runFinished was never called
573 // (e.g. runWrite failed)
574 if (fRunInProgress==fFile->GetRunId())
575 fRunInProgress = -1;
576
577 // Close the file
578 const bool rc = fFile->Close(NULL);
579
580 fLastClosed = fFile->GetRunId();
581
582 ostringstream str;
583 str << "Closed: " << fFile->GetFileName() << " (" << fFile->GetRunId() << ")";
584 if (!rc)
585 str << "... failed!";
586
587 // Signal that the file is closed
588
589 fFile.reset();
590
591 // Now do all the calls which can potentially block (dim)
592
593 CloseRun(fLastClosed);
594
595 // Time for update events before time for update runs
596 fDimQueue3.post(make_pair(Time(), fNumEvts));
597 UpdateRuns();
598
599 // Do the potentially blocking call after all others
600 rc ? fMsg.Info(str) : fMsg.Error(str);
601 }
602
603 virtual void CloseRun(uint32_t /*runid*/) { }
604
605 void updateRoi(const pair<Time, array<uint16_t,2>> &roi)
606 {
607 fDimRoi.setData(roi.second.data(), sizeof(uint16_t)*2);
608 fDimRoi.Update(roi.first);
609 }
610
611 int eventCheck(const shared_ptr<EVT_CTRL2> &evt)
612 {
613 const PEVNT_HEADER *fadhd = evt->FADhead.get();
614 const EVENT *event = evt->fEvent;
615
616 const array<uint16_t,2> roi = {{ event->Roi, event->RoiTM }};
617
618 if (roi!=fVecRoi)
619 {
620 fDimQueue4.post(make_pair(Time(), roi));
621 fVecRoi = roi;
622 }
623
624 const FAD::EventHeader *beg = reinterpret_cast<const FAD::EventHeader*>(fadhd);
625 const FAD::EventHeader *end = reinterpret_cast<const FAD::EventHeader*>(fadhd)+40;
626
627 // FIMXE: Compare with target configuration
628
629 for (const FAD::EventHeader *ptr=beg; ptr!=end; ptr++)
630 {
631 // FIXME: Compare with expectations!!!
632 if (ptr->fStartDelimiter==0)
633 {
634 if (ptr==beg)
635 beg++;
636 continue;
637 }
638
639 if (beg->fStatus != ptr->fStatus)
640 {
641 fMsg.Error("Inconsistency in FAD status detected.... closing run.");
642 evt->runCtrl->maxEvt = 0;
643 return -1;
644 }
645
646 if (beg->fRunNumber != ptr->fRunNumber)
647 {
648 fMsg.Error("Inconsistent run number detected.... closing run.");
649 evt->runCtrl->maxEvt = 0;
650 return -1;
651 }
652
653 /*
654 if (beg->fVersion != ptr->fVersion)
655 {
656 Error("Inconsist firmware version detected.... closing run.");
657 CloseRunFile(runNr, 0, 0);
658 break;
659 }
660 */
661 if (beg->fEventCounter != ptr->fEventCounter)
662 {
663 fMsg.Error("Inconsistent FAD event number detected.... closing run.");
664 evt->runCtrl->maxEvt = 0;
665 return -1;
666 }
667
668 if (beg->fTriggerCounter != ptr->fTriggerCounter)
669 {
670 fMsg.Error("Inconsistent FTM trigger number detected.... closing run.");
671 evt->runCtrl->maxEvt = 0;
672 return -1;
673 }
674
675 if (beg->fAdcClockPhaseShift != ptr->fAdcClockPhaseShift)
676 {
677 fMsg.Error("Inconsistent phase shift detected.... closing run.");
678 evt->runCtrl->maxEvt = 0;
679 return -1;
680 }
681
682 if (memcmp(beg->fDac, ptr->fDac, sizeof(beg->fDac)))
683 {
684 fMsg.Error("Inconsistent DAC values detected.... closing run.");
685 evt->runCtrl->maxEvt = 0;
686 return -1;
687 }
688
689 if (beg->fTriggerType != ptr->fTriggerType)
690 {
691 fMsg.Error("Inconsistent trigger type detected.... closing run.");
692 evt->runCtrl->maxEvt = 0;
693 return -1;
694 }
695 }
696
697 // check REFCLK_frequency
698 // check consistency with command configuration
699 // how to log errors?
700 // need gotNewRun/closedRun to know it is finished
701
702 return 0;
703 }
704
705 void applyCalib(const shared_ptr<EVT_CTRL2> &evt)
706 {
707 const PEVNT_HEADER *fadhd = evt->FADhead.get();
708 const EVENT *event = evt->fEvent;
709
710 // Currently we send any event no matter what its trigger id is...
711 // To be changed.
712 static Time oldt(boost::date_time::neg_infin);
713 Time newt;
714
715 static int skip = 0;
716
717 // FIXME: Only send events if the have newer run-numbers
718 if (newt<oldt+boost::posix_time::milliseconds(skip>0 ? 100 : 1000))
719 return;
720 oldt = newt;
721
722 // Workaround to find a valid header.....
723 const FAD::EventHeader *beg = reinterpret_cast<const FAD::EventHeader*>(fadhd);
724 const FAD::EventHeader *end = reinterpret_cast<const FAD::EventHeader*>(fadhd)+40;
725
726 // FIMXE: Compare with target configuration
727 const FAD::EventHeader *ptr=beg;
728 for (; ptr!=end; ptr++)
729 {
730 if (ptr->fStartDelimiter!=0)
731 break;
732 }
733 if (ptr==end)
734 return;
735
736
737 vector<char> data(sizeof(EVENT)+event->Roi*sizeof(float)*(1440+160));
738 memcpy(data.data(), event, sizeof(EVENT));
739
740 float *vec = reinterpret_cast<float*>(data.data()+sizeof(EVENT));
741
742 evt->runCtrl->calib->Apply(vec, event->Adc_Data, event->StartPix, event->Roi);
743 DrsCalibrate::RemoveSpikes(vec, event->Roi);
744
745 vector<float> data2(1440*4); // Mean, RMS, Max, Pos
746 const double max = DrsCalibrate::GetPixelStats(data2.data(), vec, event->Roi);
747
748 // Maximum above roughly 5pe
749 if (ptr->IsTriggerPhys() && max<100 && skip<10)
750 {
751 skip++;
752 return;
753 }
754
755 skip = 0;
756
757 fDimRawData.setQuality(ptr->fTriggerType);
758 fDimRawData.Update(data);
759
760 fDimEventData.setQuality(ptr->fTriggerType);
761 fDimEventData.Update(data2);
762
763 }
764
765 /*
766 void SendFeedbackData(PEVNT_HEADER *fadhd, EVENT *event)
767 {
768 if (!DataCalib::IsValid())
769 return;
770
771 // Workaround to find a valid header.....
772 const FAD::EventHeader *beg = reinterpret_cast<FAD::EventHeader*>(fadhd);
773 const FAD::EventHeader *end = reinterpret_cast<FAD::EventHeader*>(fadhd)+40;
774
775 // FIMXE: Compare with target configuration
776
777 const FAD::EventHeader *ptr=beg;
778 for (; ptr<end; ptr++)
779 {
780 if (ptr->fStartDelimiter!=0)
781 break;
782 }
783
784 if (ptr==end)
785 return;
786
787 if (!ptr->HasTriggerLPext() && !ptr->HasTriggerLPint())
788 return;
789
790 vector<float> data(event->Roi*1440);
791 DataCalib::Apply(data.data(), event->Adc_Data, event->StartPix, event->Roi);
792
793 DrsCalibrate::RemoveSpikes(data.data(), event->Roi);
794
795 vector<float> data2(1440); // Mean, RMS, Max, Pos, first, last
796 DrsCalibrate::GetPixelMax(data2.data(), data.data(), event->Roi, 0, event->Roi-1);
797
798 fDimFeedbackData.Update(data2);
799 }
800 */
801
802 bool IsRunWaiting()// const
803 {
804 const lock_guard<mutex> lock(mtx_newrun);
805 return fExpectedRuns.find(fRunNumber-1)!=fExpectedRuns.end();
806 }
807
808 uint32_t GetRunNumber() const
809 {
810 return fRunNumber;
811 }
812
813 /*
814 bool IsRunFileOpen()
815 {
816 return fLastOpened==fRunNumber-1;
817 }*/
818
819 bool IncreaseRunNumber(uint32_t run)
820 {
821 if (!InitRunNumber())
822 return false;
823
824 if (run<fRunNumber)
825 {
826 ostringstream msg;
827 msg <<
828 "Run number " << run << " smaller than next available "
829 "run number " << fRunNumber << " in " << fPath << " [" << fNightAsInt << "]";
830 fMsg.Error(msg);
831 return false;
832 }
833
834 fRunNumber = run;
835
836 return true;
837 }
838
839 void gotNewRun(RUN_CTRL2 &run)
840 {
841 // This is to secure iteration over fExpectedRuns
842 const lock_guard<mutex> lock(mtx_newrun);
843
844 map<uint32_t,FAD::RunDescription>::const_iterator it = fExpectedRuns.begin();
845 while (it!=fExpectedRuns.end())
846 {
847 if (it->first<run.runId)
848 {
849 ostringstream str;
850 str << "runOpen - Missed run " << it->first << ".";
851 fMsg.Info(str);
852
853 // Increase the iterator first, it becomes invalid with the next call
854 const auto is = it++;
855 fExpectedRuns.erase(is);
856 continue;
857 }
858
859 if (it->first==run.runId)
860 break;
861
862 it++;
863 }
864
865 if (it==fExpectedRuns.end())
866 {
867 ostringstream str;
868 str << "runOpen - Run " << run.runId << " wasn't expected (maybe manual triggers)";
869 fMsg.Warn(str);
870
871 // This is not ideal, but the best we can do
872 run.night = fNightAsInt;
873
874 return;
875 }
876
877 const FAD::RunDescription &conf = it->second;
878
879 run.runType = conf.name;
880 run.maxEvt = conf.maxevt;
881 run.closeTime = conf.maxtime + run.openTime;
882 run.night = conf.night;
883
884 fExpectedRuns.erase(it);
885
886 // Now signal the fadctrl (configuration process that a run is in progress)
887 // Maybe this could be done earlier, but we are talking about a
888 // negligible time scale here.
889 fRunInProgress = run.runId;
890 }
891
892 void runFinished()
893 {
894 // This is called when the last event of a run (run time exceeded or
895 // max number of events exceeded) has been received.
896 fRunInProgress = -1;
897 }
898
899 //map<boost::thread::id, string> fLastMessage;
900
901 void factOut(int severity, const char *message)
902 {
903 ostringstream str;
904 str << "EventBuilder: " << message;
905
906 /*
907 string &old = fLastMessage[boost::this_thread::get_id()];
908
909 if (str.str()==old)
910 return;
911 old = str.str();
912 */
913
914 fMsg.Update(str, severity);
915 }
916
917/*
918 void factStat(int64_t *stat, int len)
919 {
920 if (len!=7)
921 {
922 fMsg.Warn("factStat received unknown number of values.");
923 return;
924 }
925
926 vector<int64_t> data(1, g_maxMem);
927 data.insert(data.end(), stat, stat+len);
928
929 static vector<int64_t> last(8);
930 if (data==last)
931 return;
932 last = data;
933
934 fDimStatistics.Update(data);
935
936 // len ist die Laenge des arrays.
937 // array[4] enthaelt wieviele bytes im Buffer aktuell belegt sind; daran
938 // kannst Du pruefen, ob die 100MB voll sind ....
939
940 ostringstream str;
941 str
942 << "Wait=" << stat[0] << " "
943 << "Skip=" << stat[1] << " "
944 << "Del=" << stat[2] << " "
945 << "Tot=" << stat[3] << " "
946 << "Mem=" << stat[4] << "/" << g_maxMem << " "
947 << "Read=" << stat[5] << " "
948 << "Conn=" << stat[6];
949
950 fMsg.Info(str);
951 }
952 */
953
954 void factStatSend(const pair<Time,GUI_STAT> &stat)
955 {
956 fDimStatistics1.setData(&stat.second, sizeof(GUI_STAT));
957 fDimStatistics1.Update(stat.first);
958 }
959
960 void factStat(const GUI_STAT &stat)
961 {
962 fDimQueue1.post(make_pair(Time(), stat));
963 }
964
965 void factReportIncomplete(uint64_t rep)
966 {
967 fDimIncomplete.setQuality(1);
968 fDimIncomplete.Update(rep);
969 }
970
971 array<FAD::EventHeader, 40> fVecHeader;
972
973 template<typename T, class S>
974 array<T, 42> Compare(const S *vec, const T *t)
975 {
976 const int offset = reinterpret_cast<const char *>(t) - reinterpret_cast<const char *>(vec);
977
978 const T *min = NULL;
979 const T *val = NULL;
980 const T *max = NULL;
981
982 array<T, 42> arr;
983
984 // bool rc = true;
985 for (int i=0; i<40; i++)
986 {
987 const char *base = reinterpret_cast<const char*>(vec+i);
988 const T *ref = reinterpret_cast<const T*>(base+offset);
989
990 arr[i] = *ref;
991
992 if (gi_NumConnect[i]==0)
993 {
994 arr[i] = 0;
995 continue;
996 }
997
998 if (!val)
999 {
1000 min = ref;
1001 val = ref;
1002 max = ref;
1003 }
1004
1005 if (*ref<*min)
1006 min = ref;
1007
1008 if (*ref>*max)
1009 max = ref;
1010
1011 // if (*val!=*ref)
1012 // rc = false;
1013 }
1014
1015 arr[40] = val ? *min : 1;
1016 arr[41] = val ? *max : 0;
1017
1018 return arr;
1019 }
1020
1021 template<typename T>
1022 array<T, 42> CompareBits(const FAD::EventHeader *h, const T *t)
1023 {
1024 const int offset = reinterpret_cast<const char *>(t) - reinterpret_cast<const char *>(h);
1025
1026 T val = 0;
1027 T rc = 0;
1028
1029 array<T, 42> vec;
1030
1031 bool first = true;
1032
1033 for (int i=0; i<40; i++)
1034 {
1035 const char *base = reinterpret_cast<const char*>(&fVecHeader[i]);
1036 const T *ref = reinterpret_cast<const T*>(base+offset);
1037
1038 vec[i+2] = *ref;
1039
1040 if (gi_NumConnect[i]==0)
1041 {
1042 vec[i+2] = 0;
1043 continue;
1044 }
1045
1046 if (first)
1047 {
1048 first = false;
1049 val = *ref;
1050 rc = 0;
1051 }
1052
1053 rc |= val^*ref;
1054 }
1055
1056 vec[0] = rc;
1057 vec[1] = val;
1058
1059 return vec;
1060 }
1061
1062 template<typename T, size_t N>
1063 void Update(DimDescribedService &svc, const array<T, N> &data, const Time &t=Time(), int n=N)
1064 {
1065 svc.setData(const_cast<T*>(data.data()), sizeof(T)*n);
1066 svc.Update(t);
1067 }
1068
1069 template<typename T>
1070 void Print(const char *name, const pair<bool,array<T, 43>> &data)
1071 {
1072 cout << name << "|" << data.first << "|" << data.second[1] << "|" << data.second[0] << "<x<" << data.second[1] << ":";
1073 for (int i=0; i<40;i++)
1074 cout << " " << data.second[i+3];
1075 cout << endl;
1076 }
1077
1078 vector<uint> fNumConnected;
1079
1080 void procHeader(const tuple<Time,bool,FAD::EventHeader> &dat)
1081 {
1082 const Time &t = get<0>(dat);
1083 const bool changed = get<1>(dat);
1084 const FAD::EventHeader &h = get<2>(dat);
1085
1086 const FAD::EventHeader old = fVecHeader[h.Id()];
1087 fVecHeader[h.Id()] = h;
1088
1089 if (old.fVersion != h.fVersion || changed)
1090 {
1091 const array<uint16_t,42> ver = Compare(&fVecHeader[0], &fVecHeader[0].fVersion);
1092
1093 array<float,42> data;
1094 for (int i=0; i<42; i++)
1095 {
1096 ostringstream str;
1097 str << (ver[i]>>8) << '.' << (ver[i]&0xff);
1098 data[i] = stof(str.str());
1099 }
1100 Update(fDimFwVersion, data, t);
1101 }
1102
1103 if (old.fRunNumber != h.fRunNumber || changed)
1104 {
1105 const array<uint32_t,42> run = Compare(&fVecHeader[0], &fVecHeader[0].fRunNumber);
1106 fDimRunNumber.setData(&run[0], 42*sizeof(uint32_t));
1107 fDimRunNumber.Update(t);
1108 }
1109
1110 if (old.fTriggerGeneratorPrescaler != h.fTriggerGeneratorPrescaler || changed)
1111 {
1112 const array<uint16_t,42> pre = Compare(&fVecHeader[0], &fVecHeader[0].fTriggerGeneratorPrescaler);
1113 fDimPrescaler.setData(&pre[0], 42*sizeof(uint16_t));
1114 fDimPrescaler.Update(t);
1115 }
1116
1117 if (old.fDNA != h.fDNA || changed)
1118 {
1119 const array<uint64_t,42> dna = Compare(&fVecHeader[0], &fVecHeader[0].fDNA);
1120 Update(fDimDNA, dna, t, 40);
1121 }
1122
1123 if (old.fStatus != h.fStatus || changed)
1124 {
1125 const array<uint16_t,42> sts = CompareBits(&fVecHeader[0], &fVecHeader[0].fStatus);
1126 Update(fDimStatus, sts, t);
1127 }
1128
1129 if (memcmp(old.fDac, h.fDac, sizeof(h.fDac)) || changed)
1130 {
1131 array<uint16_t, FAD::kNumDac*42> dacs;
1132
1133 for (int i=0; i<FAD::kNumDac; i++)
1134 {
1135 const array<uint16_t, 42> dac = Compare(&fVecHeader[0], &fVecHeader[0].fDac[i]);
1136 memcpy(&dacs[i*42], &dac[0], sizeof(uint16_t)*42);
1137 }
1138
1139 Update(fDimDac, dacs, t);
1140 }
1141
1142 // -----------
1143
1144 static Time oldt(boost::date_time::neg_infin);
1145 Time newt;
1146
1147 if (newt>oldt+boost::posix_time::seconds(1))
1148 {
1149 oldt = newt;
1150
1151 // --- RefClock
1152
1153 const array<uint32_t,42> clk = Compare(&fVecHeader[0], &fVecHeader[0].fFreqRefClock);
1154 Update(fDimRefClock, clk, t);
1155
1156 // --- Temperatures
1157
1158 const array<int16_t,42> tmp[4] =
1159 {
1160 Compare(&fVecHeader[0], &fVecHeader[0].fTempDrs[0]), // 0-39:val, 40:min, 41:max
1161 Compare(&fVecHeader[0], &fVecHeader[0].fTempDrs[1]), // 0-39:val, 40:min, 41:max
1162 Compare(&fVecHeader[0], &fVecHeader[0].fTempDrs[2]), // 0-39:val, 40:min, 41:max
1163 Compare(&fVecHeader[0], &fVecHeader[0].fTempDrs[3]) // 0-39:val, 40:min, 41:max
1164 };
1165
1166 vector<int16_t> data;
1167 data.reserve(82);
1168 data.push_back(tmp[0][40]); // min: 0
1169 data.insert(data.end(), tmp[0].data(), tmp[0].data()+40); // val: 1-40
1170 data.push_back(tmp[0][41]); // max: 41
1171 data.insert(data.end(), tmp[0].data(), tmp[0].data()+40); // val: 42-81
1172
1173 for (int j=1; j<=3; j++)
1174 {
1175 const array<int16_t,42> &ref = tmp[j];
1176
1177 // Gloabl min
1178 if (ref[40]<data[0]) // 40=min
1179 data[0] = ref[40];
1180
1181 // Global max
1182 if (ref[41]>data[41]) // 41=max
1183 data[41] = ref[41];
1184
1185 for (int i=0; i<40; i++)
1186 {
1187 // min per board
1188 if (ref[i]<data[i+1]) // data: 1-40
1189 data[i+1] = ref[i]; // ref: 0-39
1190
1191 // max per board
1192 if (ref[i]>data[i+42]) // data: 42-81
1193 data[i+42] = ref[i]; // ref: 0-39
1194 }
1195 }
1196
1197 vector<float> deg(82); // 0: global min, 1-40: min
1198 for (int i=0; i<82; i++) // 41: global max, 42-81: max
1199 deg[i] = data[i]/16.;
1200
1201 fDimTemperature.setData(deg.data(), 82*sizeof(float));
1202 fDimTemperature.Update(t);
1203 }
1204 }
1205
1206 void debugHead(const FAD::EventHeader &h)
1207 {
1208 const uint16_t id = h.Id();
1209 if (id>39)
1210 return;
1211
1212 if (fNumConnected.size()!=40)
1213 fNumConnected.resize(40);
1214
1215 const vector<uint> con(gi_NumConnect, gi_NumConnect+40);
1216
1217 const bool changed = con!=fNumConnected || !IsThreadRunning();
1218
1219 fNumConnected = con;
1220
1221 fDimQueue2.post(make_tuple(Time(), changed, h));
1222 }
1223};
1224
1225EventBuilderWrapper *EventBuilderWrapper::This = 0;
1226
1227// ----------- Event builder callbacks implementation ---------------
1228bool runOpen(const shared_ptr<EVT_CTRL2> &evt)
1229{
1230 return EventBuilderWrapper::This->runOpen(evt);
1231}
1232
1233bool runWrite(const shared_ptr<EVT_CTRL2> &evt)
1234{
1235 return EventBuilderWrapper::This->runWrite(evt);
1236}
1237
1238void runClose()
1239{
1240 EventBuilderWrapper::This->runClose();
1241}
1242
1243int eventCheck(const shared_ptr<EVT_CTRL2> &evt)
1244{
1245 return EventBuilderWrapper::This->eventCheck(evt);
1246}
1247
1248void gotNewRun(RUN_CTRL2 &run)
1249{
1250 EventBuilderWrapper::This->gotNewRun(run);
1251}
1252
1253void runFinished()
1254{
1255 EventBuilderWrapper::This->runFinished();
1256}
1257
1258void applyCalib(const shared_ptr<EVT_CTRL2> &evt)
1259{
1260 EventBuilderWrapper::This->applyCalib(evt);
1261}
1262
1263void factOut(int severity, const char *message)
1264{
1265 EventBuilderWrapper::This->factOut(severity, message);
1266}
1267
1268void factStat(GUI_STAT stat)
1269{
1270 EventBuilderWrapper::This->factStat(stat);
1271}
1272
1273void factReportIncomplete(uint64_t rep)
1274{
1275 EventBuilderWrapper::This->factReportIncomplete(rep);
1276}
1277
1278// ------
1279
1280void debugHead(void *buf)
1281{
1282 const FAD::EventHeader &h = *reinterpret_cast<FAD::EventHeader*>(buf);
1283 EventBuilderWrapper::This->debugHead(h);
1284}
1285
1286#endif
Note: See TracBrowser for help on using the repository browser.