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

Last change on this file since 11264 was 11247, checked in by tbretz, 13 years ago
Made destructors virtual.
File size: 46.0 KB
Line 
1#ifndef FACT_EventBuilderWrapper
2#define FACT_EventBuilderWrapper
3
4/*
5#if BOOST_VERSION < 104400
6#if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 4))
7#undef BOOST_HAS_RVALUE_REFS
8#endif
9#endif
10#include <boost/thread.hpp>
11
12using namespace std;
13*/
14
15#include <boost/date_time/posix_time/posix_time_types.hpp>
16
17#include <CCfits/CCfits>
18
19#include "EventBuilder.h"
20
21extern "C" {
22 extern void StartEvtBuild();
23 extern int CloseRunFile(uint32_t runId, uint32_t closeTime);
24}
25
26namespace ba = boost::asio;
27namespace bs = boost::system;
28
29using ba::ip::tcp;
30
31class DataFileImp
32{
33 uint32_t fRunId;
34
35public:
36 DataFileImp(uint32_t id) : fRunId(id) { }
37 virtual ~DataFileImp() { }
38
39 virtual bool OpenFile(RUN_HEAD* h) = 0;
40 virtual bool Write(EVENT *) = 0;
41 virtual bool Close(RUN_TAIL * = 0) = 0;
42
43 uint32_t GetRunId() const { return fRunId; }
44
45 // --------------------------------------------------------------------------
46 //
47 //! This creates an appropriate file name for a particular run number and type
48 //! @param runNumber the run number for which a filename is to be created
49 //! @param runType an int describing the kind of run. 0=Data, 1=Pedestal, 2=Calibration, 3=Calibrated data
50 //! @param extension a string containing the extension to be appened to the file name
51 //
52 string FormFileName(uint32_t runType, string extension)
53 {
54 //TODO where am I supposed to get the base directory from ?
55 //TODO also, for creating subsequent directories, should I use the functions from the dataLogger ?
56 string baseDirectory = "./Run";
57
58 ostringstream result;
59// result << baseDirectory;
60// result << Time::fmt("/%Y/%m/%d/") << (Time() - boost::posix_time::time_duration(12,0,0));
61 result << setfill('0') << setw(8) << fRunId;
62 result << ".001_";
63 switch (runType)
64 {
65 case -1:
66 result << 'T';
67 break;
68 case 0:
69 result << 'D';
70 break;
71 case 1:
72 result << 'P';
73 break;
74 case 2:
75 result << 'C';
76 break;
77 case 3:
78 result << 'N';
79 break;
80 default:
81 result << runType;
82 };
83 result << "." << extension;
84
85 return result.str();
86 }
87};
88
89class DataFileNone : public DataFileImp
90{
91public:
92 DataFileNone(uint32_t id) : DataFileImp(id) { }
93
94 bool OpenFile(RUN_HEAD* h)
95 {
96 cout << "OPEN_FILE #" << GetRunId() << " (" << this << ")" << endl;
97 cout << " Ver= " << h->Version << endl;
98 cout << " Typ= " << h->RunType << endl;
99 cout << " Nb = " << h->NBoard << endl;
100 cout << " Np = " << h->NPix << endl;
101 cout << " NTm= " << h->NTm << endl;
102 cout << " roi= " << h->Nroi << endl;
103
104 return true;
105 }
106 bool Write(EVENT *)
107 {
108 return true;
109 }
110 bool Close(RUN_TAIL * = 0)
111 {
112 cout << "CLOSE FILE #" << GetRunId() << " (" << this << ")" << endl;
113 return true;
114 }
115};
116
117class DataFileDebug : public DataFileNone
118{
119public:
120 DataFileDebug(uint32_t id) : DataFileNone(id) { }
121
122 bool Write(EVENT *e)
123 {
124 cout << "WRITE_EVENT #" << GetRunId() << " (" << e->EventNum << ")" << endl;
125 cout << " Typ=" << e->TriggerType << endl;
126 cout << " roi=" << e->Roi << endl;
127 cout << " trg=" << e->SoftTrig << endl;
128 cout << " tim=" << e->PCTime << endl;
129
130 return true;
131 }
132};
133
134#include "FAD.h"
135
136class DataFileRaw : public DataFileImp
137{
138 ofstream fOut;
139
140 off_t fPosTail;
141
142 uint32_t fCounter;
143
144
145 // WRITE uint32_t 0xFAC77e1e (FACT Tele)
146 // ===
147 // WRITE uint32_t TYPE(>0) == 1
148 // WRITE uint32_t ID(>0) == 0
149 // WRITE uint32_t VERSION(>0) == 1
150 // WRITE uint32_t LENGTH
151 // -
152 // WRITE uint32_t TELESCOPE ID
153 // WRITE uint32_t RUNID
154 // ===
155 // WRITE uint32_t TYPE(>0) == 2
156 // WRITE uint32_t ID(>0) == 0
157 // WRITE uint32_t VERSION(>0) == 1
158 // WRITE uint32_t LENGTH
159 // -
160 // WRITE HEADER
161 // ===
162 // [ 40 TIMES
163 // WRITE uint32_t TYPE(>0) == 3
164 // WRITE uint32_t ID(>0) == 0..39
165 // WRITE uint32_t VERSION(>0) == 1
166 // WRITE uint32_t LENGTH
167 // -
168 // WRITE BOARD-HEADER
169 // ]
170 // ===
171 // WRITE uint32_t TYPE(>0) == 4
172 // WRITE uint32_t ID(>0) == 0
173 // WRITE uint32_t VERSION(>0) == 1
174 // WRITE uint32_t LENGTH
175 // -
176 // WRITE FOOTER (empty)
177 // ===
178 // [ N times
179 // WRITE uint32_t TYPE(>0) == 10
180 // WRITE uint32_t ID(>0) == counter
181 // WRITE uint32_t VERSION(>0) == 1
182 // WRITE uint32_t LENGTH HEADER
183 // -
184 // WRITE HEADER+DATA
185 // ]
186 // ===
187 // WRITE uint32_t TYPE ==0
188 // WRITE uint32_t VERSION==0
189 // WRITE uint32_t LENGTH ==0
190 // ===
191 // Go back and write footer
192
193public:
194 DataFileRaw(uint32_t id) : DataFileImp(id) { }
195 ~DataFileRaw() { Close(); }
196
197 void WriteBlockHeader(uint32_t type, uint32_t ver, uint32_t cnt, uint32_t len)
198 {
199 const uint32_t val[4] = { type, ver, cnt, len };
200
201 fOut.write(reinterpret_cast<const char*>(val), sizeof(val));
202 }
203
204 template<typename T>
205 void WriteValue(const T &t)
206 {
207 fOut.write(reinterpret_cast<const char*>(&t), sizeof(T));
208 }
209
210 enum
211 {
212 kEndOfFile = 0,
213 kIdentifier = 1,
214 kRunHeader,
215 kBoardHeader,
216 kRunSummary,
217 kEvent,
218 };
219
220 virtual bool OpenFile(RUN_HEAD *h)
221 {
222 const string name = FormFileName(h->RunType, "bin");
223
224 errno = 0;
225 fOut.open(name.c_str(), ios_base::out);
226 if (!fOut)
227 {
228 //ostringstream str;
229 //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
230 //Error(str);
231
232 return false;
233 }
234
235 fCounter = 0;
236
237 static uint32_t FACT = 0xFAC77e1e;
238
239 fOut.write(reinterpret_cast<char*>(&FACT), 4);
240
241 WriteBlockHeader(kIdentifier, 1, 0, 8);
242 WriteValue(uint32_t(0));
243 WriteValue(GetRunId());
244
245 WriteBlockHeader(kRunHeader, 1, 0, sizeof(RUN_HEAD)-sizeof(PEVNT_HEADER*));
246 fOut.write(reinterpret_cast<char*>(h), sizeof(RUN_HEAD)-sizeof(PEVNT_HEADER*));
247
248 for (int i=0; i<40; i++)
249 {
250 WriteBlockHeader(kBoardHeader, 1, i, sizeof(PEVNT_HEADER));
251 fOut.write(reinterpret_cast<char*>(h->FADhead+i), sizeof(PEVNT_HEADER));
252 }
253
254 // FIXME: Split this
255 const vector<char> block(sizeof(uint32_t)+sizeof(RUN_TAIL));
256 WriteBlockHeader(kRunSummary, 1, 0, block.size());
257
258 fPosTail = fOut.tellp();
259 fOut.write(block.data(), block.size());
260
261 if (!fOut)
262 {
263 //ostringstream str;
264 //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
265 //Error(str);
266
267 return false;
268 }
269
270 return true;
271 }
272 virtual bool Write(EVENT *evt)
273 {
274 const int sh = sizeof(EVENT)-2 + NPIX*evt->Roi*2;
275
276 WriteBlockHeader(kEvent, 1, fCounter++, sh);
277 fOut.write(reinterpret_cast<char*>(evt)+2, sh);
278 return true;
279 }
280 virtual bool Close(RUN_TAIL *tail= 0)
281 {
282 WriteBlockHeader(kEndOfFile, 0, 0, 0);
283
284 if (tail)
285 {
286 fOut.seekp(fPosTail);
287
288 WriteValue(uint32_t(1));
289 fOut.write(reinterpret_cast<char*>(tail), sizeof(RUN_TAIL));
290 }
291
292 if (!fOut)
293 {
294 //ostringstream str;
295 //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
296 //Error(str);
297
298 return false;
299 }
300
301 fOut.close();
302
303 if (!fOut)
304 {
305 //ostringstream str;
306 //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
307 //Error(str);
308
309 return false;
310 }
311
312 return true;
313 }
314};
315
316#ifdef HAS_FITS
317class DataFileFits : public DataFileImp
318{
319 CCfits::FITS* fFile; /// The pointer to the CCfits FITS file
320 CCfits::Table* fTable; /// The pointer to the CCfits binary table
321
322 uint64_t fNumRows; ///the number of rows that have been written already to the FITS file.
323
324public:
325 DataFileFits(uint32_t runid) : DataFileImp(runid), fFile(0)
326 {
327 }
328
329 // --------------------------------------------------------------------------
330 //
331 //! Default destructor
332 //! The Fits file SHOULD have been closed already, otherwise the informations
333 //! related to the RUN_TAIL will NOT be written to the file.
334 //
335 ~DataFileFits() { Close(); }
336
337 // --------------------------------------------------------------------------
338 //
339 //! Add a new column to the vectors storing the column data.
340 //! @param names the vector of string storing the columns names
341 //! @param types the vector of string storing the FITS data format
342 //! @param numElems the number of elements in this column
343 //! @param type the char describing the FITS data format
344 //! @param name the name of the particular column to be added.
345 //
346 inline void AddColumnEntry(vector<string>& names, vector<string>& types, int numElems, char type, string name)
347 {
348 names.push_back(name);
349
350 ostringstream str;
351 if (numElems != 1)
352 str << numElems;
353 str << type;
354 types.push_back(str.str());
355 }
356
357 // --------------------------------------------------------------------------
358 //
359 //! Writes a single header key entry
360 //! @param name the name of the key
361 //! @param value its value
362 //! @param comment the comment associated to that key
363 //
364 //FIXME this function is a duplicate from the class Fits. should we try to merge it ?
365 template <typename T>
366 void WriteKey(const string &name, const T &value, const string &comment)
367 {
368 try
369 {
370 fTable->addKey(name, value, comment);
371 }
372 catch (CCfits::FitsException e)
373 {
374 ostringstream str;
375 str << "Could not add header key ";
376 //TODO pipe the error message somewhere
377 }
378 }
379
380 template <typename T>
381 void WriteKey(const string &name, const int idx, const T &value, const string &comment)
382 {
383 ostringstream str;
384 str << name << idx;
385
386 WriteKey(str.str(), value, comment);
387 }
388
389 // --------------------------------------------------------------------------
390 //
391 //! DataFileFits constructor. This is the one that should be used, not the default one (parameter-less)
392 //! @param runid This parameter should probably be removed. I first thought it was the run number, but apparently it is not
393 //! @param h a pointer to the RUN_HEAD structure that contains the informations relative to this run
394 //
395 bool OpenFile(RUN_HEAD* h)
396 {
397 //Form filename, based on runid and run-type
398 const string fileName = FormFileName(h->RunType, "fits");
399
400 //create the FITS object
401 try
402 {
403 fFile = new CCfits::FITS(fileName, CCfits::RWmode::Write);
404 }
405 catch (CCfits::FitsException e)
406 {
407 ostringstream str;
408 str << "Could not open FITS file " << fileName << " reason: " << e.message();
409 //TODO display the message somewhere
410
411 return false;
412 }
413
414 //create columns according to header
415 ostringstream arrayTypes;
416
417 // uint32_t EventNum ; // EventNumber as from FTM
418 // uint16_t TriggerType ; // Trigger Type from FTM
419 // uint32_t SoftTrig ; // SoftTrigger Info (TBD)
420 // uint32_t PCTime ; // when did event start to arrive at PC
421 // uint32_t BoardTime[NBOARDS];//
422 // int16_t StartPix[NPIX]; // First Channel per Pixel (Pixels sorted according Software ID) ; -1 if not filled
423 // int16_t StartTM[NTMARK]; // First Channel for TimeMark (sorted Hardware ID) ; -1 if not filled
424 // uint16_t Adc_Data[]; // final length defined by malloc ....
425
426 vector<string> colNames;
427 vector<string> dataTypes;
428 AddColumnEntry(colNames, dataTypes, 1, 'V', "EventNum");
429 AddColumnEntry(colNames, dataTypes, 1, 'U', "TriggerType");
430 AddColumnEntry(colNames, dataTypes, 1, 'V', "SoftTrig");
431 AddColumnEntry(colNames, dataTypes, 1, 'V', "PCTime");
432 AddColumnEntry(colNames, dataTypes, NBOARDS, 'V', "BoardTime");
433 AddColumnEntry(colNames, dataTypes, NPIX, 'I', "StartPix");
434 AddColumnEntry(colNames, dataTypes, NTMARK, 'I', "StartTM");
435 AddColumnEntry(colNames, dataTypes, NPIX*h->Nroi, 'U', "Data");
436
437 //actually create the table
438 try
439 {
440 fTable = fFile->addTable("Events", 0, colNames, dataTypes);
441 if (fTable->rows() != 0)
442 {
443 ostringstream str;
444 str << "Error: table created on the fly looks non-empty.";
445 //TODO giev the error text to some error handler
446 //FIXME I guess that this error checking is useless. remove it for performances.
447 }
448 }
449 catch (const CCfits::FitsException &e)
450 {
451 ostringstream str;
452 str << "Could not create FITS table " << "Events" << " in file " << fileName << " reason: " << e.message();
453 //TODO give the error text to some error handler
454
455 Close();
456 return false;
457 }
458
459 //write header data
460 //first the "standard" keys
461 string stringValue;
462 WriteKey("EXTREL", 1.0f, "Release Number");
463 WriteKey("TELESCOP", "FACT", "Telescope that acquired this data");
464 WriteKey("ORIGIN", "ISDC", "Institution that wrote the file");
465 WriteKey("CREATOR", "FACT++ Event Builder", "Program that wrote this file");
466
467 stringValue = Time().GetAsStr();
468 stringValue[10]= 'T';
469 WriteKey("DATE", stringValue, "File creation data");
470 WriteKey("TIMESYS", "TT", "Time frame system");
471 WriteKey("TIMEUNIT", "d", "Time unit");
472 WriteKey("TIMEREF", "UTC", "Time reference frame");
473 //FIXME should we also put the start and stop time of the received data ?
474 //now the events header related variables
475 WriteKey("VERSION", h->Version, "Builder version");
476 WriteKey("RUNTYPE", h->RunType, "Type of run");
477 WriteKey("NBOARD", h->NBoard, "Number of acquisition boards");
478 WriteKey("NPIX", h->NPix, "Number of pixels");
479 WriteKey("NTM", h->NTm, "Number of Time marks");
480 WriteKey("NROI", h->Nroi, "Number of slices per pixels");
481
482 //now the boards related keywords
483 for (int i=0; i<h->NBoard; i++)
484 {
485 const PEVNT_HEADER &hh = h->FADhead[i];
486
487 WriteKey("STPKGFG", i, hh.start_package_flag,
488 "Start package flag");
489
490 WriteKey("PKGLEN", i, hh.package_length,
491 "Package length");
492
493 WriteKey("VERNO", i, hh.version_no,
494 "Version number");
495
496 WriteKey("PLLLCK", i, hh.PLLLCK,
497 "");
498/*
499 WriteKey("TRIGCRC", i, hh.trigger_crc,
500 "Trigger CRC");
501
502 WriteKey("TRIGTYP", i, hh.trigger_type,
503 "Trigger type");
504
505 WriteKey("TRIGID", i, hh.trigger_id,
506 "Trigger ID");
507
508 WriteKey("EVTCNTR", i, hh.fad_evt_counter,
509 "FAD Event Counter");
510*/
511 WriteKey("REFCLK", i, hh.REFCLK_frequency,
512 "Reference Clock Frequency");
513
514 WriteKey("BOARDID", i, hh.board_id,
515 "Board ID");
516
517 WriteKey("PHASESH", i, hh.adc_clock_phase_shift,
518 "ADC clock phase shift");
519
520 //WriteKey("TRGGEN", i, hh.number_of_triggers_to_generate,
521 // "Number of triggers to generate");
522
523 WriteKey("PRESC", i, hh.trigger_generator_prescaler,
524 "Trigger generator prescaler");
525
526 WriteKey("DNA", i, hh.DNA, "DNA");
527 WriteKey("TIME", i, hh.time, "Time");
528 WriteKey("RUNNB", i, hh.runnumber, "Run number");
529/*
530 for (int j=0;j<NTemp;j++)
531 {
532 str.str(""); str2.str("");
533 str << "DRS_T" << i << j;
534 str2 << "DRS temperature #" << i << " " << j;
535 WriteKey(str.str(), h->FADhead[i].drs_temperature[j], str2.str());
536 }
537*/
538 for (int j=0;j<NDAC;j++)
539 WriteKey("DAC", i*NDAC+j, hh.dac[j], "DAC");
540
541 //Last but not least, add header keys that will be updated when closing the file
542 WriteFooter(NULL);
543 }
544
545 return true;
546 }
547
548
549 int WriteColumns(size_t &start, size_t size, void *e)
550 {
551 int status = 0;
552 fits_write_tblbytes(fFile->fitsPointer(), fNumRows, start, size, reinterpret_cast<unsigned char*>(e), &status);
553 if (status)
554 {
555 char text[30];//max length of cfitsio error strings (from doc)
556 fits_get_errstatus(status, text);
557 //ostringstream str;
558 //str << "Writing FITS row " << i << " in " << groupName << ": " << text << " (file_write_tblbytes, rc=" << status << ")";
559 //Error(str);
560 }
561
562 start += size;
563 return status;
564 }
565
566 // --------------------------------------------------------------------------
567 //
568 //! This writes one event to the file
569 //! @param e the pointer to the EVENT
570 //
571 virtual bool Write(EVENT *e)
572 {
573 //FIXME As discussed earlier, we do not swap the bytes yet.
574 fTable->makeThisCurrent();
575
576 //insert a new row
577 int status(0);
578 if (fits_insert_rows(fTable->fitsPointer(), fNumRows, 1, &status))
579 {
580 //ostringstream str;
581 //str << "Inserting row into " << fFileName << " failed (fits_insert_rows, rc=" << status << ")";
582 //fMess->Error(str);
583 //TODO pipe this error message to the appropriate error stream
584 }
585 fNumRows++;
586
587 const int sh = sizeof(EVENT)+NPIX*e->Roi*2;
588
589 // column size pointer
590 size_t col = 1;
591 if (!WriteColumns(col, sh, e))
592 return true;
593
594 //TODO output an error
595 return false;
596
597 /*
598 //write the data, chunk by chunk
599 //FIXME hard-coded size corresponds to current variables of the event, in bytes.
600 //FIXME no padding was taken into account. Because smallest member is 2 bytes, I don't think that this should be a problem.
601 const long sizeInBytesOfEventBeforePointers = 16;
602
603 long col = 1;
604 if (FitsWriteTblBytes(col, sizeInBytesOfEventBeforePointers, e))
605 {
606 //TODO output an error
607 return false;
608 }
609 if (FitsWriteTblBytes(col, NBOARDS*2, e->BoardTime))
610 {
611 //TODO output an error
612 return false;
613 }
614 if (FitsWriteTblBytes(col, NPIX*2, e->StartPix))
615 {
616 //TODO output an error
617 return false;
618 }
619 if (FitsWriteTblBytes(col, NTMARK*2, e->StartTM))
620 {
621 //TODO output an error
622 return false;
623 }
624 if (FitsWriteTblBytes(col, NPIX*fRoi*2, e->Adc_Data))
625 {
626 //TODO output an error
627 return false;
628 }
629 return true;*/
630 }
631
632 void WriteFooter(RUN_TAIL *rt)
633 {
634 //write final header keys
635 fTable->makeThisCurrent();
636
637 WriteKey("NBEVTOK", rt ? rt->nEventsOk : uint32_t(0),
638 "How many events were written");
639
640 WriteKey("NBEVTREJ", rt ? rt->nEventsRej : uint32_t(0),
641 "How many events were rejected by SW-trig");
642
643 WriteKey("NBEVTBAD", rt ? rt->nEventsBad : uint32_t(0),
644 "How many events were rejected by Error");
645
646 //FIXME shouldn't we convert start and stop time to MjD first ?
647 //FIXME shouldn't we also add an MjD reference ?
648
649 WriteKey("TSTART", rt ? rt->PCtime0 : uint32_t(0),
650 "Time when first event received");
651
652 WriteKey("TSTOP", rt ? rt->PCtimeX : uint32_t(0),
653 "Time when last event received");
654 }
655
656 // --------------------------------------------------------------------------
657 //
658 //! Closes the file, and before this it write the TAIL data
659 //! @param rt the pointer to the RUN_TAIL data structure
660 //
661 virtual bool Close(RUN_TAIL *rt = 0)
662 {
663 if (!fFile)
664 return false;
665
666 WriteFooter(rt);
667
668 delete fFile;
669 fFile = NULL;
670
671 return true;
672 }
673
674};
675#else
676#define DataFileFits DataFileRaw
677#endif
678
679class EventBuilderWrapper
680{
681public:
682 // FIXME
683 static EventBuilderWrapper *This;
684
685 MessageImp &fMsg;
686
687private:
688 boost::thread fThread;
689
690 enum CommandStates_t // g_runStat
691 {
692 kAbort = -2, // quit as soon as possible ('abort')
693 kExit = -1, // stop reading, quit when buffered events done ('exit')
694 kInitialize = 0, // 'initialize' (e.g. dim not yet started)
695 kHybernate = 1, // do nothing for long time ('hybernate') [wakeup within ~1sec]
696 kSleep = 2, // do nothing ('sleep') [wakeup within ~10msec]
697 kModeFlush = 10, // read data from camera, but skip them ('flush')
698 kModeTest = 20, // read data and process them, but do not write to disk ('test')
699 kModeFlag = 30, // read data, process and write all to disk ('flag')
700 kModeRun = 40, // read data, process and write selected to disk ('run')
701 };
702
703 enum
704 {
705 kCurrent = 0,
706 kTotal = 1,
707 kEventId = 2,
708 kTriggerId = 3,
709 };
710
711 enum FileFormat_t
712 {
713 kNone = 0,
714 kDebug,
715 kFits,
716 kRaw
717 };
718
719 FileFormat_t fFileFormat;
720
721
722 uint32_t fMaxRun;
723 uint32_t fLastOpened;
724 uint32_t fLastClosed;
725 uint32_t fNumEvts[4];
726
727 DimDescribedService fDimRuns;
728 DimDescribedService fDimEvents;
729 DimDescribedService fDimEventData;
730 DimDescribedService fDimFwVersion;
731 DimDescribedService fDimRunNumber;
732 DimDescribedService fDimStatus;
733 DimDescribedService fDimDNA;
734 DimDescribedService fDimTemperature;
735 DimDescribedService fDimRefClock;
736 DimDescribedService fDimStatistics;
737
738 bool fDebugStream;
739 bool fDebugRead;
740
741 int Write(const Time &time, const std::string &txt, int qos)
742 {
743 return fMsg.Write(time, txt, qos);
744 }
745
746
747 int fRunNumber;
748
749
750 void InitRunNumber()
751 {
752 const int night = Time().NightAsInt();
753
754 fRunNumber = 1000;
755
756 while (--fRunNumber>=0)
757 {
758 ostringstream name;
759 name << night << '.' << setfill('0') << setw(3) << fRunNumber;
760
761 if (access((name.str()+".bin").c_str(), F_OK) == 0)
762 break;
763 if (access((name.str()+".fits").c_str(), F_OK) == 0)
764 break;
765 }
766
767 fRunNumber++;
768
769 cout << "FOUND: " << night << '.' << setfill('0') << setw(3) << fRunNumber << endl;
770 }
771
772public:
773 EventBuilderWrapper(MessageImp &imp) : fMsg(imp),
774 fFileFormat(kNone), fMaxRun(0), fLastOpened(0), fLastClosed(0),
775 fDimRuns ("FAD_CONTROL/RUNS", "I:5", ""),
776 fDimEvents ("FAD_CONTROL/EVENTS", "I:4", ""),
777 fDimEventData ("FAD_CONTROL/EVENT_DATA", "S:1;I:1;S:1;I:2;S:1;S", ""),
778 fDimFwVersion ("FAD_CONTROL/FIRMWARE_VERSION", "F:42", ""),
779 fDimRunNumber ("FAD_CONTROL/RUN_NUMBER", "I:42", ""),
780 fDimStatus ("FAD_CONTROL/STATUS", "S:42", ""),
781 fDimDNA ("FAD_CONTROL/DNA", "X:40", ""),
782 fDimTemperature ("FAD_CONTROL/TEMPERATURE", "F:82", ""),
783 fDimRefClock ("FAD_CONTROL/REFERENCE_CLOCK", "I:42", ""),
784 fDimStatistics ("FAD_CONTROL/STATISTICS", "X:8", ""),
785 fDebugStream(false), fDebugRead(false)
786 {
787 if (This)
788 throw logic_error("EventBuilderWrapper cannot be instantiated twice.");
789
790 This = this;
791
792 memset(fNumEvts, 0, sizeof(fNumEvts));
793
794 fDimEvents.Update(fNumEvts);
795
796 for (size_t i=0; i<40; i++)
797 ConnectSlot(i, tcp::endpoint());
798
799 // InitRunNumber();
800 }
801 virtual ~EventBuilderWrapper()
802 {
803 Abort();
804
805 // FIXME: Used timed_join and abort afterwards
806 // What's the maximum time the eb need to abort?
807 fThread.join();
808 //ffMsg.Info("EventBuilder stopped.");
809
810 for (vector<DataFileImp*>::iterator it=fFiles.begin(); it!=fFiles.end(); it++)
811 delete *it;
812 }
813
814 bool IsThreadRunning()
815 {
816 return !fThread.timed_join(boost::posix_time::microseconds(0));
817 }
818
819 void SetMaxMemory(unsigned int mb) const
820 {
821 if (mb*1000000<GetUsedMemory())
822 {
823 // ffMsg.Warn("...");
824 return;
825 }
826
827 g_maxMem = size_t(mb)*1000000;
828 }
829
830 void StartThread(const vector<tcp::endpoint> &addr)
831 {
832 if (IsThreadRunning())
833 {
834 fMsg.Warn("Start - EventBuilder still running");
835 return;
836 }
837
838 for (size_t i=0; i<40; i++)
839 ConnectSlot(i, addr[i]);
840
841 g_runStat = kModeRun;
842
843 fMsg.Message("Starting EventBuilder thread");
844
845 fThread = boost::thread(StartEvtBuild);
846 }
847 void ConnectSlot(unsigned int i, const tcp::endpoint &addr)
848 {
849 if (i>39)
850 return;
851
852 if (addr==tcp::endpoint())
853 {
854 DisconnectSlot(i);
855 return;
856 }
857
858 g_port[i].sockAddr.sin_family = AF_INET;
859 g_port[i].sockAddr.sin_addr.s_addr = htonl(addr.address().to_v4().to_ulong());
860 g_port[i].sockAddr.sin_port = htons(addr.port());
861 // In this order
862 g_port[i].sockDef = 1;
863 }
864 void DisconnectSlot(unsigned int i)
865 {
866 if (i>39)
867 return;
868
869 g_port[i].sockDef = 0;
870 // In this order
871 g_port[i].sockAddr.sin_family = AF_INET;
872 g_port[i].sockAddr.sin_addr.s_addr = 0;
873 g_port[i].sockAddr.sin_port = 0;
874 }
875 void IgnoreSlot(unsigned int i)
876 {
877 if (i>39)
878 return;
879 if (g_port[i].sockAddr.sin_port==0)
880 return;
881
882 g_port[i].sockDef = -1;
883 }
884
885
886 void Abort()
887 {
888 fMsg.Message("Signal abort to EventBuilder thread...");
889 g_runStat = kAbort;
890 }
891
892 void Exit()
893 {
894 fMsg.Message("Signal exit to EventBuilder thread...");
895 g_runStat = kExit;
896 }
897
898 /*
899 void Wait()
900 {
901 fThread.join();
902 ffMsg.Message("EventBuilder stopped.");
903 }*/
904
905 void Hybernate() const { g_runStat = kHybernate; }
906 void Sleep() const { g_runStat = kSleep; }
907 void FlushMode() const { g_runStat = kModeFlush; }
908 void TestMode() const { g_runStat = kModeTest; }
909 void FlagMode() const { g_runStat = kModeFlag; }
910 void RunMode() const { g_runStat = kModeRun; }
911
912 // FIXME: To be removed
913 void SetMode(int mode) const { g_runStat = mode; }
914
915 bool IsConnected(int i) const { return gi_NumConnect[i]==7; }
916 bool IsConnecting(int i) const { return !IsConnected(i) && !IsDisconnected(i); }
917 bool IsDisconnected(int i) const { return gi_NumConnect[i]<=0 && g_port[i].sockDef==0; }
918 int GetNumConnected(int i) const { return gi_NumConnect[i]; }
919
920 void SetIgnore(int i, bool b) const { if (g_port[i].sockDef!=0) g_port[i].sockDef=b?-1:1; }
921 bool IsIgnored(int i) const { return g_port[i].sockDef==-1; }
922
923 void SetOutputFormat(FileFormat_t f) { fFileFormat = f; }
924
925 void SetDebugStream(bool b)
926 {
927 fDebugStream = b;
928 if (b)
929 return;
930
931 for (int i=0; i<40; i++)
932 {
933 if (!fDumpStream[i].is_open())
934 continue;
935
936 fDumpStream[i].close();
937
938 ostringstream name;
939 name << "socket_dump-" << setfill('0') << setw(2) << i << ".bin";
940 fMsg.Message("Closed file '"+name.str()+"'");
941 }
942 }
943
944 void SetDebugRead(bool b)
945 {
946 fDebugRead = b;
947 if (b || !fDumpRead.is_open())
948 return;
949
950 fDumpRead.close();
951 fMsg.Message("Closed file 'socket_events.txt'");
952 }
953
954 size_t GetUsedMemory() const { return gi_usedMem; }
955
956 virtual int CloseOpenFiles() { CloseRunFile(0, 0); return 0; }
957
958
959 /*
960 struct OpenFileToDim
961 {
962 int code;
963 char fileName[FILENAME_MAX];
964 };
965
966 SignalRunOpened(runid, filename);
967 // Send num open files
968 // Send runid, (more info about the run?), filename via dim
969
970 SignalEvtWritten(runid);
971 // Send num events written of newest file
972
973 SignalRunClose(runid);
974 // Send new num open files
975 // Send empty file-name if no file is open
976
977 */
978
979 // -------------- Mapped event builder callbacks ------------------
980
981 void UpdateRuns()
982 {
983 uint32_t values[5] =
984 {
985 static_cast<uint32_t>(fFiles.size()),
986 0xffffffff,
987 0,
988 fLastOpened,
989 fLastClosed
990 };
991
992 for (vector<DataFileImp*>::const_iterator it=fFiles.begin();
993 it!=fFiles.end(); it++)
994 {
995 const DataFileImp *file = *it;
996
997 if (file->GetRunId()<values[1])
998 values[1] = file->GetRunId();
999
1000 if (file->GetRunId()>values[2])
1001 values[2] = file->GetRunId();
1002 }
1003
1004 fMaxRun = values[2];
1005
1006 fDimRuns.Update(values);
1007 }
1008
1009 vector<DataFileImp*> fFiles;
1010
1011 FileHandle_t runOpen(uint32_t runid, RUN_HEAD *h, size_t)
1012 {
1013 // Check if file already exists...
1014 DataFileImp *file = 0;
1015 switch (fFileFormat)
1016 {
1017 case kNone: file = new DataFileNone(runid); break;
1018 case kDebug: file = new DataFileDebug(runid); break;
1019 case kFits: file = new DataFileFits(runid); break;
1020 case kRaw: file = new DataFileRaw(runid); break;
1021 }
1022
1023 try
1024 {
1025 if (!file->OpenFile(h))
1026 return 0;
1027 }
1028 catch (const exception &e)
1029 {
1030 return 0;
1031 }
1032
1033 fFiles.push_back(file);
1034
1035 fLastOpened = runid;
1036 UpdateRuns();
1037
1038 fNumEvts[kEventId] = 0;
1039 fNumEvts[kTriggerId] = 0;
1040
1041 fNumEvts[kCurrent] = 0;
1042 fDimEvents.Update(fNumEvts);
1043 // fDimCurrentEvent.Update(uint32_t(0));
1044
1045 return reinterpret_cast<FileHandle_t>(file);
1046 }
1047
1048 int runWrite(FileHandle_t handler, EVENT *e, size_t)
1049 {
1050 DataFileImp *file = reinterpret_cast<DataFileImp*>(handler);
1051
1052 if (!file->Write(e))
1053 return -1;
1054
1055 if (file->GetRunId()==fMaxRun)
1056 {
1057 fNumEvts[kCurrent]++;
1058 fNumEvts[kEventId] = e->EventNum;
1059 fNumEvts[kTriggerId] = e->TriggerType;
1060 }
1061
1062 fNumEvts[kTotal]++;
1063
1064 static Time oldt(boost::date_time::neg_infin);
1065 Time newt;
1066 if (newt>oldt+boost::posix_time::seconds(1))
1067 {
1068 fDimEvents.Update(fNumEvts);
1069 oldt = newt;
1070 }
1071
1072
1073 // ===> SignalEvtWritten(runid);
1074 // Send num events written of newest file
1075
1076 /* close run runId (all all runs if runId=0) */
1077 /* return: 0=close scheduled / >0 already closed / <0 does not exist */
1078 //CloseRunFile(file->GetRunId(), time(NULL)+2) ;
1079
1080 return 0;
1081 }
1082
1083 int runClose(FileHandle_t handler, RUN_TAIL *tail, size_t)
1084 {
1085 DataFileImp *file = reinterpret_cast<DataFileImp*>(handler);
1086
1087 const vector<DataFileImp*>::iterator it = find(fFiles.begin(), fFiles.end(), file);
1088 if (it==fFiles.end())
1089 {
1090 ostringstream str;
1091 str << "File handler (" << handler << ") requested to close by event builder doesn't exist.";
1092 fMsg.Fatal(str);
1093 return -1;
1094 }
1095
1096 ostringstream str;
1097 str << "Closing file for run " << file->GetRunId() << " (" << file << ")" << endl;
1098 fMsg.Info(str);
1099
1100 fFiles.erase(it);
1101
1102 fLastClosed = file->GetRunId();
1103 UpdateRuns();
1104
1105 fDimEvents.Update(fNumEvts);
1106
1107 const bool rc = file->Close(tail);
1108 if (!rc)
1109 {
1110 // Error message
1111 }
1112
1113 delete file;
1114
1115 // ==> SignalRunClose(runid);
1116 // Send new num open files
1117 // Send empty file-name if no file is open
1118
1119 return rc ? 0 : -1;
1120 }
1121
1122 ofstream fDumpStream[40];
1123
1124 void debugStream(int isock, void *buf, int len)
1125 {
1126 if (!fDebugStream)
1127 return;
1128
1129 const int slot = isock/7;
1130 if (slot<0 || slot>39)
1131 return;
1132
1133 if (!fDumpStream[slot].is_open())
1134 {
1135 ostringstream name;
1136 name << "socket_dump-" << setfill('0') << setw(2) << slot << ".bin";
1137
1138 fDumpStream[slot].open(name.str().c_str(), ios::app);
1139 if (!fDumpStream[slot])
1140 {
1141 ostringstream str;
1142 str << "Open file '" << name << "': " << strerror(errno) << " (errno=" << errno << ")";
1143 fMsg.Error(str);
1144
1145 return;
1146 }
1147
1148 fMsg.Message("Opened file '"+name.str()+"' for writing.");
1149 }
1150
1151 fDumpStream[slot].write(reinterpret_cast<const char*>(buf), len);
1152 }
1153
1154 ofstream fDumpRead; // Stream to possibly dump docket events
1155
1156 void debugRead(int isock, int ibyte, uint32_t event, uint32_t ftmevt, uint32_t runno, int state, uint32_t tsec, uint32_t tusec)
1157 {
1158 // isock = socketID (0-279)
1159 // ibyte = #bytes gelesen
1160 // event = eventId (oder 0 wenn noch nicht bekannt)
1161 // state : 1=finished reading data
1162 // 0=reading data
1163 // -1=start reading data (header)
1164 // -2=start reading data,
1165 // eventId not known yet (too little data)
1166 // tsec, tusec = time when reading seconds, microseconds
1167 //
1168 if (!fDebugRead || ibyte==0)
1169 return;
1170
1171 if (!fDumpRead.is_open())
1172 {
1173 fDumpRead.open("socket_events.txt", ios::app);
1174 if (!fDumpRead)
1175 {
1176 ostringstream str;
1177 str << "Open file 'socket_events.txt': " << strerror(errno) << " (errno=" << errno << ")";
1178 fMsg.Error(str);
1179
1180 return;
1181 }
1182
1183 fMsg.Message("Opened file 'socket_events.txt' for writing.");
1184
1185 fDumpRead << "# START: " << Time().GetAsStr() << endl;
1186 fDumpRead << "# state time_sec time_usec socket slot runno event_id trigger_id bytes_received" << endl;
1187 }
1188
1189 fDumpRead
1190 << setw(2) << state << " "
1191 << setw(8) << tsec << " "
1192 << setw(9) << tusec << " "
1193 << setw(3) << isock << " "
1194 << setw(2) << isock/7 << " "
1195 << runno << " "
1196 << event << " "
1197 << ftmevt << " "
1198 << ibyte << endl;
1199 }
1200
1201 struct DimEventData
1202 {
1203 uint16_t Roi ; // #slices per pixel (same for all pixels and tmarks)
1204 uint32_t EventNum ; // EventNumber as from FTM
1205 uint16_t TriggerType ; // Trigger Type from FTM
1206
1207 uint32_t PCTime ; // when did event start to arrive at PC
1208 uint32_t BoardTime; //
1209
1210 int16_t StartPix; // First Channel per Pixel (Pixels sorted according Software ID) ; -1 if not filled
1211 int16_t StartTM; // First Channel for TimeMark (sorted Hardware ID) ; -1 if not filled
1212
1213 uint16_t Adc_Data[]; // final length defined by malloc ....
1214
1215 } __attribute__((__packed__));;
1216
1217 int eventCheck(PEVNT_HEADER *fadhd, EVENT *event)
1218 {
1219 /*
1220 fadhd[i] ist ein array mit den 40 fad-headers
1221 (falls ein board nicht gelesen wurde, ist start_package_flag =0 )
1222
1223 event ist die Struktur, die auch die write routine erhaelt;
1224 darin sind im header die 'soll-werte' fuer z.B. eventID
1225 als auch die ADC-Werte (falls Du die brauchst)
1226
1227 Wenn die routine einen negativen Wert liefert, wird das event
1228 geloescht (nicht an die write-routine weitergeleitet [mind. im Prinzip]
1229 */
1230
1231 static Time oldt(boost::date_time::neg_infin);
1232 Time newt;
1233
1234 if (newt<oldt+boost::posix_time::seconds(1))
1235 return 0;
1236
1237 oldt = newt;
1238
1239 static DimEventData *data = 0;
1240
1241 const size_t sz = sizeof(DimEventData)+event->Roi*2*1440;
1242
1243 if (data && data->Roi != event->Roi)
1244 {
1245 delete data;
1246 data = 0;
1247 }
1248
1249 if (!data)
1250 data = reinterpret_cast<DimEventData*>(new char[sz]);
1251
1252// cout << sizeof(DimEventData) << " " << event->Roi << " " << sz << " " << sizeof(*data) << endl;
1253
1254 data->Roi = event->Roi;
1255 data->EventNum = event->EventNum;
1256 data->TriggerType = event->TriggerType;
1257 data->PCTime = event->PCTime;
1258 data->BoardTime = event->BoardTime[0];
1259 data->StartPix = event->StartPix[0];
1260 data->StartTM = event->StartTM[0];
1261
1262 memcpy(data->Adc_Data, event->Adc_Data, event->Roi*2*1440);
1263
1264 fDimEventData.setData(data, sz);
1265 fDimEventData.updateService();
1266
1267 //delete data;
1268
1269 return 0;
1270 }
1271
1272 void factOut(int severity, int err, const char *message)
1273 {
1274 // FIXME: Make the output to the console stream thread-safe
1275 ostringstream str;
1276 str << "EventBuilder(";
1277 if (err<0)
1278 str << "---";
1279 else
1280 str << err;
1281 str << "): " << message;
1282
1283 static string last;
1284 if (str.str()==last)
1285 return;
1286
1287 last = str.str();
1288 fMsg.Update(str, severity);
1289 }
1290
1291 void factStat(int64_t *stat, int len)
1292 {
1293 if (len!=7)
1294 {
1295 fMsg.Warn("factStat received unknown number of values.");
1296 return;
1297 }
1298
1299 vector<int64_t> data(1, g_maxMem);
1300 data.insert(data.end(), stat, stat+len);
1301
1302 static vector<int64_t> last(8);
1303 if (data==last)
1304 return;
1305 last = data;
1306
1307 fDimStatistics.Update(data);
1308
1309 // len ist die Laenge des arrays.
1310 // array[4] enthaelt wieviele bytes im Buffer aktuell belegt sind; daran
1311 // kannst Du pruefen, ob die 100MB voll sind ....
1312
1313 ostringstream str;
1314 str
1315 << "Wait=" << stat[0] << " "
1316 << "Skip=" << stat[1] << " "
1317 << "Del=" << stat[2] << " "
1318 << "Tot=" << stat[3] << " "
1319 << "Mem=" << stat[4] << "/" << g_maxMem << " "
1320 << "Read=" << stat[5] << " "
1321 << "Conn=" << stat[6];
1322
1323 fMsg.Info(str);
1324 }
1325
1326 boost::array<FAD::EventHeader, 40> fVecHeader;
1327
1328 template<typename T>
1329 boost::array<T, 42> Compare(const FAD::EventHeader *h, const T *t)
1330 {
1331 const int offset = reinterpret_cast<const char *>(t) - reinterpret_cast<const char *>(h);
1332
1333 const T *min = NULL;
1334 const T *val = NULL;
1335 const T *max = NULL;
1336
1337 boost::array<T, 42> vec;
1338
1339 bool rc = true;
1340 for (int i=0; i<40; i++)
1341 {
1342 const char *base = reinterpret_cast<const char*>(&fVecHeader[i]);
1343 const T *ref = reinterpret_cast<const T*>(base+offset);
1344
1345 vec[i] = *ref;
1346
1347 if (gi_NumConnect[i]!=7)
1348 {
1349 vec[i] = 0;
1350 continue;
1351 }
1352
1353 if (!val)
1354 {
1355 min = ref;
1356 val = ref;
1357 max = ref;
1358 }
1359
1360 if (*val<*min)
1361 min = val;
1362
1363 if (*val>*max)
1364 max = val;
1365
1366 if (*val!=*ref)
1367 rc = false;
1368 }
1369
1370 vec[40] = val ? *min : 0xffffffff;
1371 vec[41] = val ? *max : 0;
1372
1373 return vec;
1374 }
1375
1376 template<typename T>
1377 boost::array<T, 42> CompareBits(const FAD::EventHeader *h, const T *t)
1378 {
1379 const int offset = reinterpret_cast<const char *>(t) - reinterpret_cast<const char *>(h);
1380
1381 T val = 0;
1382 T rc = 0;
1383
1384 boost::array<T, 42> vec;
1385
1386 bool first = true;
1387
1388 for (int i=0; i<40; i++)
1389 {
1390 const char *base = reinterpret_cast<const char*>(&fVecHeader[i]);
1391 const T *ref = reinterpret_cast<const T*>(base+offset);
1392
1393 vec[i+2] = *ref;
1394
1395 if (gi_NumConnect[i]!=7)
1396 {
1397 vec[i+2] = 0;
1398 continue;
1399 }
1400
1401 if (first)
1402 {
1403 first = false;
1404 val = *ref;
1405 rc = 0;
1406 }
1407
1408 rc |= val^*ref;
1409 }
1410
1411 vec[0] = rc;
1412 vec[1] = val;
1413
1414 return vec;
1415 }
1416
1417 template<typename T, size_t N>
1418 void Update(DimDescribedService &svc, const boost::array<T, N> &data, int n=N)
1419 {
1420// svc.setQuality(vec[40]<=vec[41]);
1421 svc.setData(const_cast<T*>(data.data()), sizeof(T)*n);
1422 svc.updateService();
1423 }
1424
1425 template<typename T>
1426 void Print(const char *name, const pair<bool,boost::array<T, 43>> &data)
1427 {
1428 cout << name << "|" << data.first << "|" << data.second[1] << "|" << data.second[0] << "<x<" << data.second[1] << ":";
1429 for (int i=0; i<40;i++)
1430 cout << " " << data.second[i+3];
1431 cout << endl;
1432 }
1433
1434 vector<uint> fNumConnected;
1435
1436 void debugHead(int socket, const FAD::EventHeader &h)
1437 {
1438 const uint16_t id = h.Id();
1439 if (id>39)
1440 return;
1441
1442 if (fNumConnected.size()!=40)
1443 fNumConnected.resize(40);
1444
1445 vector<uint> con(gi_NumConnect, gi_NumConnect+40);
1446
1447 bool changed = con!=fNumConnected || !IsThreadRunning();
1448
1449 fNumConnected = con;
1450
1451 const FAD::EventHeader old = fVecHeader[id];
1452 fVecHeader[id] = h;
1453
1454 if (old.fVersion != h.fVersion || changed)
1455 {
1456 const boost::array<uint16_t,42> ver = Compare(&h, &h.fVersion);
1457
1458 boost::array<float,42> data;
1459 for (int i=0; i<42; i++)
1460 {
1461 ostringstream str;
1462 str << (ver[i]>>8) << '.' << (ver[i]&0xff);
1463 data[i] = atof(str.str().c_str());
1464 }
1465 Update(fDimFwVersion, data);
1466 }
1467
1468 if (old.fRunNumber != h.fRunNumber || changed)
1469 {
1470 const boost::array<uint32_t,42> run = Compare(&h, &h.fRunNumber);
1471 fDimRunNumber.Update(run);
1472 }
1473
1474 if (old.fDNA != h.fDNA || changed)
1475 {
1476 const boost::array<uint64_t,42> dna = Compare(&h, &h.fDNA);
1477 Update(fDimDNA, dna, 40);
1478 }
1479
1480 if (old.fStatus != h.fStatus || changed)
1481 {
1482 const boost::array<uint16_t,42> sts = CompareBits(&h, &h.fStatus);
1483 Update(fDimStatus, sts);
1484 }
1485
1486 // -----------
1487
1488 static Time oldt(boost::date_time::neg_infin);
1489 Time newt;
1490
1491 if (newt>oldt+boost::posix_time::seconds(1))
1492 {
1493 oldt = newt;
1494
1495 // --- RefClock
1496
1497 const boost::array<uint32_t,42> clk = Compare(&h, &h.fFreqRefClock);
1498 Update(fDimRefClock, clk);
1499
1500 // --- Temperatures
1501
1502 const boost::array<int16_t,42> tmp[4] =
1503 {
1504 Compare(&h, &h.fTempDrs[0]),
1505 Compare(&h, &h.fTempDrs[1]),
1506 Compare(&h, &h.fTempDrs[2]),
1507 Compare(&h, &h.fTempDrs[3])
1508 };
1509
1510 vector<int16_t> data;
1511 data.reserve(82);
1512 data.push_back(tmp[0][0]);
1513 data.insert(data.end(), tmp[0].data()+2, tmp[0].data()+42);
1514 data.push_back(tmp[0][1]);
1515 data.insert(data.end(), tmp[0].data()+2, tmp[0].data()+42);
1516
1517 for (int j=0; j<=3; j++)
1518 {
1519 const boost::array<int16_t,42> &ref = tmp[j];
1520
1521 // Gloabl min
1522 if (ref[40]<data[0])
1523 data[0] = ref[40];
1524
1525 // Global max
1526 if (ref[41]>data[40])
1527 data[40] = ref[41];
1528
1529 for (int i=0; i<40; i++)
1530 {
1531 // min per board
1532 if (ref[i]<data[i+1])
1533 data[i+1] = ref[i];
1534
1535 // max per board
1536 if (ref[i]>data[i+41])
1537 data[i+41] = ref[i];
1538 }
1539 }
1540
1541 vector<float> deg(82);
1542 for (int i=0; i<82; i++)
1543 deg[i] = data[i]/16.;
1544 fDimTemperature.Update(deg);
1545 }
1546
1547 /*
1548 uint16_t fTriggerType;
1549 uint32_t fTriggerId;
1550 uint32_t fEventCounter;
1551 uint16_t fAdcClockPhaseShift;
1552 uint16_t fNumTriggersToGenerate;
1553 uint16_t fTriggerGeneratorPrescaler;
1554 uint32_t fTimeStamp;
1555 int16_t fTempDrs[kNumTemp]; // In units of 1/16 deg(?)
1556 uint16_t fDac[kNumDac];
1557 */
1558 }
1559};
1560
1561EventBuilderWrapper *EventBuilderWrapper::This = 0;
1562
1563// ----------- Event builder callbacks implementation ---------------
1564extern "C"
1565{
1566 FileHandle_t runOpen(uint32_t irun, RUN_HEAD *runhd, size_t len)
1567 {
1568 return EventBuilderWrapper::This->runOpen(irun, runhd, len);
1569 }
1570
1571 int runWrite(FileHandle_t fileId, EVENT *event, size_t len)
1572 {
1573 return EventBuilderWrapper::This->runWrite(fileId, event, len);
1574 }
1575
1576 int runClose(FileHandle_t fileId, RUN_TAIL *runth, size_t len)
1577 {
1578 return EventBuilderWrapper::This->runClose(fileId, runth, len);
1579 }
1580
1581 void factOut(int severity, int err, const char *message)
1582 {
1583 if (severity!=99)
1584 EventBuilderWrapper::This->factOut(severity, err, message);
1585 }
1586
1587 void factStat(int64_t *array, int len)
1588 {
1589 EventBuilderWrapper::This->factStat(array, len);
1590 }
1591
1592 void debugHead(int socket, void *buf)
1593 {
1594 const uint16_t *ptr = reinterpret_cast<uint16_t*>(buf);
1595
1596 EventBuilderWrapper::This->debugHead(socket, FAD::EventHeader(ptr));
1597 }
1598
1599 void debugStream(int isock, void *buf, int len)
1600 {
1601 return EventBuilderWrapper::This->debugStream(isock, buf, len);
1602 }
1603
1604 void debugRead(int isock, int ibyte, int32_t event, int32_t ftmevt, int32_t runno, int state, uint32_t tsec, uint32_t tusec)
1605 {
1606 EventBuilderWrapper::This->debugRead(isock, ibyte, event, ftmevt, runno, state, tsec, tusec);
1607 }
1608
1609 int eventCheck(PEVNT_HEADER *fadhd, EVENT *event)
1610 {
1611 return EventBuilderWrapper::This->eventCheck(fadhd, event);
1612 }
1613}
1614
1615#endif
Note: See TracBrowser for help on using the repository browser.