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

Last change on this file since 11033 was 11013, checked in by tbretz, 13 years ago
Some little updates; added DataFileDebug
File size: 30.4 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 int Write(const Time &time, const std::string &txt, int qos)
723 {
724 return fMsg.Write(time, txt, qos);
725 }
726
727public:
728 EventBuilderWrapper(MessageImp &imp) : fMsg(imp),
729 fFileFormat(kRaw), fMaxRun(0),
730 fDimFiles ("FAD_CONTROL/FILES", "X:1", ""),
731 fDimRuns ("FAD_CONTROL/RUNS", "I:1", ""),
732 fDimEvents("FAD_CONTROL/EVENTS", "I:2", ""),
733 fDimCurrentEvent("FAD_CONTROL/CURRENT_EVENT", "I:1", "")
734 {
735 if (This)
736 throw logic_error("EventBuilderWrapper cannot be instantiated twice.");
737
738 This = this;
739
740 memset(fNumEvts, 0, sizeof(fNumEvts));
741
742 Update(fDimRuns, uint32_t(0));
743 Update(fDimCurrentEvent, uint32_t(0));
744 Update(fDimEvents, fNumEvts);
745 }
746 ~EventBuilderWrapper()
747 {
748 Abort();
749
750 // FIXME: Used timed_join and abort afterwards
751 // What's the maximum time the eb need to abort?
752 fThread.join();
753 //ffMsg.Info("EventBuilder stopped.");
754
755 for (vector<DataFileImp*>::iterator it=fFiles.begin(); it!=fFiles.end(); it++)
756 delete *it;
757 }
758
759 bool IsThreadRunning()
760 {
761 return !fThread.timed_join(boost::posix_time::microseconds(0));
762 }
763
764 void SetMaxMemory(unsigned int mb) const
765 {
766 if (mb*1000000<GetUsedMemory())
767 {
768 // ffMsg.Warn("...");
769 return;
770 }
771
772 g_maxMem = mb*1000000;
773 }
774
775 void Start(const vector<tcp::endpoint> &addr)
776 {
777 if (IsThreadRunning())
778 {
779 fMsg.Warn("Start - EventBuilder still running");
780 return;
781 }
782
783 int cnt = 0;
784 for (size_t i=0; i<40; i++)
785 {
786 if (addr[i]==tcp::endpoint())
787 {
788 g_port[i].sockDef = -1;
789 continue;
790 }
791
792 // -1: if entry shell not be used
793 // 0: event builder will connect but ignore the events
794 // 1: event builder will connect and build events
795 g_port[i].sockDef = 1;
796
797 g_port[i].sockAddr.sin_family = AF_INET;
798 g_port[i].sockAddr.sin_addr.s_addr = htonl(addr[i].address().to_v4().to_ulong());
799 g_port[i].sockAddr.sin_port = htons(addr[i].port());
800
801 cnt++;
802 }
803
804// g_maxBoards = cnt;
805 g_actBoards = cnt;
806
807 g_runStat = kModeRun;
808
809 fMsg.Message("Starting EventBuilder thread");
810
811 fThread = boost::thread(StartEvtBuild);
812 }
813 void Abort()
814 {
815 fMsg.Message("Signal abort to EventBuilder thread...");
816 g_runStat = kAbort;
817 }
818
819 void Exit()
820 {
821 fMsg.Message("Signal exit to EventBuilder thread...");
822 g_runStat = kExit;
823 }
824
825 /*
826 void Wait()
827 {
828 fThread.join();
829 ffMsg.Message("EventBuilder stopped.");
830 }*/
831
832 void Hybernate() const { g_runStat = kHybernate; }
833 void Sleep() const { g_runStat = kSleep; }
834 void FlushMode() const { g_runStat = kModeFlush; }
835 void TestMode() const { g_runStat = kModeTest; }
836 void FlagMode() const { g_runStat = kModeFlag; }
837 void RunMode() const { g_runStat = kModeRun; }
838
839 // FIXME: To be removed
840 void SetMode(int mode) const { g_runStat = mode; }
841
842 bool IsConnected(int i) const { return gi_NumConnect[i]==7; }
843 bool IsDisconnected(int i) const { return gi_NumConnect[i]<=0; }
844 int GetNumConnected(int i) const { return gi_NumConnect[i]; }
845
846 size_t GetUsedMemory() const { return gi_usedMem; }
847
848 virtual int CloseOpenFiles() { CloseRunFile(0, 0); return 0; }
849
850
851 /*
852 struct OpenFileToDim
853 {
854 int code;
855 char fileName[FILENAME_MAX];
856 };
857
858 SignalRunOpened(runid, filename);
859 // Send num open files
860 // Send runid, (more info about the run?), filename via dim
861
862 SignalEvtWritten(runid);
863 // Send num events written of newest file
864
865 SignalRunClose(runid);
866 // Send new num open files
867 // Send empty file-name if no file is open
868
869 */
870
871 // -------------- Mapped event builder callbacks ------------------
872
873 vector<DataFileImp*> fFiles;
874
875 template<class T>
876 void Update(DimDescribedService &svc, const T &data) const
877 {
878 cout << "Update: " << svc.getName() << " (" << sizeof(T) << ")" << endl;
879 svc.setData(const_cast<T*>(&data), sizeof(T));
880 svc.updateService();
881 }
882
883 FileHandle_t runOpen(uint32_t runid, RUN_HEAD *h, size_t)
884 {
885 // Check if file already exists...
886 DataFileImp *file = 0;
887 switch (fFileFormat)
888 {
889 case kNone: file = new DataFileNone(runid); break;
890 case kDebug: file = new DataFileDebug(runid); break;
891 case kFits: file = new DataFileFits(runid); break;
892 case kRaw: file = new DataFileRaw(runid); break;
893 }
894
895 try
896 {
897 if (!file->OpenFile(h))
898 return 0;
899 }
900 catch (const exception &e)
901 {
902 return 0;
903 }
904
905 fFiles.push_back(file);
906
907 if (runid>fMaxRun)
908 {
909 fMaxRun = runid;
910 fNumEvts[kCurrent] = 0;
911
912 Update(fDimRuns, fMaxRun);
913 Update(fDimEvents, fNumEvts);
914 Update(fDimCurrentEvent, uint32_t(0));
915 }
916
917 Update(fDimFiles, fFiles.size());
918
919 return reinterpret_cast<FileHandle_t>(file);
920 }
921
922 int runWrite(FileHandle_t handler, EVENT *e, size_t)
923 {
924 DataFileImp *file = reinterpret_cast<DataFileImp*>(handler);
925
926 if (!file->Write(e))
927 return -1;
928
929 if (file->GetRunId()==fMaxRun)
930 {
931 Update(fDimCurrentEvent, e->EventNum);
932 fNumEvts[kCurrent]++;
933 }
934
935 fNumEvts[kTotal]++;
936 Update(fDimEvents, fNumEvts);
937
938 // ===> SignalEvtWritten(runid);
939 // Send num events written of newest file
940
941 /* close run runId (all all runs if runId=0) */
942 /* return: 0=close scheduled / >0 already closed / <0 does not exist */
943 //CloseRunFile(file->GetRunId(), time(NULL)+2) ;
944
945 return 0;
946 }
947
948 int runClose(FileHandle_t handler, RUN_TAIL *tail, size_t)
949 {
950 DataFileImp *file = reinterpret_cast<DataFileImp*>(handler);
951
952 const vector<DataFileImp*>::iterator it = find(fFiles.begin(), fFiles.end(), file);
953 if (it==fFiles.end())
954 {
955 ostringstream str;
956 str << "File handler (" << handler << ") requested to close by event builder doesn't exist.";
957 fMsg.Fatal(str);
958 return -1;
959 }
960
961 ostringstream str;
962 str << "Closing file for run " << file->GetRunId() << " (" << file << ")" << endl;
963 fMsg.Info(str);
964
965 fFiles.erase(it);
966
967 Update(fDimFiles, fFiles.size());
968
969 const bool rc = file->Close(tail);
970 if (!rc)
971 {
972 // Error message
973 }
974
975 delete file;
976
977 // ==> SignalRunClose(runid);
978 // Send new num open files
979 // Send empty file-name if no file is open
980
981 return rc ? 0 : -1;
982 }
983};
984
985EventBuilderWrapper *EventBuilderWrapper::This = 0;
986
987// ----------- Event builder callbacks implementation ---------------
988extern "C"
989{
990 FileHandle_t runOpen(uint32_t irun, RUN_HEAD *runhd, size_t len)
991 {
992 return EventBuilderWrapper::This->runOpen(irun, runhd, len);
993 }
994
995 int runWrite(FileHandle_t fileId, EVENT *event, size_t len)
996 {
997 return EventBuilderWrapper::This->runWrite(fileId, event, len);
998 }
999
1000 int runClose(FileHandle_t fileId, RUN_TAIL *runth, size_t len)
1001 {
1002 return EventBuilderWrapper::This->runClose(fileId, runth, len);
1003 }
1004
1005 void factOut(int severity, int err, char *message)
1006 {
1007 // FIXME: Make the output to the console stream thread-safe
1008 ostringstream str;
1009 str << "EventBuilder(";
1010 if (err<0)
1011 str << "---";
1012 else
1013 str << err;
1014 str << "): " << message;
1015 EventBuilderWrapper::This->fMsg.Update(str, severity);
1016 }
1017
1018 void factStat(int severity, int err, char* message )
1019 {
1020 if (err!=-1)
1021 {
1022 factOut(severity, err, message);
1023 return;
1024 }
1025
1026 static string last;
1027 if (message==last)
1028 return;
1029
1030 last = message;
1031
1032 ostringstream str("Status: ");
1033 str << message;
1034
1035 EventBuilderWrapper::This->fMsg.Update(str, severity);
1036 }
1037
1038 /*
1039 void message(int severity, const char *msg)
1040 {
1041 EventBuilderWrapper::This->Update(msg, severity);
1042 }*/
1043}
1044
1045#endif
Note: See TracBrowser for help on using the repository browser.