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

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