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

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