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

Last change on this file since 11084 was 11082, checked in by tbretz, 13 years ago
Added commands DUMP_STREAM and DUMP_RECV to have better access to the behaviour of the sockets.
File size: 33.2 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
722 bool fDebugStream;
723 bool fDebugRead;
724
725 int Write(const Time &time, const std::string &txt, int qos)
726 {
727 return fMsg.Write(time, txt, qos);
728 }
729
730public:
731 EventBuilderWrapper(MessageImp &imp) : fMsg(imp),
732 fFileFormat(kRaw), fMaxRun(0),
733 fDimFiles ("FAD_CONTROL/FILES", "X:1", ""),
734 fDimRuns ("FAD_CONTROL/RUNS", "I:1", ""),
735 fDimEvents("FAD_CONTROL/EVENTS", "I:2", ""),
736 fDimCurrentEvent("FAD_CONTROL/CURRENT_EVENT", "I:1", ""),
737 fDebugStream(false), fDebugRead(false)
738 {
739 if (This)
740 throw logic_error("EventBuilderWrapper cannot be instantiated twice.");
741
742 This = this;
743
744 memset(fNumEvts, 0, sizeof(fNumEvts));
745
746 Update(fDimRuns, uint32_t(0));
747 Update(fDimCurrentEvent, uint32_t(0));
748 Update(fDimEvents, fNumEvts);
749 }
750 ~EventBuilderWrapper()
751 {
752 Abort();
753
754 // FIXME: Used timed_join and abort afterwards
755 // What's the maximum time the eb need to abort?
756 fThread.join();
757 //ffMsg.Info("EventBuilder stopped.");
758
759 for (vector<DataFileImp*>::iterator it=fFiles.begin(); it!=fFiles.end(); it++)
760 delete *it;
761 }
762
763 bool IsThreadRunning()
764 {
765 return !fThread.timed_join(boost::posix_time::microseconds(0));
766 }
767
768 void SetMaxMemory(unsigned int mb) const
769 {
770 if (mb*1000000<GetUsedMemory())
771 {
772 // ffMsg.Warn("...");
773 return;
774 }
775
776 g_maxMem = mb*1000000;
777 }
778
779 void Start(const vector<tcp::endpoint> &addr)
780 {
781 if (IsThreadRunning())
782 {
783 fMsg.Warn("Start - EventBuilder still running");
784 return;
785 }
786
787 int cnt = 0;
788 for (size_t i=0; i<40; i++)
789 {
790 if (addr[i]==tcp::endpoint())
791 {
792 g_port[i].sockDef = -1;
793 continue;
794 }
795
796 // -1: if entry shell not be used
797 // 0: event builder will connect but ignore the events
798 // 1: event builder will connect and build events
799 g_port[i].sockDef = 1;
800
801 g_port[i].sockAddr.sin_family = AF_INET;
802 g_port[i].sockAddr.sin_addr.s_addr = htonl(addr[i].address().to_v4().to_ulong());
803 g_port[i].sockAddr.sin_port = htons(addr[i].port());
804
805 cnt++;
806 }
807
808// g_maxBoards = cnt;
809 g_actBoards = cnt;
810
811 g_runStat = kModeRun;
812
813 fMsg.Message("Starting EventBuilder thread");
814
815 fThread = boost::thread(StartEvtBuild);
816 }
817 void Abort()
818 {
819 fMsg.Message("Signal abort to EventBuilder thread...");
820 g_runStat = kAbort;
821 }
822
823 void Exit()
824 {
825 fMsg.Message("Signal exit to EventBuilder thread...");
826 g_runStat = kExit;
827 }
828
829 /*
830 void Wait()
831 {
832 fThread.join();
833 ffMsg.Message("EventBuilder stopped.");
834 }*/
835
836 void Hybernate() const { g_runStat = kHybernate; }
837 void Sleep() const { g_runStat = kSleep; }
838 void FlushMode() const { g_runStat = kModeFlush; }
839 void TestMode() const { g_runStat = kModeTest; }
840 void FlagMode() const { g_runStat = kModeFlag; }
841 void RunMode() const { g_runStat = kModeRun; }
842
843 // FIXME: To be removed
844 void SetMode(int mode) const { g_runStat = mode; }
845
846 bool IsConnected(int i) const { return gi_NumConnect[i]==7; }
847 bool IsDisconnected(int i) const { return gi_NumConnect[i]<=0; }
848 int GetNumConnected(int i) const { return gi_NumConnect[i]; }
849
850 void SetIgnore(int i, bool b) const { if (g_port[i].sockDef>=0) g_port[i].sockDef=b?0:1; }
851 bool IsIgnored(int i) const { return g_port[i].sockDef==0; }
852
853 void SetDebugStream(bool b) { fDebugStream = b; if (!b) for (int i=0; i<40; i++) fDumpStream[i].close(); }
854 void SetDebugRead(bool b) { fDebugRead = b; if (!b) fDumpRead.close(); }
855
856 size_t GetUsedMemory() const { return gi_usedMem; }
857
858 virtual int CloseOpenFiles() { CloseRunFile(0, 0); return 0; }
859
860
861 /*
862 struct OpenFileToDim
863 {
864 int code;
865 char fileName[FILENAME_MAX];
866 };
867
868 SignalRunOpened(runid, filename);
869 // Send num open files
870 // Send runid, (more info about the run?), filename via dim
871
872 SignalEvtWritten(runid);
873 // Send num events written of newest file
874
875 SignalRunClose(runid);
876 // Send new num open files
877 // Send empty file-name if no file is open
878
879 */
880
881 // -------------- Mapped event builder callbacks ------------------
882
883 vector<DataFileImp*> fFiles;
884
885 template<class T>
886 void Update(DimDescribedService &svc, const T &data) const
887 {
888 cout << "Update: " << svc.getName() << " (" << sizeof(T) << ")" << endl;
889 svc.setData(const_cast<T*>(&data), sizeof(T));
890 svc.updateService();
891 }
892
893 FileHandle_t runOpen(uint32_t runid, RUN_HEAD *h, size_t)
894 {
895 // Check if file already exists...
896 DataFileImp *file = 0;
897 switch (fFileFormat)
898 {
899 case kNone: file = new DataFileNone(runid); break;
900 case kDebug: file = new DataFileDebug(runid); break;
901 case kFits: file = new DataFileFits(runid); break;
902 case kRaw: file = new DataFileRaw(runid); break;
903 }
904
905 try
906 {
907 if (!file->OpenFile(h))
908 return 0;
909 }
910 catch (const exception &e)
911 {
912 return 0;
913 }
914
915 fFiles.push_back(file);
916
917 if (runid>fMaxRun)
918 {
919 fMaxRun = runid;
920 fNumEvts[kCurrent] = 0;
921
922 Update(fDimRuns, fMaxRun);
923 Update(fDimEvents, fNumEvts);
924 Update(fDimCurrentEvent, uint32_t(0));
925 }
926
927 Update(fDimFiles, fFiles.size());
928
929 return reinterpret_cast<FileHandle_t>(file);
930 }
931
932 int runWrite(FileHandle_t handler, EVENT *e, size_t)
933 {
934 DataFileImp *file = reinterpret_cast<DataFileImp*>(handler);
935
936 if (!file->Write(e))
937 return -1;
938
939 if (file->GetRunId()==fMaxRun)
940 {
941 Update(fDimCurrentEvent, e->EventNum);
942 fNumEvts[kCurrent]++;
943 }
944
945 fNumEvts[kTotal]++;
946 Update(fDimEvents, fNumEvts);
947
948 // ===> SignalEvtWritten(runid);
949 // Send num events written of newest file
950
951 /* close run runId (all all runs if runId=0) */
952 /* return: 0=close scheduled / >0 already closed / <0 does not exist */
953 //CloseRunFile(file->GetRunId(), time(NULL)+2) ;
954
955 return 0;
956 }
957
958 int runClose(FileHandle_t handler, RUN_TAIL *tail, size_t)
959 {
960 DataFileImp *file = reinterpret_cast<DataFileImp*>(handler);
961
962 const vector<DataFileImp*>::iterator it = find(fFiles.begin(), fFiles.end(), file);
963 if (it==fFiles.end())
964 {
965 ostringstream str;
966 str << "File handler (" << handler << ") requested to close by event builder doesn't exist.";
967 fMsg.Fatal(str);
968 return -1;
969 }
970
971 ostringstream str;
972 str << "Closing file for run " << file->GetRunId() << " (" << file << ")" << endl;
973 fMsg.Info(str);
974
975 fFiles.erase(it);
976
977 Update(fDimFiles, fFiles.size());
978
979 const bool rc = file->Close(tail);
980 if (!rc)
981 {
982 // Error message
983 }
984
985 delete file;
986
987 // ==> SignalRunClose(runid);
988 // Send new num open files
989 // Send empty file-name if no file is open
990
991 return rc ? 0 : -1;
992 }
993
994 ofstream fDumpStream[40];
995
996 void debugStream(int isock, void *buf, int len)
997 {
998 if (!fDebugStream)
999 return;
1000
1001 const int slot = isock/7;
1002 if (slot<0 || slot>39)
1003 return;
1004
1005 if (!fDumpStream[slot].is_open())
1006 {
1007 ostringstream name;
1008 name << "socket_dump-" << setfill('0') << setw(2) << slot << ".bin";
1009
1010 fDumpStream[slot].open(name.str().c_str(), ios::app);
1011 if (!fDumpStream[slot])
1012 {
1013 //ostringstream str;
1014 //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
1015 //Error(str);
1016
1017 return;
1018 }
1019 }
1020
1021 fDumpStream[slot].write(reinterpret_cast<const char*>(buf), len);
1022 }
1023
1024 ofstream fDumpRead; // Stream to possibly dump docket events
1025
1026 void debugRead(int isock, int ibyte, int32_t event, int state, uint32_t tsec, uint32_t tusec)
1027 {
1028 // isock = socketID (0-279)
1029 // ibyte = #bytes gelesen
1030 // event = eventId (oder 0 wenn noch nicht bekannt)
1031 // state : 0=reading data
1032 // 1=finished reading data
1033 // -1=start reading data (header)
1034 // -2=start reading data,
1035 // eventId not known yet (too little data)
1036 // tsec, tusec = time when reading seconds, microseconds
1037 //
1038 if (!fDebugRead)
1039 return;
1040
1041 if (!fDumpRead.is_open())
1042 {
1043 fDumpRead.open("socket_events.txt", ios::app);
1044 if (!fDumpRead)
1045 {
1046 //ostringstream str;
1047 //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
1048 //Error(str);
1049
1050 return;
1051 }
1052 }
1053
1054 fDumpRead
1055 << setw(2) << state << " "
1056 << setw(8) << tsec << " "
1057 << setw(9) << tusec << " "
1058 << setw(3) << isock << " "
1059 << setw(2) << isock/7 << " "
1060 << event << " "
1061 << ibyte << endl;
1062 }
1063
1064};
1065
1066EventBuilderWrapper *EventBuilderWrapper::This = 0;
1067
1068// ----------- Event builder callbacks implementation ---------------
1069extern "C"
1070{
1071 FileHandle_t runOpen(uint32_t irun, RUN_HEAD *runhd, size_t len)
1072 {
1073 return EventBuilderWrapper::This->runOpen(irun, runhd, len);
1074 }
1075
1076 int runWrite(FileHandle_t fileId, EVENT *event, size_t len)
1077 {
1078 return EventBuilderWrapper::This->runWrite(fileId, event, len);
1079 }
1080
1081 int runClose(FileHandle_t fileId, RUN_TAIL *runth, size_t len)
1082 {
1083 return EventBuilderWrapper::This->runClose(fileId, runth, len);
1084 }
1085
1086 void factOut(int severity, int err, char *message)
1087 {
1088 // FIXME: Make the output to the console stream thread-safe
1089 ostringstream str;
1090 str << "EventBuilder(";
1091 if (err<0)
1092 str << "---";
1093 else
1094 str << err;
1095 str << "): " << message;
1096 EventBuilderWrapper::This->fMsg.Update(str, severity);
1097 }
1098
1099 void factStat(int severity, int err, char* message )
1100 {
1101 if (err!=-1)
1102 {
1103 factOut(severity, err, message);
1104 return;
1105 }
1106
1107 static string last;
1108 if (message==last)
1109 return;
1110
1111 last = message;
1112
1113 ostringstream str("Status: ");
1114 str << message;
1115
1116 EventBuilderWrapper::This->fMsg.Update(str, severity);
1117 }
1118
1119 void debugStream(int isock, void *buf, int len)
1120 {
1121 return EventBuilderWrapper::This->debugStream(isock, buf, len);
1122 }
1123
1124 void debugRead(int isock, int ibyte, int32_t event, int state, uint32_t tsec, uint32_t tusec)
1125 {
1126 return EventBuilderWrapper::This->debugRead(isock, ibyte, event, state, tsec, tusec);
1127 }
1128
1129 /*
1130 void message(int severity, const char *msg)
1131 {
1132 EventBuilderWrapper::This->Update(msg, severity);
1133 }*/
1134}
1135
1136#endif
Note: See TracBrowser for help on using the repository browser.