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

Last change on this file since 16329 was 16108, checked in by tbretz, 12 years ago
Added a new run-close condition for the case an invalid event was received.
File size: 40.0 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 bool 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 return false;
643 }
644
645 if (beg->fRunNumber != ptr->fRunNumber)
646 {
647 fMsg.Error("Inconsistent run number detected.... closing run.");
648 return false;
649 }
650
651 /*
652 if (beg->fVersion != ptr->fVersion)
653 {
654 Error("Inconsist firmware version detected.... closing run.");
655 CloseRunFile(runNr, 0, 0);
656 break;
657 }
658 */
659 if (beg->fEventCounter != ptr->fEventCounter)
660 {
661 fMsg.Error("Inconsistent FAD event number detected.... closing run.");
662 return false;
663 }
664
665 if (beg->fTriggerCounter != ptr->fTriggerCounter)
666 {
667 fMsg.Error("Inconsistent FTM trigger number detected.... closing run.");
668 return false;
669 }
670
671 if (beg->fAdcClockPhaseShift != ptr->fAdcClockPhaseShift)
672 {
673 fMsg.Error("Inconsistent phase shift detected.... closing run.");
674 return false;
675 }
676
677 if (memcmp(beg->fDac, ptr->fDac, sizeof(beg->fDac)))
678 {
679 fMsg.Error("Inconsistent DAC values detected.... closing run.");
680 return false;
681 }
682
683 if (beg->fTriggerType != ptr->fTriggerType)
684 {
685 fMsg.Error("Inconsistent trigger type detected.... closing run.");
686 return false;
687 }
688 }
689
690 // check REFCLK_frequency
691 // check consistency with command configuration
692 // how to log errors?
693 // need gotNewRun/closedRun to know it is finished
694
695 return true;
696 }
697
698 void applyCalib(const shared_ptr<EVT_CTRL2> &evt)
699 {
700 const PEVNT_HEADER *fadhd = evt->FADhead.get();
701 const EVENT *event = evt->fEvent;
702
703 // Currently we send any event no matter what its trigger id is...
704 // To be changed.
705 static Time oldt(boost::date_time::neg_infin);
706 Time newt;
707
708 static int skip = 0;
709
710 // FIXME: Only send events if the have newer run-numbers
711 if (newt<oldt+boost::posix_time::milliseconds(skip>0 ? 100 : 1000))
712 return;
713 oldt = newt;
714
715 // Workaround to find a valid header.....
716 const FAD::EventHeader *beg = reinterpret_cast<const FAD::EventHeader*>(fadhd);
717 const FAD::EventHeader *end = reinterpret_cast<const FAD::EventHeader*>(fadhd)+40;
718
719 // FIMXE: Compare with target configuration
720 const FAD::EventHeader *ptr=beg;
721 for (; ptr!=end; ptr++)
722 {
723 if (ptr->fStartDelimiter!=0)
724 break;
725 }
726 if (ptr==end)
727 return;
728
729
730 vector<char> data(sizeof(EVENT)+event->Roi*sizeof(float)*(1440+160));
731 memcpy(data.data(), event, sizeof(EVENT));
732
733 float *vec = reinterpret_cast<float*>(data.data()+sizeof(EVENT));
734
735 evt->runCtrl->calib->Apply(vec, event->Adc_Data, event->StartPix, event->Roi);
736 DrsCalibrate::RemoveSpikes(vec, event->Roi);
737
738 vector<float> data2(1440*4); // Mean, RMS, Max, Pos
739 const double max = DrsCalibrate::GetPixelStats(data2.data(), vec, event->Roi);
740
741 // Maximum above roughly 5pe
742 if (ptr->IsTriggerPhys() && max<100 && skip<10)
743 {
744 skip++;
745 return;
746 }
747
748 skip = 0;
749
750 fDimRawData.setQuality(ptr->fTriggerType);
751 fDimRawData.Update(data);
752
753 fDimEventData.setQuality(ptr->fTriggerType);
754 fDimEventData.Update(data2);
755
756 }
757
758 /*
759 void SendFeedbackData(PEVNT_HEADER *fadhd, EVENT *event)
760 {
761 if (!DataCalib::IsValid())
762 return;
763
764 // Workaround to find a valid header.....
765 const FAD::EventHeader *beg = reinterpret_cast<FAD::EventHeader*>(fadhd);
766 const FAD::EventHeader *end = reinterpret_cast<FAD::EventHeader*>(fadhd)+40;
767
768 // FIMXE: Compare with target configuration
769
770 const FAD::EventHeader *ptr=beg;
771 for (; ptr<end; ptr++)
772 {
773 if (ptr->fStartDelimiter!=0)
774 break;
775 }
776
777 if (ptr==end)
778 return;
779
780 if (!ptr->HasTriggerLPext() && !ptr->HasTriggerLPint())
781 return;
782
783 vector<float> data(event->Roi*1440);
784 DataCalib::Apply(data.data(), event->Adc_Data, event->StartPix, event->Roi);
785
786 DrsCalibrate::RemoveSpikes(data.data(), event->Roi);
787
788 vector<float> data2(1440); // Mean, RMS, Max, Pos, first, last
789 DrsCalibrate::GetPixelMax(data2.data(), data.data(), event->Roi, 0, event->Roi-1);
790
791 fDimFeedbackData.Update(data2);
792 }
793 */
794
795 bool IsRunWaiting()// const
796 {
797 const lock_guard<mutex> lock(mtx_newrun);
798 return fExpectedRuns.find(fRunNumber-1)!=fExpectedRuns.end();
799 }
800
801 uint32_t GetRunNumber() const
802 {
803 return fRunNumber;
804 }
805
806 /*
807 bool IsRunFileOpen()
808 {
809 return fLastOpened==fRunNumber-1;
810 }*/
811
812 bool IncreaseRunNumber(uint32_t run)
813 {
814 if (!InitRunNumber())
815 return false;
816
817 if (run<fRunNumber)
818 {
819 ostringstream msg;
820 msg <<
821 "Run number " << run << " smaller than next available "
822 "run number " << fRunNumber << " in " << fPath << " [" << fNightAsInt << "]";
823 fMsg.Error(msg);
824 return false;
825 }
826
827 fRunNumber = run;
828
829 return true;
830 }
831
832 void gotNewRun(RUN_CTRL2 &run)
833 {
834 // This is to secure iteration over fExpectedRuns
835 const lock_guard<mutex> lock(mtx_newrun);
836
837 map<uint32_t,FAD::RunDescription>::const_iterator it = fExpectedRuns.begin();
838 while (it!=fExpectedRuns.end())
839 {
840 if (it->first<run.runId)
841 {
842 ostringstream str;
843 str << "runOpen - Missed run " << it->first << ".";
844 fMsg.Info(str);
845
846 // Increase the iterator first, it becomes invalid with the next call
847 const auto is = it++;
848 fExpectedRuns.erase(is);
849 continue;
850 }
851
852 if (it->first==run.runId)
853 break;
854
855 it++;
856 }
857
858 if (it==fExpectedRuns.end())
859 {
860 ostringstream str;
861 str << "runOpen - Run " << run.runId << " wasn't expected (maybe manual triggers)";
862 fMsg.Warn(str);
863
864 // This is not ideal, but the best we can do
865 run.night = fNightAsInt;
866
867 return;
868 }
869
870 const FAD::RunDescription &conf = it->second;
871
872 run.runType = conf.name;
873 run.maxEvt = conf.maxevt;
874 run.closeTime = conf.maxtime + run.openTime;
875 run.night = conf.night;
876
877 fExpectedRuns.erase(it);
878
879 // Now signal the fadctrl (configuration process that a run is in progress)
880 // Maybe this could be done earlier, but we are talking about a
881 // negligible time scale here.
882 fRunInProgress = run.runId;
883 }
884
885 void runFinished()
886 {
887 // This is called when the last event of a run (run time exceeded or
888 // max number of events exceeded) has been received.
889 fRunInProgress = -1;
890 }
891
892 //map<boost::thread::id, string> fLastMessage;
893
894 void factOut(int severity, const char *message)
895 {
896 ostringstream str;
897 str << "EventBuilder: " << message;
898
899 /*
900 string &old = fLastMessage[boost::this_thread::get_id()];
901
902 if (str.str()==old)
903 return;
904 old = str.str();
905 */
906
907 fMsg.Update(str, severity);
908 }
909
910/*
911 void factStat(int64_t *stat, int len)
912 {
913 if (len!=7)
914 {
915 fMsg.Warn("factStat received unknown number of values.");
916 return;
917 }
918
919 vector<int64_t> data(1, g_maxMem);
920 data.insert(data.end(), stat, stat+len);
921
922 static vector<int64_t> last(8);
923 if (data==last)
924 return;
925 last = data;
926
927 fDimStatistics.Update(data);
928
929 // len ist die Laenge des arrays.
930 // array[4] enthaelt wieviele bytes im Buffer aktuell belegt sind; daran
931 // kannst Du pruefen, ob die 100MB voll sind ....
932
933 ostringstream str;
934 str
935 << "Wait=" << stat[0] << " "
936 << "Skip=" << stat[1] << " "
937 << "Del=" << stat[2] << " "
938 << "Tot=" << stat[3] << " "
939 << "Mem=" << stat[4] << "/" << g_maxMem << " "
940 << "Read=" << stat[5] << " "
941 << "Conn=" << stat[6];
942
943 fMsg.Info(str);
944 }
945 */
946
947 void factStatSend(const pair<Time,GUI_STAT> &stat)
948 {
949 fDimStatistics1.setData(&stat.second, sizeof(GUI_STAT));
950 fDimStatistics1.Update(stat.first);
951 }
952
953 void factStat(const GUI_STAT &stat)
954 {
955 fDimQueue1.post(make_pair(Time(), stat));
956 }
957
958 void factReportIncomplete(uint64_t rep)
959 {
960 fDimIncomplete.setQuality(1);
961 fDimIncomplete.Update(rep);
962 }
963
964 array<FAD::EventHeader, 40> fVecHeader;
965
966 template<typename T, class S>
967 array<T, 42> Compare(const S *vec, const T *t)
968 {
969 const int offset = reinterpret_cast<const char *>(t) - reinterpret_cast<const char *>(vec);
970
971 const T *min = NULL;
972 const T *val = NULL;
973 const T *max = NULL;
974
975 array<T, 42> arr;
976
977 // bool rc = true;
978 for (int i=0; i<40; i++)
979 {
980 const char *base = reinterpret_cast<const char*>(vec+i);
981 const T *ref = reinterpret_cast<const T*>(base+offset);
982
983 arr[i] = *ref;
984
985 if (gi_NumConnect[i]==0)
986 {
987 arr[i] = 0;
988 continue;
989 }
990
991 if (!val)
992 {
993 min = ref;
994 val = ref;
995 max = ref;
996 }
997
998 if (*ref<*min)
999 min = ref;
1000
1001 if (*ref>*max)
1002 max = ref;
1003
1004 // if (*val!=*ref)
1005 // rc = false;
1006 }
1007
1008 arr[40] = val ? *min : 1;
1009 arr[41] = val ? *max : 0;
1010
1011 return arr;
1012 }
1013
1014 template<typename T>
1015 array<T, 42> CompareBits(const FAD::EventHeader *h, const T *t)
1016 {
1017 const int offset = reinterpret_cast<const char *>(t) - reinterpret_cast<const char *>(h);
1018
1019 T val = 0;
1020 T rc = 0;
1021
1022 array<T, 42> vec;
1023
1024 bool first = true;
1025
1026 for (int i=0; i<40; i++)
1027 {
1028 const char *base = reinterpret_cast<const char*>(&fVecHeader[i]);
1029 const T *ref = reinterpret_cast<const T*>(base+offset);
1030
1031 vec[i+2] = *ref;
1032
1033 if (gi_NumConnect[i]==0)
1034 {
1035 vec[i+2] = 0;
1036 continue;
1037 }
1038
1039 if (first)
1040 {
1041 first = false;
1042 val = *ref;
1043 rc = 0;
1044 }
1045
1046 rc |= val^*ref;
1047 }
1048
1049 vec[0] = rc;
1050 vec[1] = val;
1051
1052 return vec;
1053 }
1054
1055 template<typename T, size_t N>
1056 void Update(DimDescribedService &svc, const array<T, N> &data, const Time &t=Time(), int n=N)
1057 {
1058 svc.setData(const_cast<T*>(data.data()), sizeof(T)*n);
1059 svc.Update(t);
1060 }
1061
1062 template<typename T>
1063 void Print(const char *name, const pair<bool,array<T, 43>> &data)
1064 {
1065 cout << name << "|" << data.first << "|" << data.second[1] << "|" << data.second[0] << "<x<" << data.second[1] << ":";
1066 for (int i=0; i<40;i++)
1067 cout << " " << data.second[i+3];
1068 cout << endl;
1069 }
1070
1071 vector<uint> fNumConnected;
1072
1073 void procHeader(const tuple<Time,bool,FAD::EventHeader> &dat)
1074 {
1075 const Time &t = get<0>(dat);
1076 const bool changed = get<1>(dat);
1077 const FAD::EventHeader &h = get<2>(dat);
1078
1079 const FAD::EventHeader old = fVecHeader[h.Id()];
1080 fVecHeader[h.Id()] = h;
1081
1082 if (old.fVersion != h.fVersion || changed)
1083 {
1084 const array<uint16_t,42> ver = Compare(&fVecHeader[0], &fVecHeader[0].fVersion);
1085
1086 array<float,42> data;
1087 for (int i=0; i<42; i++)
1088 {
1089 ostringstream str;
1090 str << (ver[i]>>8) << '.' << (ver[i]&0xff);
1091 data[i] = stof(str.str());
1092 }
1093 Update(fDimFwVersion, data, t);
1094 }
1095
1096 if (old.fRunNumber != h.fRunNumber || changed)
1097 {
1098 const array<uint32_t,42> run = Compare(&fVecHeader[0], &fVecHeader[0].fRunNumber);
1099 fDimRunNumber.setData(&run[0], 42*sizeof(uint32_t));
1100 fDimRunNumber.Update(t);
1101 }
1102
1103 if (old.fTriggerGeneratorPrescaler != h.fTriggerGeneratorPrescaler || changed)
1104 {
1105 const array<uint16_t,42> pre = Compare(&fVecHeader[0], &fVecHeader[0].fTriggerGeneratorPrescaler);
1106 fDimPrescaler.setData(&pre[0], 42*sizeof(uint16_t));
1107 fDimPrescaler.Update(t);
1108 }
1109
1110 if (old.fDNA != h.fDNA || changed)
1111 {
1112 const array<uint64_t,42> dna = Compare(&fVecHeader[0], &fVecHeader[0].fDNA);
1113 Update(fDimDNA, dna, t, 40);
1114 }
1115
1116 if (old.fStatus != h.fStatus || changed)
1117 {
1118 const array<uint16_t,42> sts = CompareBits(&fVecHeader[0], &fVecHeader[0].fStatus);
1119 Update(fDimStatus, sts, t);
1120 }
1121
1122 if (memcmp(old.fDac, h.fDac, sizeof(h.fDac)) || changed)
1123 {
1124 array<uint16_t, FAD::kNumDac*42> dacs;
1125
1126 for (int i=0; i<FAD::kNumDac; i++)
1127 {
1128 const array<uint16_t, 42> dac = Compare(&fVecHeader[0], &fVecHeader[0].fDac[i]);
1129 memcpy(&dacs[i*42], &dac[0], sizeof(uint16_t)*42);
1130 }
1131
1132 Update(fDimDac, dacs, t);
1133 }
1134
1135 // -----------
1136
1137 static Time oldt(boost::date_time::neg_infin);
1138 Time newt;
1139
1140 if (newt>oldt+boost::posix_time::seconds(1))
1141 {
1142 oldt = newt;
1143
1144 // --- RefClock
1145
1146 const array<uint32_t,42> clk = Compare(&fVecHeader[0], &fVecHeader[0].fFreqRefClock);
1147 Update(fDimRefClock, clk, t);
1148
1149 // --- Temperatures
1150
1151 const array<int16_t,42> tmp[4] =
1152 {
1153 Compare(&fVecHeader[0], &fVecHeader[0].fTempDrs[0]), // 0-39:val, 40:min, 41:max
1154 Compare(&fVecHeader[0], &fVecHeader[0].fTempDrs[1]), // 0-39:val, 40:min, 41:max
1155 Compare(&fVecHeader[0], &fVecHeader[0].fTempDrs[2]), // 0-39:val, 40:min, 41:max
1156 Compare(&fVecHeader[0], &fVecHeader[0].fTempDrs[3]) // 0-39:val, 40:min, 41:max
1157 };
1158
1159 vector<int16_t> data;
1160 data.reserve(82);
1161 data.push_back(tmp[0][40]); // min: 0
1162 data.insert(data.end(), tmp[0].data(), tmp[0].data()+40); // val: 1-40
1163 data.push_back(tmp[0][41]); // max: 41
1164 data.insert(data.end(), tmp[0].data(), tmp[0].data()+40); // val: 42-81
1165
1166 for (int j=1; j<=3; j++)
1167 {
1168 const array<int16_t,42> &ref = tmp[j];
1169
1170 // Gloabl min
1171 if (ref[40]<data[0]) // 40=min
1172 data[0] = ref[40];
1173
1174 // Global max
1175 if (ref[41]>data[41]) // 41=max
1176 data[41] = ref[41];
1177
1178 for (int i=0; i<40; i++)
1179 {
1180 // min per board
1181 if (ref[i]<data[i+1]) // data: 1-40
1182 data[i+1] = ref[i]; // ref: 0-39
1183
1184 // max per board
1185 if (ref[i]>data[i+42]) // data: 42-81
1186 data[i+42] = ref[i]; // ref: 0-39
1187 }
1188 }
1189
1190 vector<float> deg(82); // 0: global min, 1-40: min
1191 for (int i=0; i<82; i++) // 41: global max, 42-81: max
1192 deg[i] = data[i]/16.;
1193
1194 fDimTemperature.setData(deg.data(), 82*sizeof(float));
1195 fDimTemperature.Update(t);
1196 }
1197 }
1198
1199 void debugHead(const FAD::EventHeader &h)
1200 {
1201 const uint16_t id = h.Id();
1202 if (id>39)
1203 return;
1204
1205 if (fNumConnected.size()!=40)
1206 fNumConnected.resize(40);
1207
1208 const vector<uint> con(gi_NumConnect, gi_NumConnect+40);
1209
1210 const bool changed = con!=fNumConnected || !IsThreadRunning();
1211
1212 fNumConnected = con;
1213
1214 fDimQueue2.post(make_tuple(Time(), changed, h));
1215 }
1216};
1217
1218EventBuilderWrapper *EventBuilderWrapper::This = 0;
1219
1220// ----------- Event builder callbacks implementation ---------------
1221bool runOpen(const shared_ptr<EVT_CTRL2> &evt)
1222{
1223 return EventBuilderWrapper::This->runOpen(evt);
1224}
1225
1226bool runWrite(const shared_ptr<EVT_CTRL2> &evt)
1227{
1228 return EventBuilderWrapper::This->runWrite(evt);
1229}
1230
1231void runClose()
1232{
1233 EventBuilderWrapper::This->runClose();
1234}
1235
1236bool eventCheck(const shared_ptr<EVT_CTRL2> &evt)
1237{
1238 return EventBuilderWrapper::This->eventCheck(evt);
1239}
1240
1241void gotNewRun(RUN_CTRL2 &run)
1242{
1243 EventBuilderWrapper::This->gotNewRun(run);
1244}
1245
1246void runFinished()
1247{
1248 EventBuilderWrapper::This->runFinished();
1249}
1250
1251void applyCalib(const shared_ptr<EVT_CTRL2> &evt)
1252{
1253 EventBuilderWrapper::This->applyCalib(evt);
1254}
1255
1256void factOut(int severity, const char *message)
1257{
1258 EventBuilderWrapper::This->factOut(severity, message);
1259}
1260
1261void factStat(GUI_STAT stat)
1262{
1263 EventBuilderWrapper::This->factStat(stat);
1264}
1265
1266void factReportIncomplete(uint64_t rep)
1267{
1268 EventBuilderWrapper::This->factReportIncomplete(rep);
1269}
1270
1271// ------
1272
1273void debugHead(void *buf)
1274{
1275 const FAD::EventHeader &h = *reinterpret_cast<FAD::EventHeader*>(buf);
1276 EventBuilderWrapper::This->debugHead(h);
1277}
1278
1279#endif
Note: See TracBrowser for help on using the repository browser.