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

Last change on this file since 10978 was 10967, checked in by tbretz, 13 years ago
Check for NULL in Close
File size: 29.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};
83
84
85#include "FAD.h"
86
87class DataFileRaw : public DataFileImp
88{
89 ofstream fOut;
90
91 off_t fPosTail;
92
93 uint32_t fCounter;
94
95
96 // WRITE uint32_t 0xFAC77e1e (FACT Tele)
97 // ===
98 // WRITE uint32_t TYPE(>0) == 1
99 // WRITE uint32_t ID(>0) == 0
100 // WRITE uint32_t VERSION(>0) == 1
101 // WRITE uint32_t LENGTH
102 // -
103 // WRITE uint32_t TELESCOPE ID
104 // WRITE uint32_t RUNID
105 // ===
106 // WRITE uint32_t TYPE(>0) == 2
107 // WRITE uint32_t ID(>0) == 0
108 // WRITE uint32_t VERSION(>0) == 1
109 // WRITE uint32_t LENGTH
110 // -
111 // WRITE HEADER
112 // ===
113 // [ 40 TIMES
114 // WRITE uint32_t TYPE(>0) == 3
115 // WRITE uint32_t ID(>0) == 0..39
116 // WRITE uint32_t VERSION(>0) == 1
117 // WRITE uint32_t LENGTH
118 // -
119 // WRITE BOARD-HEADER
120 // ]
121 // ===
122 // WRITE uint32_t TYPE(>0) == 4
123 // WRITE uint32_t ID(>0) == 0
124 // WRITE uint32_t VERSION(>0) == 1
125 // WRITE uint32_t LENGTH
126 // -
127 // WRITE FOOTER (empty)
128 // ===
129 // [ N times
130 // WRITE uint32_t TYPE(>0) == 10
131 // WRITE uint32_t ID(>0) == counter
132 // WRITE uint32_t VERSION(>0) == 1
133 // WRITE uint32_t LENGTH HEADER
134 // -
135 // WRITE HEADER+DATA
136 // ]
137 // ===
138 // WRITE uint32_t TYPE ==0
139 // WRITE uint32_t VERSION==0
140 // WRITE uint32_t LENGTH ==0
141 // ===
142 // Go back and write footer
143
144public:
145 DataFileRaw(uint32_t id) : DataFileImp(id) { }
146 ~DataFileRaw() { Close(); }
147
148 void WriteBlockHeader(uint32_t type, uint32_t ver, uint32_t cnt, uint32_t len)
149 {
150 const uint32_t val[4] = { type, ver, cnt, len };
151
152 fOut.write(reinterpret_cast<const char*>(val), sizeof(val));
153 }
154
155 template<typename T>
156 void WriteValue(const T &t)
157 {
158 fOut.write(reinterpret_cast<const char*>(&t), sizeof(T));
159 }
160
161 enum
162 {
163 kIdentifier = 1,
164 kRunHeader,
165 kBoardHeader,
166 kRunSummary,
167 kEvent,
168 };
169
170 virtual bool OpenFile(RUN_HEAD *h)
171 {
172 const string name = FormFileName(h->RunType, "bin");
173
174 errno = 0;
175 fOut.open(name.c_str(), ios_base::out);
176 if (!fOut)
177 {
178 //ostringstream str;
179 //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
180 //Error(str);
181
182 return false;
183 }
184
185 fCounter = 0;
186
187 static uint32_t FACT = 0xFAC77e1e;
188
189 fOut.write(reinterpret_cast<char*>(&FACT), 4);
190
191 WriteBlockHeader(kIdentifier, 1, 0, 8);
192 WriteValue(uint32_t(0));
193 WriteValue(GetRunId());
194
195 WriteBlockHeader(kRunHeader, 1, 0, sizeof(RUN_HEAD)-sizeof(PEVNT_HEADER*));
196 fOut.write(reinterpret_cast<char*>(h), sizeof(RUN_HEAD)-sizeof(PEVNT_HEADER*));
197
198 for (int i=0; i<40; i++)
199 {
200 WriteBlockHeader(kBoardHeader, 1, i, sizeof(PEVNT_HEADER));
201 fOut.write(reinterpret_cast<char*>(h->FADhead+i), sizeof(PEVNT_HEADER));
202 }
203
204 const vector<char> block(sizeof(uint32_t)+sizeof(RUN_TAIL));
205 WriteBlockHeader(kRunSummary, 1, 0, block.size());
206
207 fPosTail = fOut.tellp();
208 fOut.write(block.data(), block.size());
209
210 if (!fOut)
211 {
212 //ostringstream str;
213 //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
214 //Error(str);
215
216 return false;
217 }
218
219 return true;
220 }
221 virtual bool Write(EVENT *evt)
222 {
223 const int sh = sizeof(PEVNT_HEADER)+(NPIX-1)*evt->Roi*2;
224
225 WriteBlockHeader(kEvent, 1, fCounter++, sh);
226 fOut.write(reinterpret_cast<char*>(evt)+2, sh-2);
227 return true;
228 }
229 virtual bool Close(RUN_TAIL *tail= 0)
230 {
231 if (tail)
232 {
233 fOut.seekp(fPosTail);
234
235 WriteValue(uint32_t(1));
236 fOut.write(reinterpret_cast<char*>(tail), sizeof(RUN_TAIL));
237 }
238
239 if (!fOut)
240 {
241 //ostringstream str;
242 //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
243 //Error(str);
244
245 return false;
246 }
247
248 fOut.close();
249
250 if (!fOut)
251 {
252 //ostringstream str;
253 //str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
254 //Error(str);
255
256 return false;
257 }
258
259 return true;
260 }
261};
262
263
264class DataFileFits : public DataFileImp
265{
266 CCfits::FITS* fFile; /// The pointer to the CCfits FITS file
267 CCfits::Table* fTable; /// The pointer to the CCfits binary table
268
269 uint64_t fNumRows; ///the number of rows that have been written already to the FITS file.
270
271public:
272 DataFileFits(uint32_t runid) : DataFileImp(runid), fFile(0)
273 {
274 }
275
276 // --------------------------------------------------------------------------
277 //
278 //! Default destructor
279 //! The Fits file SHOULD have been closed already, otherwise the informations
280 //! related to the RUN_TAIL will NOT be written to the file.
281 //
282 ~DataFileFits() { Close(); }
283
284 // --------------------------------------------------------------------------
285 //
286 //! Add a new column to the vectors storing the column data.
287 //! @param names the vector of string storing the columns names
288 //! @param types the vector of string storing the FITS data format
289 //! @param numElems the number of elements in this column
290 //! @param type the char describing the FITS data format
291 //! @param name the name of the particular column to be added.
292 //
293 inline void AddColumnEntry(vector<string>& names, vector<string>& types, int numElems, char type, string name)
294 {
295 names.push_back(name);
296
297 ostringstream str;
298 if (numElems != 1)
299 str << numElems;
300 str << type;
301 types.push_back(str.str());
302 }
303
304 // --------------------------------------------------------------------------
305 //
306 //! Writes a single header key entry
307 //! @param name the name of the key
308 //! @param value its value
309 //! @param comment the comment associated to that key
310 //
311 //FIXME this function is a duplicate from the class Fits. should we try to merge it ?
312 template <typename T>
313 void WriteKey(const string &name, const T &value, const string &comment)
314 {
315 try
316 {
317 fTable->addKey(name, value, comment);
318 }
319 catch (CCfits::FitsException e)
320 {
321 ostringstream str;
322 str << "Could not add header key ";
323 //TODO pipe the error message somewhere
324 }
325 }
326
327 template <typename T>
328 void WriteKey(const string &name, const int idx, const T &value, const string &comment)
329 {
330 ostringstream str;
331 str << name << idx;
332
333 WriteKey(str.str(), value, comment);
334 }
335
336 // --------------------------------------------------------------------------
337 //
338 //! DataFileFits constructor. This is the one that should be used, not the default one (parameter-less)
339 //! @param runid This parameter should probably be removed. I first thought it was the run number, but apparently it is not
340 //! @param h a pointer to the RUN_HEAD structure that contains the informations relative to this run
341 //
342 bool OpenFile(RUN_HEAD* h)
343 {
344 //Form filename, based on runid and run-type
345 const string fileName = FormFileName(h->RunType, "fits");
346
347 //create the FITS object
348 try
349 {
350 fFile = new CCfits::FITS(fileName, CCfits::RWmode::Write);
351 }
352 catch (CCfits::FitsException e)
353 {
354 ostringstream str;
355 str << "Could not open FITS file " << fileName << " reason: " << e.message();
356 //TODO display the message somewhere
357
358 return false;
359 }
360
361 //create columns according to header
362 ostringstream arrayTypes;
363
364 // uint32_t EventNum ; // EventNumber as from FTM
365 // uint16_t TriggerType ; // Trigger Type from FTM
366 // uint32_t SoftTrig ; // SoftTrigger Info (TBD)
367 // uint32_t PCTime ; // when did event start to arrive at PC
368 // uint32_t BoardTime[NBOARDS];//
369 // int16_t StartPix[NPIX]; // First Channel per Pixel (Pixels sorted according Software ID) ; -1 if not filled
370 // int16_t StartTM[NTMARK]; // First Channel for TimeMark (sorted Hardware ID) ; -1 if not filled
371 // uint16_t Adc_Data[]; // final length defined by malloc ....
372
373 vector<string> colNames;
374 vector<string> dataTypes;
375 AddColumnEntry(colNames, dataTypes, 1, 'V', "EventNum");
376 AddColumnEntry(colNames, dataTypes, 1, 'U', "TriggerType");
377 AddColumnEntry(colNames, dataTypes, 1, 'V', "SoftTrig");
378 AddColumnEntry(colNames, dataTypes, 1, 'V', "PCTime");
379 AddColumnEntry(colNames, dataTypes, NBOARDS, 'V', "BoardTime");
380 AddColumnEntry(colNames, dataTypes, NPIX, 'I', "StartPix");
381 AddColumnEntry(colNames, dataTypes, NTMARK, 'I', "StartTM");
382 AddColumnEntry(colNames, dataTypes, NPIX*h->Nroi, 'U', "Data");
383
384 //actually create the table
385 try
386 {
387 fTable = fFile->addTable("Events", 0, colNames, dataTypes);
388 if (fTable->rows() != 0)
389 {
390 ostringstream str;
391 str << "Error: table created on the fly looks non-empty.";
392 //TODO giev the error text to some error handler
393 //FIXME I guess that this error checking is useless. remove it for performances.
394 }
395 }
396 catch (const CCfits::FitsException &e)
397 {
398 ostringstream str;
399 str << "Could not create FITS table " << "Events" << " in file " << fileName << " reason: " << e.message();
400 //TODO give the error text to some error handler
401
402 Close();
403 return false;
404 }
405
406 //write header data
407 //first the "standard" keys
408 string stringValue;
409 WriteKey("EXTREL", 1.0f, "Release Number");
410 WriteKey("TELESCOP", "FACT", "Telescope that acquired this data");
411 WriteKey("ORIGIN", "ISDC", "Institution that wrote the file");
412 WriteKey("CREATOR", "FACT++ Event Builder", "Program that wrote this file");
413
414 stringValue = Time().GetAsStr();
415 stringValue[10]= 'T';
416 WriteKey("DATE", stringValue, "File creation data");
417 WriteKey("TIMESYS", "TT", "Time frame system");
418 WriteKey("TIMEUNIT", "d", "Time unit");
419 WriteKey("TIMEREF", "UTC", "Time reference frame");
420 //FIXME should we also put the start and stop time of the received data ?
421 //now the events header related variables
422 WriteKey("VERSION", h->Version, "Builder version");
423 WriteKey("RUNTYPE", h->RunType, "Type of run");
424 WriteKey("NBOARD", h->NBoard, "Number of acquisition boards");
425 WriteKey("NPIX", h->NPix, "Number of pixels");
426 WriteKey("NTM", h->NTm, "Number of Time marks");
427 WriteKey("NROI", h->Nroi, "Number of slices per pixels");
428
429 //now the boards related keywords
430 for (int i=0; i<h->NBoard; i++)
431 {
432 const PEVNT_HEADER &hh = h->FADhead[i];
433
434 WriteKey("STPKGFG", i, hh.start_package_flag,
435 "Start package flag");
436
437 WriteKey("PKGLEN", i, hh.package_length,
438 "Package length");
439
440 WriteKey("VERNO", i, hh.version_no,
441 "Version number");
442
443 WriteKey("PLLLCK", i, hh.PLLLCK,
444 "");
445/*
446 WriteKey("TRIGCRC", i, hh.trigger_crc,
447 "Trigger CRC");
448
449 WriteKey("TRIGTYP", i, hh.trigger_type,
450 "Trigger type");
451
452 WriteKey("TRIGID", i, hh.trigger_id,
453 "Trigger ID");
454
455 WriteKey("EVTCNTR", i, hh.fad_evt_counter,
456 "FAD Event Counter");
457*/
458 WriteKey("REFCLK", i, hh.REFCLK_frequency,
459 "Reference Clock Frequency");
460
461 WriteKey("BOARDID", i, hh.board_id,
462 "Board ID");
463
464 WriteKey("PHASESH", i, hh.adc_clock_phase_shift,
465 "ADC clock phase shift");
466
467 //WriteKey("TRGGEN", i, hh.number_of_triggers_to_generate,
468 // "Number of triggers to generate");
469
470 WriteKey("PRESC", i, hh.trigger_generator_prescaler,
471 "Trigger generator prescaler");
472
473 WriteKey("DNA", i, hh.DNA, "DNA");
474 WriteKey("TIME", i, hh.time, "Time");
475 WriteKey("RUNNB", i, hh.runnumber, "Run number");
476/*
477 for (int j=0;j<NTemp;j++)
478 {
479 str.str(""); str2.str("");
480 str << "DRS_T" << i << j;
481 str2 << "DRS temperature #" << i << " " << j;
482 WriteKey(str.str(), h->FADhead[i].drs_temperature[j], str2.str());
483 }
484*/
485 for (int j=0;j<NDAC;j++)
486 WriteKey("DAC", i*NDAC+j, hh.dac[j], "DAC");
487
488 //Last but not least, add header keys that will be updated when closing the file
489 WriteFooter(NULL);
490 }
491
492 return true;
493 }
494
495
496 int WriteColumns(size_t &start, size_t size, void *e)
497 {
498 int status = 0;
499 fits_write_tblbytes(fFile->fitsPointer(), fNumRows, start, size, reinterpret_cast<unsigned char*>(e), &status);
500 start += size;
501 return status;
502 }
503
504 // --------------------------------------------------------------------------
505 //
506 //! This writes one event to the file
507 //! @param e the pointer to the EVENT
508 //
509 virtual bool Write(EVENT *e)
510 {
511 //FIXME As discussed earlier, we do not swap the bytes yet.
512 fTable->makeThisCurrent();
513
514 //insert a new row
515 int status(0);
516 if (fits_insert_rows(fTable->fitsPointer(), fNumRows, 1, &status))
517 {
518 ostringstream str;
519 str << "Could not insert a row in fits file";
520 //TODO pipe this error message to the appropriate error stream
521 }
522 fNumRows++;
523
524 const int sh = sizeof(PEVNT_HEADER)+(NPIX-1)*e->Roi*2;
525
526 // column size pointer
527 size_t col = 1;
528 if (!WriteColumns(col, sh, e))
529 return true;
530
531 //TODO output an error
532 return false;
533
534 /*
535 //write the data, chunk by chunk
536 //FIXME hard-coded size corresponds to current variables of the event, in bytes.
537 //FIXME no padding was taken into account. Because smallest member is 2 bytes, I don't think that this should be a problem.
538 const long sizeInBytesOfEventBeforePointers = 16;
539
540 long col = 1;
541 if (FitsWriteTblBytes(col, sizeInBytesOfEventBeforePointers, e))
542 {
543 //TODO output an error
544 return false;
545 }
546 if (FitsWriteTblBytes(col, NBOARDS*2, e->BoardTime))
547 {
548 //TODO output an error
549 return false;
550 }
551 if (FitsWriteTblBytes(col, NPIX*2, e->StartPix))
552 {
553 //TODO output an error
554 return false;
555 }
556 if (FitsWriteTblBytes(col, NTMARK*2, e->StartTM))
557 {
558 //TODO output an error
559 return false;
560 }
561 if (FitsWriteTblBytes(col, NPIX*fRoi*2, e->Adc_Data))
562 {
563 //TODO output an error
564 return false;
565 }
566 return true;*/
567 }
568
569 void WriteFooter(RUN_TAIL *rt)
570 {
571 //write final header keys
572 fTable->makeThisCurrent();
573
574 WriteKey("NBEVTOK", rt ? rt->nEventsOk : uint32_t(0),
575 "How many events were written");
576
577 WriteKey("NBEVTREJ", rt ? rt->nEventsRej : uint32_t(0),
578 "How many events were rejected by SW-trig");
579
580 WriteKey("NBEVTBAD", rt ? rt->nEventsBad : uint32_t(0),
581 "How many events were rejected by Error");
582
583 //FIXME shouldn't we convert start and stop time to MjD first ?
584 //FIXME shouldn't we also add an MjD reference ?
585
586 WriteKey("TSTART", rt ? rt->PCtime0 : uint32_t(0),
587 "Time when first event received");
588
589 WriteKey("TSTOP", rt ? rt->PCtimeX : uint32_t(0),
590 "Time when last event received");
591 }
592
593 // --------------------------------------------------------------------------
594 //
595 //! Closes the file, and before this it write the TAIL data
596 //! @param rt the pointer to the RUN_TAIL data structure
597 //
598 virtual bool Close(RUN_TAIL *rt = 0)
599 {
600 if (!fFile)
601 return false;
602
603 WriteFooter(rt);
604
605 delete fFile;
606 fFile = NULL;
607
608 return true;
609 }
610
611};
612
613class EventBuilderWrapper
614{
615public:
616 // FIXME
617 static EventBuilderWrapper *This;
618
619private:
620 boost::thread fThread;
621
622 enum CommandStates_t // g_runStat
623 {
624 kAbort = -2, // quit as soon as possible ('abort')
625 kExit = -1, // stop reading, quit when buffered events done ('exit')
626 kInitialize = 0, // 'initialize' (e.g. dim not yet started)
627 kHybernate = 1, // do nothing for long time ('hybernate') [wakeup within ~1sec]
628 kSleep = 2, // do nothing ('sleep') [wakeup within ~10msec]
629 kModeFlush = 10, // read data from camera, but skip them ('flush')
630 kModeTest = 20, // read data and process them, but do not write to disk ('test')
631 kModeFlag = 30, // read data, process and write all to disk ('flag')
632 kModeRun = 40, // read data, process and write selected to disk ('run')
633 };
634
635 MessageImp &fMsg;
636
637 enum
638 {
639 kCurrent = 0,
640 kTotal = 1
641 };
642
643 bool fFitsFormat;
644
645 uint32_t fMaxRun;
646 uint32_t fNumEvts[2];
647
648 DimDescribedService fDimFiles;
649 DimDescribedService fDimRuns;
650 DimDescribedService fDimEvents;
651 DimDescribedService fDimCurrentEvent;
652
653public:
654 EventBuilderWrapper(MessageImp &msg) : fMsg(msg),
655 fFitsFormat(false), fMaxRun(0),
656 fDimFiles ("FAD_CONTROL/FILES", "X:1", ""),
657 fDimRuns ("FAD_CONTROL/RUNS", "I:1", ""),
658 fDimEvents("FAD_CONTROL/EVENTS", "I:2", ""),
659 fDimCurrentEvent("FAD_CONTROL/CURRENT_EVENT", "I:1", "")
660 {
661 if (This)
662 throw logic_error("EventBuilderWrapper cannot be instantiated twice.");
663
664 This = this;
665
666 memset(fNumEvts, 0, sizeof(fNumEvts));
667
668 Update(fDimRuns, uint32_t(0));
669 Update(fDimCurrentEvent, uint32_t(0));
670 Update(fDimEvents, fNumEvts);
671 }
672 ~EventBuilderWrapper()
673 {
674 Abort();
675 // FIXME: Used timed_join and abort afterwards
676 // What's the maximum time the eb need to abort?
677 fThread.join();
678 //fMsg.Info("EventBuilder stopped.");
679
680 for (vector<DataFileImp*>::iterator it=fFiles.begin(); it!=fFiles.end(); it++)
681 delete *it;
682 }
683
684 void Update(ostringstream &msg, int severity)
685 {
686 fMsg.Update(msg, severity);
687 }
688
689 bool IsThreadRunning()
690 {
691 return !fThread.timed_join(boost::posix_time::microseconds(0));
692 }
693
694 void SetMaxMemory(unsigned int mb) const
695 {
696 if (mb*1000000<GetUsedMemory())
697 {
698 // fMsg.Warn("...");
699 return;
700 }
701
702 g_maxMem = mb*1000000;
703 }
704
705 void Start(const vector<tcp::endpoint> &addr)
706 {
707 if (IsThreadRunning())
708 {
709 fMsg.Warn("Start - EventBuilder still running");
710 return;
711 }
712
713 int cnt = 0;
714 for (size_t i=0; i<40; i++)
715 {
716 if (addr[i]==tcp::endpoint())
717 {
718 g_port[i].sockDef = -1;
719 continue;
720 }
721
722 // -1: if entry shell not be used
723 // 0: event builder will connect but ignore the events
724 // 1: event builder will connect and build events
725 g_port[i].sockDef = 1;
726
727 g_port[i].sockAddr.sin_family = AF_INET;
728 g_port[i].sockAddr.sin_addr.s_addr = htonl(addr[i].address().to_v4().to_ulong());
729 g_port[i].sockAddr.sin_port = htons(addr[i].port());
730
731 cnt++;
732 }
733
734// g_maxBoards = cnt;
735 g_actBoards = cnt;
736
737 g_runStat = kModeRun;
738
739 fMsg.Message("Starting EventBuilder thread");
740
741 fThread = boost::thread(StartEvtBuild);
742 }
743 void Abort()
744 {
745 fMsg.Message("Signal abort to EventBuilder thread...");
746 g_runStat = kAbort;
747 }
748
749 void Exit()
750 {
751 fMsg.Message("Signal exit to EventBuilder thread...");
752 g_runStat = kExit;
753 }
754
755 /*
756 void Wait()
757 {
758 fThread.join();
759 fMsg.Message("EventBuilder stopped.");
760 }*/
761
762 void Hybernate() const { g_runStat = kHybernate; }
763 void Sleep() const { g_runStat = kSleep; }
764 void FlushMode() const { g_runStat = kModeFlush; }
765 void TestMode() const { g_runStat = kModeTest; }
766 void FlagMode() const { g_runStat = kModeFlag; }
767 void RunMode() const { g_runStat = kModeRun; }
768
769 // FIXME: To be removed
770 void SetMode(int mode) const { g_runStat = mode; }
771
772 bool IsConnected(int i) const { return gi_NumConnect[i]==7; }
773 bool IsDisconnected(int i) const { return gi_NumConnect[i]<=0; }
774 int GetNumConnected(int i) const { return gi_NumConnect[i]; }
775
776 size_t GetUsedMemory() const { return gi_usedMem; }
777
778 virtual int CloseOpenFiles() { CloseRunFile(0, 0); return 0; }
779
780
781 /*
782 struct OpenFileToDim
783 {
784 int code;
785 char fileName[FILENAME_MAX];
786 };
787
788 SignalRunOpened(runid, filename);
789 // Send num open files
790 // Send runid, (more info about the run?), filename via dim
791
792 SignalEvtWritten(runid);
793 // Send num events written of newest file
794
795 SignalRunClose(runid);
796 // Send new num open files
797 // Send empty file-name if no file is open
798
799 */
800
801 // -------------- Mapped event builder callbacks ------------------
802
803 vector<DataFileImp*> fFiles;
804
805 template<class T>
806 void Update(DimDescribedService &svc, const T &data) const
807 {
808 cout << "Update: " << svc.getName() << " (" << sizeof(T) << ")" << endl;
809 svc.setData(const_cast<T*>(&data), sizeof(T));
810 svc.updateService();
811 }
812
813 FileHandle_t runOpen(uint32_t runid, RUN_HEAD *h, size_t)
814 {
815 // Check if file already exists...
816 DataFileImp *file = fFitsFormat ?
817 static_cast<DataFileImp*>(new DataFileFits(runid)) :
818 static_cast<DataFileImp*>(new DataFileRaw(runid));
819
820 try
821 {
822 if (!file->OpenFile(h))
823 return 0;
824 }
825 catch (const exception &e)
826 {
827 return 0;
828 }
829
830 cout << "OPEN_FILE #" << runid << " (" << file << ")" << endl;
831 cout << " Ver= " << h->Version << endl;
832 cout << " Typ= " << h->RunType << endl;
833 cout << " Nb = " << h->NBoard << endl;
834 cout << " Np = " << h->NPix << endl;
835 cout << " NTm= " << h->NTm << endl;
836 cout << " roi= " << h->Nroi << endl;
837
838 fFiles.push_back(file);
839
840 if (runid>fMaxRun)
841 {
842 fMaxRun = runid;
843 fNumEvts[kCurrent] = 0;
844
845 Update(fDimRuns, fMaxRun);
846 Update(fDimEvents, fNumEvts);
847 Update(fDimCurrentEvent, uint32_t(0));
848 }
849
850 Update(fDimFiles, fFiles.size());
851
852// fDimFiles.setData(fFiles.size());
853// fDimFiles.update();
854
855 return reinterpret_cast<FileHandle_t>(file);
856 }
857
858 int runWrite(FileHandle_t handler, EVENT *e, size_t)
859 {
860 DataFileImp *file = reinterpret_cast<DataFileImp*>(handler);
861
862 cout << "WRITE_EVENT " << file->GetRunId() << endl;
863
864 cout << " Evt=" << e->EventNum << endl;
865 cout << " Typ=" << e->TriggerType << endl;
866 cout << " roi=" << e->Roi << endl;
867 cout << " trg=" << e->SoftTrig << endl;
868 cout << " tim=" << e->PCTime << endl;
869
870 if (!file->Write(e))
871 return -1;
872
873 if (file->GetRunId()==fMaxRun)
874 {
875 Update(fDimCurrentEvent, e->EventNum);
876 fNumEvts[kCurrent]++;
877 }
878
879 fNumEvts[kTotal]++;
880 Update(fDimEvents, fNumEvts);
881
882 // ===> SignalEvtWritten(runid);
883 // Send num events written of newest file
884
885 /* close run runId (all all runs if runId=0) */
886 /* return: 0=close scheduled / >0 already closed / <0 does not exist */
887 //CloseRunFile(file->GetRunId(), time(NULL)+2) ;
888
889 return 0;
890 }
891
892 int runClose(FileHandle_t handler, RUN_TAIL *tail, size_t)
893 {
894 DataFileImp *file = reinterpret_cast<DataFileImp*>(handler);
895
896 const vector<DataFileImp*>::iterator it = find(fFiles.begin(), fFiles.end(), file);
897 if (it==fFiles.end())
898 {
899 ostringstream str;
900 str << "File handler (" << handler << ") requested to close by event builder doesn't exist.";
901 fMsg.Fatal(str);
902 return -1;
903 }
904
905 ostringstream str;
906 str << "CLOSE_RUN requested for " << file->GetRunId() << " (" << file << ")" <<endl;
907 fMsg.Debug(str);
908
909 fFiles.erase(it);
910
911 Update(fDimFiles, fFiles.size());
912
913 //fDimFiles.setData(fFiles.size());
914 //fDimFiles.update();
915
916 const bool rc = file->Close(tail);
917 if (!rc)
918 {
919 // Error message
920 }
921
922 delete file;
923
924 // ==> SignalRunClose(runid);
925 // Send new num open files
926 // Send empty file-name if no file is open
927
928 return rc ? 0 : -1;
929 }
930};
931
932EventBuilderWrapper *EventBuilderWrapper::This = 0;
933
934// ----------- Event builder callbacks implementation ---------------
935extern "C"
936{
937 FileHandle_t runOpen(uint32_t irun, RUN_HEAD *runhd, size_t len)
938 {
939 return EventBuilderWrapper::This->runOpen(irun, runhd, len);
940 }
941
942 int runWrite(FileHandle_t fileId, EVENT *event, size_t len)
943 {
944 return EventBuilderWrapper::This->runWrite(fileId, event, len);
945 }
946
947 int runClose(FileHandle_t fileId, RUN_TAIL *runth, size_t len)
948 {
949 return EventBuilderWrapper::This->runClose(fileId, runth, len);
950 }
951
952 void factOut(int severity, int err, char *message)
953 {
954 // FIXME: Make the output to the console stream thread-safe
955 ostringstream str;
956 str << "EventBuilder(";
957 if (err<0)
958 str << "---";
959 else
960 str << err;
961 str << "): " << message;
962 EventBuilderWrapper::This->Update(str, severity);
963 }
964
965 void factStat(int severity, int err, char* message )
966 {
967 static string last;
968 if (message==last)
969 return;
970
971 if (err!=-1)
972 factOut(severity, err, message);
973 else
974 {
975 ostringstream str("Status: ");
976 str << message;
977 EventBuilderWrapper::This->Update(str, severity);
978 }
979
980 last = message;
981 }
982
983 /*
984 void message(int severity, const char *msg)
985 {
986 EventBuilderWrapper::This->Update(msg, severity);
987 }*/
988}
989
990#endif
Note: See TracBrowser for help on using the repository browser.