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

Last change on this file since 11379 was 11376, checked in by tbretz, 15 years ago
Updated writing of FITS; pipe MessageImp to all writers; enabled initialization of fRunNumber; updated FITS writing to a simplified but working version.
File size: 51.8 KB
Line 
1#ifndef FACT_EventBuilderWrapper
2#define FACT_EventBuilderWrapper
3
4#include <sstream>
5
6#if BOOST_VERSION < 104400
7#if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 4))
8#undef BOOST_HAS_RVALUE_REFS
9#endif
10#endif
11#include <boost/thread.hpp>
12#include <boost/date_time/posix_time/posix_time_types.hpp>
13
14#include <CCfits/CCfits>
15
16#include "EventBuilder.h"
17
18extern "C" {
19 extern void StartEvtBuild();
20 extern int CloseRunFile(uint32_t runId, uint32_t closeTime);
21}
22
23namespace ba = boost::asio;
24namespace bs = boost::system;
25
26using ba::ip::tcp;
27
28using namespace std;
29
30class DataFileImp
31{
32 uint32_t fRunId;
33
34protected:
35 MessageImp &fLog;
36 string fFileName;
37
38public:
39 DataFileImp(uint32_t id, MessageImp &imp) : fRunId(id), fLog(imp) { }
40 virtual ~DataFileImp() { }
41
42 virtual bool OpenFile(RUN_HEAD* h) = 0;
43 virtual bool Write(EVENT *) = 0;
44 virtual bool Close(RUN_TAIL * = 0) = 0;
45
46 const string &GetFileName() const { return fFileName; }
47
48 uint32_t GetRunId() const { return fRunId; }
49
50 // --------------------------------------------------------------------------
51 //
52 //! This creates an appropriate file name for a particular run number and type
53 //! @param runNumber the run number for which a filename is to be created
54 //! @param runType an int describing the kind of run. 0=Data, 1=Pedestal, 2=Calibration, 3=Calibrated data
55 //! @param extension a string containing the extension to be appened to the file name
56 //
57 string FormFileName(uint32_t runType, string extension)
58 {
59 //TODO where am I supposed to get the base directory from ?
60 //TODO also, for creating subsequent directories, should I use the functions from the dataLogger ?
61 string baseDirectory = "./Run";
62
63 ostringstream result;
64// result << baseDirectory;
65// result << Time::fmt("/%Y/%m/%d/") << (Time() - boost::posix_time::time_duration(12,0,0));
66 result << setfill('0') << setw(8) << fRunId;
67 result << ".001_";
68 switch (runType)
69 {
70 case -1:
71 result << 'T';
72 break;
73 case 0:
74 result << 'D';
75 break;
76 case 1:
77 result << 'P';
78 break;
79 case 2:
80 result << 'C';
81 break;
82 case 3:
83 result << 'N';
84 break;
85 default:
86 result << runType;
87 };
88 result << "." << extension;
89
90 return result.str();
91 }
92};
93
94class DataFileNone : public DataFileImp
95{
96public:
97 DataFileNone(uint32_t id, MessageImp &imp) : DataFileImp(id, imp) { }
98
99 bool OpenFile(RUN_HEAD* h)
100 {
101 fFileName = "/dev/null";
102 cout << "OPEN_FILE #" << GetRunId() << " (" << this << ")" << endl;
103 cout << " Ver= " << h->Version << endl;
104 cout << " Typ= " << h->RunType << endl;
105 cout << " Nb = " << h->NBoard << endl;
106 cout << " Np = " << h->NPix << endl;
107 cout << " NTm= " << h->NTm << endl;
108 cout << " roi= " << h->Nroi << endl;
109
110 return true;
111 }
112 bool Write(EVENT *)
113 {
114 return true;
115 }
116 bool Close(RUN_TAIL * = 0)
117 {
118 cout << "CLOSE FILE #" << GetRunId() << " (" << this << ")" << endl;
119 return true;
120 }
121};
122
123class DataFileDebug : public DataFileNone
124{
125public:
126 DataFileDebug(uint32_t id, MessageImp &imp) : DataFileNone(id, imp) { }
127
128 bool Write(EVENT *e)
129 {
130 cout << "WRITE_EVENT #" << GetRunId() << " (" << e->EventNum << ")" << endl;
131 cout << " Typ=" << e->TriggerType << endl;
132 cout << " roi=" << e->Roi << endl;
133 cout << " trg=" << e->SoftTrig << endl;
134 cout << " tim=" << e->PCTime << endl;
135
136 return true;
137 }
138};
139
140#include "FAD.h"
141
142class DataFileRaw : public DataFileImp
143{
144 ofstream fOut;
145
146 off_t fPosTail;
147
148 uint32_t fCounter;
149
150
151 // WRITE uint32_t 0xFAC77e1e (FACT Tele)
152 // ===
153 // WRITE uint32_t TYPE(>0) == 1
154 // WRITE uint32_t ID(>0) == 0
155 // WRITE uint32_t VERSION(>0) == 1
156 // WRITE uint32_t LENGTH
157 // -
158 // WRITE uint32_t TELESCOPE ID
159 // WRITE uint32_t RUNID
160 // ===
161 // WRITE uint32_t TYPE(>0) == 2
162 // WRITE uint32_t ID(>0) == 0
163 // WRITE uint32_t VERSION(>0) == 1
164 // WRITE uint32_t LENGTH
165 // -
166 // WRITE HEADER
167 // ===
168 // [ 40 TIMES
169 // WRITE uint32_t TYPE(>0) == 3
170 // WRITE uint32_t ID(>0) == 0..39
171 // WRITE uint32_t VERSION(>0) == 1
172 // WRITE uint32_t LENGTH
173 // -
174 // WRITE BOARD-HEADER
175 // ]
176 // ===
177 // WRITE uint32_t TYPE(>0) == 4
178 // WRITE uint32_t ID(>0) == 0
179 // WRITE uint32_t VERSION(>0) == 1
180 // WRITE uint32_t LENGTH
181 // -
182 // WRITE FOOTER (empty)
183 // ===
184 // [ N times
185 // WRITE uint32_t TYPE(>0) == 10
186 // WRITE uint32_t ID(>0) == counter
187 // WRITE uint32_t VERSION(>0) == 1
188 // WRITE uint32_t LENGTH HEADER
189 // -
190 // WRITE HEADER+DATA
191 // ]
192 // ===
193 // WRITE uint32_t TYPE ==0
194 // WRITE uint32_t VERSION==0
195 // WRITE uint32_t LENGTH ==0
196 // ===
197 // Go back and write footer
198
199public:
200 DataFileRaw(uint32_t id, MessageImp &imp) : DataFileImp(id, imp), fPosTail(0) { }
201 ~DataFileRaw() { if (fOut.is_open()) Close(); }
202
203 void WriteBlockHeader(uint32_t type, uint32_t ver, uint32_t cnt, uint32_t len)
204 {
205 const uint32_t val[4] = { type, ver, cnt, len };
206
207 fOut.write(reinterpret_cast<const char*>(val), sizeof(val));
208 }
209
210 template<typename T>
211 void WriteValue(const T &t)
212 {
213 fOut.write(reinterpret_cast<const char*>(&t), sizeof(T));
214 }
215
216 enum
217 {
218 kEndOfFile = 0,
219 kIdentifier = 1,
220 kRunHeader,
221 kBoardHeader,
222 kRunSummary,
223 kEvent,
224 };
225
226 bool OpenFile(RUN_HEAD *h)
227 {
228 const string name = FormFileName(h->RunType, "bin");
229 if (access(name.c_str(), F_OK)==0)
230 {
231 fLog.Error("File '"+name+"' already exists.");
232 return false;
233 }
234
235 fFileName = name;
236
237 errno = 0;
238 fOut.open(name.c_str(), ios_base::out);
239 if (!fOut)
240 {
241 ostringstream str;
242 str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
243 fLog.Error(str);
244
245 return false;
246 }
247
248 fCounter = 0;
249
250 static uint32_t FACT = 0xFAC77e1e;
251
252 fOut.write(reinterpret_cast<char*>(&FACT), 4);
253
254 WriteBlockHeader(kIdentifier, 1, 0, 8);
255 WriteValue(uint32_t(0));
256 WriteValue(GetRunId());
257
258 WriteBlockHeader(kRunHeader, 1, 0, sizeof(RUN_HEAD)-sizeof(PEVNT_HEADER*));
259 fOut.write(reinterpret_cast<char*>(h), sizeof(RUN_HEAD)-sizeof(PEVNT_HEADER*));
260
261 for (int i=0; i<40; i++)
262 {
263 WriteBlockHeader(kBoardHeader, 1, i, sizeof(PEVNT_HEADER));
264 fOut.write(reinterpret_cast<char*>(h->FADhead+i), sizeof(PEVNT_HEADER));
265 }
266
267 // FIXME: Split this
268 const vector<char> block(sizeof(uint32_t)+sizeof(RUN_TAIL));
269 WriteBlockHeader(kRunSummary, 1, 0, block.size());
270
271 fPosTail = fOut.tellp();
272 fOut.write(block.data(), block.size());
273
274 if (!fOut)
275 {
276 ostringstream str;
277 str << "Open file " << name << ": " << strerror(errno) << " (errno=" << errno << ")";
278 fLog.Error(str);
279
280 return false;
281 }
282
283 return true;
284 }
285 bool Write(EVENT *evt)
286 {
287 const int sh = sizeof(EVENT)-2 + NPIX*evt->Roi*2;
288
289 WriteBlockHeader(kEvent, 1, fCounter++, sh);
290 fOut.write(reinterpret_cast<char*>(evt)+2, sh);
291 return true;
292 }
293 bool Close(RUN_TAIL *tail= 0)
294 {
295 WriteBlockHeader(kEndOfFile, 0, 0, 0);
296
297 if (tail)
298 {
299 fOut.seekp(fPosTail);
300
301 WriteValue(uint32_t(1));
302 fOut.write(reinterpret_cast<char*>(tail), sizeof(RUN_TAIL));
303 }
304
305 if (!fOut)
306 {
307 ostringstream str;
308 str << " Writing footer: " << strerror(errno) << " (errno=" << errno << ")";
309 fLog.Error(str);
310
311 return false;
312 }
313
314 fOut.close();
315
316 if (!fOut)
317 {
318 ostringstream str;
319 str << "Closing file: " << strerror(errno) << " (errno=" << errno << ")";
320 fLog.Error(str);
321
322 return false;
323 }
324
325 return true;
326 }
327};
328
329#ifdef HAVE_FITS
330class DataFileFits : public DataFileImp
331{
332 CCfits::FITS* fFile; /// The pointer to the CCfits FITS file
333 CCfits::Table* fTable; /// The pointer to the CCfits binary table
334
335 uint64_t fNumRows; ///the number of rows that have been written already to the FITS file.
336
337 Converter *fConv;
338
339public:
340 DataFileFits(uint32_t runid, MessageImp &imp) :
341 DataFileImp(runid, imp), fFile(0), fNumRows(0), fConv(0)
342 {
343 }
344
345 // --------------------------------------------------------------------------
346 //
347 //! Default destructor
348 //! The Fits file SHOULD have been closed already, otherwise the informations
349 //! related to the RUN_TAIL will NOT be written to the file.
350 //
351 ~DataFileFits() { Close(); delete fConv; }
352
353 // --------------------------------------------------------------------------
354 //
355 //! Add a new column to the vectors storing the column data.
356 //! @param names the vector of string storing the columns names
357 //! @param types the vector of string storing the FITS data format
358 //! @param numElems the number of elements in this column
359 //! @param type the char describing the FITS data format
360 //! @param name the name of the particular column to be added.
361 //
362 inline void AddColumnEntry(vector<string>& names, vector<string>& types, int numElems, char type, string name)
363 {
364 names.push_back(name);
365
366 ostringstream str;
367 if (numElems != 1)
368 str << numElems;
369 str << type;
370 types.push_back(str.str());
371 }
372
373 // --------------------------------------------------------------------------
374 //
375 //! Writes a single header key entry
376 //! @param name the name of the key
377 //! @param value its value
378 //! @param comment the comment associated to that key
379 //
380 //FIXME this function is a duplicate from the class Fits. should we try to merge it ?
381 template <typename T>
382 void WriteKey(const string &name, const T &value, const string &comment)
383 {
384 try
385 {
386 fTable->addKey(name, value, comment);
387 }
388 catch (CCfits::FitsException e)
389 {
390 ostringstream str;
391 str << "Could not add header key " << name;
392 fLog.Error(str);
393 }
394 }
395
396 template <typename T>
397 void WriteKey(const string &name, const int idx, const T &value, const string &comment)
398 {
399 ostringstream str;
400 str << name << idx;
401
402 WriteKey(str.str(), value, comment);
403 }
404
405 // --------------------------------------------------------------------------
406 //
407 //! DataFileFits constructor. This is the one that should be used, not the default one (parameter-less)
408 //! @param runid This parameter should probably be removed. I first thought it was the run number, but apparently it is not
409 //! @param h a pointer to the RUN_HEAD structure that contains the informations relative to this run
410 //
411 bool OpenFile(RUN_HEAD* h)
412 {
413 //Form filename, based on runid and run-type
414 const string fileName = FormFileName(h->RunType, "fits");
415 if (access(fileName.c_str(), F_OK)==0)
416 {
417 fLog.Error("File '"+fileName+"' already exists.");
418 return false;
419 }
420
421 fFileName = fileName;
422
423 /*
424 out <<
425 "SIMPLE = T / file does conform to FITS standard "
426 "BITPIX = 8 / number of bits per data pixel "
427 "NAXIS = 0 / number of data axes "
428 "EXTEND = T / FITS dataset may contain extensions "
429 "COMMENT FITS (Flexible Image Transport System) format is defined in 'Astronomy"
430 "COMMENT and Astrophysics', volume 376, page 359; bibcode: 2001A&A...376..359H "
431 "END ";
432 for (int i=0; i<29; i++)
433 out << " "
434 */
435
436 //create the FITS object
437 try
438 {
439 fFile = new CCfits::FITS(fileName, CCfits::RWmode::Write);
440 }
441 catch (CCfits::FitsException e)
442 {
443 ostringstream str;
444 str << "Could not open FITS file " << fileName << ": " << e.message();
445 fLog.Error(str);
446 return false;
447 }
448
449 vector<string> colNames;
450 vector<string> dataTypes;
451 AddColumnEntry(colNames, dataTypes, 1, 'J', "EventNum");
452 AddColumnEntry(colNames, dataTypes, 1, 'I', "TriggerType");
453 AddColumnEntry(colNames, dataTypes, 1, 'J', "SoftTrig");
454 AddColumnEntry(colNames, dataTypes, 1, 'J', "PCTime");
455 AddColumnEntry(colNames, dataTypes, NBOARDS, 'J', "BoardTime");
456 AddColumnEntry(colNames, dataTypes, NPIX, 'I', "StartPix");
457 AddColumnEntry(colNames, dataTypes, NTMARK, 'I', "StartTM");
458 AddColumnEntry(colNames, dataTypes, NPIX*h->Nroi, 'I', "Data");
459
460 ostringstream fmt;
461 fmt << "I:1;S:1;I:1;I:1";
462 fmt << ";I:" << NBOARDS;
463 fmt << ";S:" << NPIX;
464 fmt << ";S:" << NTMARK;
465 fmt << ";S:" << NPIX*h->Nroi;
466
467 fConv = new Converter(fmt.str());
468
469 //actually create the table
470 try
471 {
472 fTable = fFile->addTable("Events", 0, colNames, dataTypes);
473 }
474 catch (const CCfits::FitsException &e)
475 {
476 ostringstream str;
477 str << "Could not create FITS table 'Events' in file " << fileName << " reason: " << e.message();
478 fLog.Error(str);
479 return false;
480 }
481
482 if (fTable->rows() != 0)
483 {
484 fLog.Error("FITS table created on the fly looks non-empty.");
485 return false;
486 }
487
488 //write header data
489 //first the "standard" keys
490 WriteKey("EXTREL", 1.0f, "Release Number");
491 WriteKey("TELESCOP", "FACT", "Telescope that acquired this data");
492 WriteKey("ORIGIN", "ISDC", "Institution that wrote the file");
493 WriteKey("CREATOR", "FACT++ Event Builder", "Program that wrote this file");
494
495 string stringValue;
496 stringValue = Time().GetAsStr();
497 stringValue[10]= 'T';
498 WriteKey("DATE", stringValue, "File creation data");
499 WriteKey("TIMESYS", "TT", "Time frame system");
500 WriteKey("TIMEUNIT", "d", "Time unit");
501 WriteKey("TIMEREF", "UTC", "Time reference frame");
502 //FIXME should we also put the start and stop time of the received data ?
503 //now the events header related variables
504 WriteKey("VERSION", h->Version, "Builder version");
505 WriteKey("RUNTYPE", h->RunType, "Type of run");
506 WriteKey("NBOARD", h->NBoard, "Number of acquisition boards");
507 WriteKey("NPIX", h->NPix, "Number of pixels");
508 WriteKey("NTM", h->NTm, "Number of Time marks");
509 WriteKey("NROI", h->Nroi, "Number of slices per pixels");
510/*
511 //now the boards related keywords
512 for (int i=0; i<h->NBoard; i++)
513 {
514 const PEVNT_HEADER &hh = h->FADhead[i];
515
516 WriteKey("STPKGFG", i, hh.start_package_flag,
517 "Start package flag");
518
519 WriteKey("PKGLEN", i, hh.package_length,
520 "Package length");
521
522 WriteKey("VERNO", i, hh.version_no,
523 "Version number");
524
525 WriteKey("STATUS", i, hh.PLLLCK,
526 "");
527
528// WriteKey("TRIGCRC", i, hh.trigger_crc,
529// "Trigger CRC");
530
531// WriteKey("TRIGTYP", i, hh.trigger_type,
532// "Trigger type");
533
534// WriteKey("TRIGID", i, hh.trigger_id,
535// "Trigger ID");
536
537// WriteKey("EVTCNTR", i, hh.fad_evt_counter,
538// "FAD Event Counter");
539
540// WriteKey("REFCLK", i, hh.REFCLK_frequency,
541// "Reference Clock Frequency");
542
543 WriteKey("BOARDID", i, hh.board_id,
544 "Board ID");
545
546 WriteKey("PHASESH", i, hh.adc_clock_phase_shift,
547 "ADC clock phase shift");
548
549 WriteKey("TRGGEN", i, hh.number_of_triggers_to_generate,
550 "Number of triggers to generate");
551
552 WriteKey("PRESC", i, hh.trigger_generator_prescaler,
553 "Trigger generator prescaler");
554
555 WriteKey("DNA", i, hh.DNA, "DNA");
556 WriteKey("TIME", i, hh.time, "Time");
557 WriteKey("RUNNB", i, hh.runnumber, "Run number");
558
559// for (int j=0;j<NTemp;j++)
560// {
561// str.str(""); str2.str("");
562// str << "DRS_T" << i << j;
563// str2 << "DRS temperature #" << i << " " << j;
564// WriteKey(str.str(), h->FADhead[i].drs_temperature[j], str2.str());
565// }
566 for (int j=0;j<NDAC;j++)
567 WriteKey("DAC", i*NDAC+j, hh.dac[j], "DAC");
568 }
569*/
570
571 //Last but not least, add header keys that will be updated when closing the file
572 //WriteFooter(NULL);
573
574 return true;
575 }
576
577
578 int WriteColumns(size_t &start, size_t size, const void *e)
579 {
580 int status = 0;
581 fits_write_tblbytes(fFile->fitsPointer(), fNumRows, start, size,
582 (unsigned char*)e, &status);
583 if (status)
584 {
585 char text[30];//max length of cfitsio error strings (from doc)
586 fits_get_errstatus(status, text);
587
588 ostringstream str;
589 str << "Writing FITS row " << fNumRows << ": " << text << " (file_write_tblbytes, rc=" << status << ")";
590 fLog.Error(str);
591 }
592
593 start += size;
594 return status;
595 }
596
597 // --------------------------------------------------------------------------
598 //
599 //! This writes one event to the file
600 //! @param e the pointer to the EVENT
601 //
602 virtual bool Write(EVENT *e)
603 {
604 //FIXME As discussed earlier, we do not swap the bytes yet.
605 fTable->makeThisCurrent();
606
607 //insert a new row
608 int status(0);
609 if (fits_insert_rows(fTable->fitsPointer(), fNumRows, 1, &status))
610 {
611 char text[30];//max length of cfitsio error strings (from doc)
612 fits_get_errstatus(status, text);
613
614 ostringstream str;
615 str << "Inserting row " << fNumRows << " into " << fFileName << ": " << text << " (fits_insert_rows, rc=" << status << ")";
616 fLog.Error(str);
617
618 return false;
619 }
620 fNumRows++;
621
622 const vector<char> data = fConv->ToFits(((char*)e)+2, sizeof(EVENT)+NPIX*e->Roi*2-2);
623
624 // column size pointer
625 size_t col = 1;
626 if (!WriteColumns(col, data.size(), data.data()))
627 return true;
628
629 //TODO output an error
630 return false;
631
632 /*
633 //write the data, chunk by chunk
634 //FIXME hard-coded size corresponds to current variables of the event, in bytes.
635 //FIXME no padding was taken into account. Because smallest member is 2 bytes, I don't think that this should be a problem.
636 const long sizeInBytesOfEventBeforePointers = 16;
637
638 long col = 1;
639 if (FitsWriteTblBytes(col, sizeInBytesOfEventBeforePointers, e))
640 {
641 //TODO output an error
642 return false;
643 }
644 if (FitsWriteTblBytes(col, NBOARDS*2, e->BoardTime))
645 {
646 //TODO output an error
647 return false;
648 }
649 if (FitsWriteTblBytes(col, NPIX*2, e->StartPix))
650 {
651 //TODO output an error
652 return false;
653 }
654 if (FitsWriteTblBytes(col, NTMARK*2, e->StartTM))
655 {
656 //TODO output an error
657 return false;
658 }
659 if (FitsWriteTblBytes(col, NPIX*fRoi*2, e->Adc_Data))
660 {
661 //TODO output an error
662 return false;
663 }
664 return true;*/
665 }
666
667 void WriteFooter(RUN_TAIL *rt)
668 {
669 //write final header keys
670 fTable->makeThisCurrent();
671
672 WriteKey("NBEVTOK", rt ? rt->nEventsOk : uint32_t(0),
673 "How many events were written");
674
675 WriteKey("NBEVTREJ", rt ? rt->nEventsRej : uint32_t(0),
676 "How many events were rejected by SW-trig");
677
678 WriteKey("NBEVTBAD", rt ? rt->nEventsBad : uint32_t(0),
679 "How many events were rejected by Error");
680
681 //FIXME shouldn't we convert start and stop time to MjD first ?
682 //FIXME shouldn't we also add an MjD reference ?
683
684 WriteKey("TSTART", rt ? rt->PCtime0 : uint32_t(0),
685 "Time when first event received");
686
687 WriteKey("TSTOP", rt ? rt->PCtimeX : uint32_t(0),
688 "Time when last event received");
689 }
690
691 // --------------------------------------------------------------------------
692 //
693 //! Closes the file, and before this it write the TAIL data
694 //! @param rt the pointer to the RUN_TAIL data structure
695 //
696 virtual bool Close(RUN_TAIL *rt = 0)
697 {
698 if (!fFile)
699 return false;
700
701 //WriteFooter(rt);
702
703 delete fFile;
704 fFile = NULL;
705
706 return true;
707 }
708
709};
710#else
711#define DataFileFits DataFileRaw
712#endif
713
714#include "DimWriteStatistics.h"
715
716class EventBuilderWrapper
717{
718public:
719 // FIXME
720 static EventBuilderWrapper *This;
721
722 MessageImp &fMsg;
723
724private:
725 boost::thread fThread;
726
727 enum CommandStates_t // g_runStat
728 {
729 kAbort = -2, // quit as soon as possible ('abort')
730 kExit = -1, // stop reading, quit when buffered events done ('exit')
731 kInitialize = 0, // 'initialize' (e.g. dim not yet started)
732 kHybernate = 1, // do nothing for long time ('hybernate') [wakeup within ~1sec]
733 kSleep = 2, // do nothing ('sleep') [wakeup within ~10msec]
734 kModeFlush = 10, // read data from camera, but skip them ('flush')
735 kModeTest = 20, // read data and process them, but do not write to disk ('test')
736 kModeFlag = 30, // read data, process and write all to disk ('flag')
737 kModeRun = 40, // read data, process and write selected to disk ('run')
738 };
739
740 enum
741 {
742 kCurrent = 0,
743 kTotal = 1,
744 kEventId = 2,
745 kTriggerId = 3,
746 };
747
748 enum FileFormat_t
749 {
750 kNone = 0,
751 kDebug,
752 kFits,
753 kRaw
754 };
755
756 FileFormat_t fFileFormat;
757
758
759 uint32_t fMaxRun;
760 uint32_t fLastOpened;
761 uint32_t fLastClosed;
762 uint32_t fNumEvts[4];
763
764 DimWriteStatistics fDimWriteStats;
765 DimDescribedService fDimRuns;
766 DimDescribedService fDimEvents;
767 DimDescribedService fDimEventData;
768 DimDescribedService fDimFwVersion;
769 DimDescribedService fDimRunNumber;
770 DimDescribedService fDimStatus;
771 DimDescribedService fDimDNA;
772 DimDescribedService fDimTemperature;
773 DimDescribedService fDimRefClock;
774 DimDescribedService fDimStatistics1;
775 DimDescribedService fDimStatistics2;
776
777 bool fDebugStream;
778 bool fDebugRead;
779 bool fDebugLog;
780
781 int Write(const Time &time, const std::string &txt, int qos)
782 {
783 return fMsg.Write(time, txt, qos);
784 }
785
786
787 uint32_t fRunNumber;
788
789 void InitRunNumber()
790 {
791 const int night = Time().NightAsInt();
792
793 fRunNumber = 1000;
794
795 while (--fRunNumber>0)
796 {
797 ostringstream name;
798 name << night << '.' << setfill('0') << setw(3) << fRunNumber;
799
800 if (access((name.str()+".bin").c_str(), F_OK) == 0)
801 break;
802 if (access((name.str()+".fits").c_str(), F_OK) == 0)
803 break;
804 }
805
806 fRunNumber++;
807
808 cout << "FOUND: " << night << '.' << setfill('0') << setw(3) << fRunNumber << endl;
809 }
810
811public:
812 EventBuilderWrapper(MessageImp &imp) : fMsg(imp),
813 fFileFormat(kNone), fMaxRun(0), fLastOpened(0), fLastClosed(0),
814 fDimWriteStats ("FAD_CONTROL", imp),
815 fDimRuns ("FAD_CONTROL/RUNS", "I:5;C", ""),
816 fDimEvents ("FAD_CONTROL/EVENTS", "I:4", ""),
817 fDimEventData ("FAD_CONTROL/EVENT_DATA", "S:1;I:1;S:1;I:2;S:1;S", ""),
818 fDimFwVersion ("FAD_CONTROL/FIRMWARE_VERSION", "F:42", ""),
819 fDimRunNumber ("FAD_CONTROL/RUN_NUMBER", "I:42", ""),
820 fDimStatus ("FAD_CONTROL/STATUS", "S:42", ""),
821 fDimDNA ("FAD_CONTROL/DNA", "X:40", ""),
822 fDimTemperature ("FAD_CONTROL/TEMPERATURE", "F:82", ""),
823 fDimRefClock ("FAD_CONTROL/REFERENCE_CLOCK", "I:42", ""),
824 fDimStatistics1 ("FAD_CONTROL/STATISTICS1", "I:3;I:2;X:4;I:3;I:1;I:2;C:40;I:40;I:40;X:40", ""),
825 fDimStatistics2 ("FAD_CONTROL/STATISTICS2", "I:1;I:280;X:40;I:40;I:4;I:4;I:2;I:2;I:3;C:40", ""),
826 fDebugStream(false), fDebugRead(false), fDebugLog(false)
827 {
828 if (This)
829 throw logic_error("EventBuilderWrapper cannot be instantiated twice.");
830
831 This = this;
832
833 memset(fNumEvts, 0, sizeof(fNumEvts));
834
835 fDimEvents.Update(fNumEvts);
836
837 for (size_t i=0; i<40; i++)
838 ConnectSlot(i, tcp::endpoint());
839
840 InitRunNumber();
841 }
842 virtual ~EventBuilderWrapper()
843 {
844 Abort();
845
846 // FIXME: Used timed_join and abort afterwards
847 // What's the maximum time the eb need to abort?
848 fThread.join();
849 //ffMsg.Info("EventBuilder stopped.");
850
851 for (vector<DataFileImp*>::iterator it=fFiles.begin(); it!=fFiles.end(); it++)
852 delete *it;
853 }
854
855 uint32_t IncreaseRunNumber()
856 {
857 return fRunNumber++;
858 }
859
860
861 bool IsThreadRunning()
862 {
863 return !fThread.timed_join(boost::posix_time::microseconds(0));
864 }
865
866 void SetMaxMemory(unsigned int mb) const
867 {
868 /*
869 if (mb*1000000<GetUsedMemory())
870 {
871 // ffMsg.Warn("...");
872 return;
873 }*/
874
875 g_maxMem = size_t(mb)*1000000;
876 }
877
878 void StartThread(const vector<tcp::endpoint> &addr)
879 {
880 if (IsThreadRunning())
881 {
882 fMsg.Warn("Start - EventBuilder still running");
883 return;
884 }
885
886 fLastMessage.clear();
887
888 for (size_t i=0; i<40; i++)
889 ConnectSlot(i, addr[i]);
890
891 g_runStat = kModeRun;
892
893 fMsg.Message("Starting EventBuilder thread");
894
895 fThread = boost::thread(StartEvtBuild);
896 }
897 void ConnectSlot(unsigned int i, const tcp::endpoint &addr)
898 {
899 if (i>39)
900 return;
901
902 if (addr==tcp::endpoint())
903 {
904 DisconnectSlot(i);
905 return;
906 }
907
908 g_port[i].sockAddr.sin_family = AF_INET;
909 g_port[i].sockAddr.sin_addr.s_addr = htonl(addr.address().to_v4().to_ulong());
910 g_port[i].sockAddr.sin_port = htons(addr.port());
911 // In this order
912 g_port[i].sockDef = 1;
913 }
914 void DisconnectSlot(unsigned int i)
915 {
916 if (i>39)
917 return;
918
919 g_port[i].sockDef = 0;
920 // In this order
921 g_port[i].sockAddr.sin_family = AF_INET;
922 g_port[i].sockAddr.sin_addr.s_addr = 0;
923 g_port[i].sockAddr.sin_port = 0;
924 }
925 void IgnoreSlot(unsigned int i)
926 {
927 if (i>39)
928 return;
929 if (g_port[i].sockAddr.sin_port==0)
930 return;
931
932 g_port[i].sockDef = -1;
933 }
934
935
936 void Abort()
937 {
938 fMsg.Message("Signal abort to EventBuilder thread...");
939 g_runStat = kAbort;
940 }
941
942 void ResetThread(bool soft)
943 {
944 /*
945 if (g_reset > 0)
946
947 * suspend reading
948 * reset = g_reset;
949 * g_reset=0
950
951 * reset% 10
952 == 0 leave event Buffers as they are
953 == 1 let all buffers drain (write (incomplete) events)
954 > 1 flush all buffers (do not write buffered events)
955
956 * (reset/10)%10
957 > 0 close all sockets and destroy them (also free the
958 allocated read-buffers)
959 recreate before resuming operation
960 [ this is more than just close/open that can be
961 triggered by e.g. close/open the base-socket ]
962
963 * (reset/100)%10
964 > 0 close all open run-files
965
966 * (reset/1000)
967 sleep so many seconds before resuming operation
968 (does not (yet) take into account time left when waiting
969 for buffers getting empty ...)
970
971 * resume_reading
972
973 */
974 fMsg.Message("Signal reset to EventBuilder thread...");
975 g_reset = soft ? 101 : 102;
976 }
977
978 void Exit()
979 {
980 fMsg.Message("Signal exit to EventBuilder thread...");
981 g_runStat = kExit;
982 }
983
984 /*
985 void Wait()
986 {
987 fThread.join();
988 ffMsg.Message("EventBuilder stopped.");
989 }*/
990
991 void Hybernate() const { g_runStat = kHybernate; }
992 void Sleep() const { g_runStat = kSleep; }
993 void FlushMode() const { g_runStat = kModeFlush; }
994 void TestMode() const { g_runStat = kModeTest; }
995 void FlagMode() const { g_runStat = kModeFlag; }
996 void RunMode() const { g_runStat = kModeRun; }
997
998 // FIXME: To be removed
999 void SetMode(int mode) const { g_runStat = mode; }
1000
1001 bool IsConnected(int i) const { return gi_NumConnect[i]==7; }
1002 bool IsConnecting(int i) const { return !IsConnected(i) && !IsDisconnected(i); }
1003 bool IsDisconnected(int i) const { return gi_NumConnect[i]<=0 && g_port[i].sockDef==0; }
1004 int GetNumConnected(int i) const { return gi_NumConnect[i]; }
1005
1006 void SetIgnore(int i, bool b) const { if (g_port[i].sockDef!=0) g_port[i].sockDef=b?-1:1; }
1007 bool IsIgnored(int i) const { return g_port[i].sockDef==-1; }
1008
1009 void SetOutputFormat(FileFormat_t f) { fFileFormat = f; }
1010
1011 void SetDebugLog(bool b) { fDebugLog = b; }
1012
1013 void SetDebugStream(bool b)
1014 {
1015 fDebugStream = b;
1016 if (b)
1017 return;
1018
1019 for (int i=0; i<40; i++)
1020 {
1021 if (!fDumpStream[i].is_open())
1022 continue;
1023
1024 fDumpStream[i].close();
1025
1026 ostringstream name;
1027 name << "socket_dump-" << setfill('0') << setw(2) << i << ".bin";
1028 fMsg.Message("Closed file '"+name.str()+"'");
1029 }
1030 }
1031
1032 void SetDebugRead(bool b)
1033 {
1034 fDebugRead = b;
1035 if (b || !fDumpRead.is_open())
1036 return;
1037
1038 fDumpRead.close();
1039 fMsg.Message("Closed file 'socket_events.txt'");
1040 }
1041
1042// size_t GetUsedMemory() const { return gi_usedMem; }
1043
1044 virtual int CloseOpenFiles() { CloseRunFile(0, 0); return 0; }
1045
1046
1047 /*
1048 struct OpenFileToDim
1049 {
1050 int code;
1051 char fileName[FILENAME_MAX];
1052 };
1053
1054 SignalRunOpened(runid, filename);
1055 // Send num open files
1056 // Send runid, (more info about the run?), filename via dim
1057
1058 SignalEvtWritten(runid);
1059 // Send num events written of newest file
1060
1061 SignalRunClose(runid);
1062 // Send new num open files
1063 // Send empty file-name if no file is open
1064
1065 */
1066
1067 // -------------- Mapped event builder callbacks ------------------
1068
1069 void UpdateRuns(const string &fname="")
1070 {
1071 uint32_t values[5] =
1072 {
1073 static_cast<uint32_t>(fFiles.size()),
1074 0xffffffff,
1075 0,
1076 fLastOpened,
1077 fLastClosed
1078 };
1079
1080 for (vector<DataFileImp*>::const_iterator it=fFiles.begin();
1081 it!=fFiles.end(); it++)
1082 {
1083 const DataFileImp *file = *it;
1084
1085 if (file->GetRunId()<values[1])
1086 values[1] = file->GetRunId();
1087
1088 if (file->GetRunId()>values[2])
1089 values[2] = file->GetRunId();
1090 }
1091
1092 fMaxRun = values[2];
1093
1094 vector<char> data(sizeof(values)+fname.size()+1);
1095 memcpy(data.data(), values, sizeof(values));
1096 strcpy(data.data()+sizeof(values), fname.c_str());
1097
1098 fDimRuns.Update(data);
1099 }
1100
1101 vector<DataFileImp*> fFiles;
1102
1103 FileHandle_t runOpen(uint32_t runid, RUN_HEAD *h, size_t)
1104 {
1105 // Check if file already exists...
1106 DataFileImp *file = 0;
1107 switch (fFileFormat)
1108 {
1109 case kNone: file = new DataFileNone(runid, fMsg); break;
1110 case kDebug: file = new DataFileDebug(runid, fMsg); break;
1111 case kFits: file = new DataFileFits(runid, fMsg); break;
1112 case kRaw: file = new DataFileRaw(runid, fMsg); break;
1113 }
1114
1115 try
1116 {
1117 if (!file->OpenFile(h))
1118 return 0;
1119 }
1120 catch (const exception &e)
1121 {
1122 return 0;
1123 }
1124
1125 fFiles.push_back(file);
1126
1127 ostringstream str;
1128 str << "Opened: " << file->GetFileName() << " (" << file->GetRunId() << ")";
1129 fMsg.Info(str);
1130
1131 fDimWriteStats.FileOpened(file->GetFileName());
1132
1133 fLastOpened = runid;
1134 UpdateRuns(file->GetFileName());
1135
1136 fNumEvts[kEventId] = 0;
1137 fNumEvts[kTriggerId] = 0;
1138
1139 fNumEvts[kCurrent] = 0;
1140 fDimEvents.Update(fNumEvts);
1141 // fDimCurrentEvent.Update(uint32_t(0));
1142
1143 return reinterpret_cast<FileHandle_t>(file);
1144 }
1145
1146 int runWrite(FileHandle_t handler, EVENT *e, size_t)
1147 {
1148 DataFileImp *file = reinterpret_cast<DataFileImp*>(handler);
1149
1150 if (!file->Write(e))
1151 return -1;
1152
1153 if (file->GetRunId()==fMaxRun)
1154 {
1155 fNumEvts[kCurrent]++;
1156 fNumEvts[kEventId] = e->EventNum;
1157 fNumEvts[kTriggerId] = e->TriggerType;
1158 }
1159
1160 fNumEvts[kTotal]++;
1161
1162 static Time oldt(boost::date_time::neg_infin);
1163 Time newt;
1164 if (newt>oldt+boost::posix_time::seconds(1))
1165 {
1166 fDimEvents.Update(fNumEvts);
1167 oldt = newt;
1168 }
1169
1170
1171 // ===> SignalEvtWritten(runid);
1172 // Send num events written of newest file
1173
1174 /* close run runId (all all runs if runId=0) */
1175 /* return: 0=close scheduled / >0 already closed / <0 does not exist */
1176 //CloseRunFile(file->GetRunId(), time(NULL)+2) ;
1177
1178 return 0;
1179 }
1180
1181 int runClose(FileHandle_t handler, RUN_TAIL *tail, size_t)
1182 {
1183 DataFileImp *file = reinterpret_cast<DataFileImp*>(handler);
1184
1185 const vector<DataFileImp*>::iterator it = find(fFiles.begin(), fFiles.end(), file);
1186 if (it==fFiles.end())
1187 {
1188 ostringstream str;
1189 str << "File handler (" << handler << ") requested to close by event builder doesn't exist.";
1190 fMsg.Fatal(str);
1191 return -1;
1192 }
1193
1194 fFiles.erase(it);
1195
1196 fLastClosed = file->GetRunId();
1197 UpdateRuns();
1198
1199 fDimEvents.Update(fNumEvts);
1200
1201 const bool rc = file->Close(tail);
1202 if (!rc)
1203 {
1204 // Error message
1205 }
1206
1207 ostringstream str;
1208 str << "Closed: " << file->GetFileName() << " (" << file->GetRunId() << ")";
1209 fMsg.Info(str);
1210
1211 delete file;
1212
1213 // ==> SignalRunClose(runid);
1214 // Send new num open files
1215 // Send empty file-name if no file is open
1216
1217 return rc ? 0 : -1;
1218 }
1219
1220 ofstream fDumpStream[40];
1221
1222 void debugStream(int isock, void *buf, int len)
1223 {
1224 if (!fDebugStream)
1225 return;
1226
1227 const int slot = isock/7;
1228 if (slot<0 || slot>39)
1229 return;
1230
1231 if (!fDumpStream[slot].is_open())
1232 {
1233 ostringstream name;
1234 name << "socket_dump-" << setfill('0') << setw(2) << slot << ".bin";
1235
1236 fDumpStream[slot].open(name.str().c_str(), ios::app);
1237 if (!fDumpStream[slot])
1238 {
1239 ostringstream str;
1240 str << "Open file '" << name << "': " << strerror(errno) << " (errno=" << errno << ")";
1241 fMsg.Error(str);
1242
1243 return;
1244 }
1245
1246 fMsg.Message("Opened file '"+name.str()+"' for writing.");
1247 }
1248
1249 fDumpStream[slot].write(reinterpret_cast<const char*>(buf), len);
1250 }
1251
1252 ofstream fDumpRead; // Stream to possibly dump docket events
1253
1254 void debugRead(int isock, int ibyte, uint32_t event, uint32_t ftmevt, uint32_t runno, int state, uint32_t tsec, uint32_t tusec)
1255 {
1256 // isock = socketID (0-279)
1257 // ibyte = #bytes gelesen
1258 // event = eventId (oder 0 wenn noch nicht bekannt)
1259 // state : 1=finished reading data
1260 // 0=reading data
1261 // -1=start reading data (header)
1262 // -2=start reading data,
1263 // eventId not known yet (too little data)
1264 // tsec, tusec = time when reading seconds, microseconds
1265 //
1266 if (!fDebugRead || ibyte==0)
1267 return;
1268
1269 if (!fDumpRead.is_open())
1270 {
1271 fDumpRead.open("socket_events.txt", ios::app);
1272 if (!fDumpRead)
1273 {
1274 ostringstream str;
1275 str << "Open file 'socket_events.txt': " << strerror(errno) << " (errno=" << errno << ")";
1276 fMsg.Error(str);
1277
1278 return;
1279 }
1280
1281 fMsg.Message("Opened file 'socket_events.txt' for writing.");
1282
1283 fDumpRead << "# START: " << Time().GetAsStr() << endl;
1284 fDumpRead << "# state time_sec time_usec socket slot runno event_id trigger_id bytes_received" << endl;
1285 }
1286
1287 fDumpRead
1288 << setw(2) << state << " "
1289 << setw(8) << tsec << " "
1290 << setw(9) << tusec << " "
1291 << setw(3) << isock << " "
1292 << setw(2) << isock/7 << " "
1293 << runno << " "
1294 << event << " "
1295 << ftmevt << " "
1296 << ibyte << endl;
1297 }
1298
1299 struct DimEventData
1300 {
1301 uint16_t Roi ; // #slices per pixel (same for all pixels and tmarks)
1302 uint32_t EventNum ; // EventNumber as from FTM
1303 uint16_t TriggerType ; // Trigger Type from FTM
1304
1305 uint32_t PCTime ; // when did event start to arrive at PC
1306 uint32_t BoardTime; //
1307
1308 int16_t StartPix; // First Channel per Pixel (Pixels sorted according Software ID) ; -1 if not filled
1309 int16_t StartTM; // First Channel for TimeMark (sorted Hardware ID) ; -1 if not filled
1310
1311 uint16_t Adc_Data[]; // final length defined by malloc ....
1312
1313 } __attribute__((__packed__));;
1314
1315 int eventCheck(PEVNT_HEADER *fadhd, EVENT *event)
1316 {
1317 /*
1318 fadhd[i] ist ein array mit den 40 fad-headers
1319 (falls ein board nicht gelesen wurde, ist start_package_flag =0 )
1320
1321 event ist die Struktur, die auch die write routine erhaelt;
1322 darin sind im header die 'soll-werte' fuer z.B. eventID
1323 als auch die ADC-Werte (falls Du die brauchst)
1324
1325 Wenn die routine einen negativen Wert liefert, wird das event
1326 geloescht (nicht an die write-routine weitergeleitet [mind. im Prinzip]
1327 */
1328
1329 static Time oldt(boost::date_time::neg_infin);
1330 Time newt;
1331
1332 if (newt<oldt+boost::posix_time::seconds(1))
1333 return 0;
1334
1335 oldt = newt;
1336
1337 static DimEventData *data = 0;
1338
1339 const size_t sz = sizeof(DimEventData)+event->Roi*2*1440;
1340
1341 if (data && data->Roi != event->Roi)
1342 {
1343 delete data;
1344 data = 0;
1345 }
1346
1347 if (!data)
1348 data = reinterpret_cast<DimEventData*>(new char[sz]);
1349
1350// cout << sizeof(DimEventData) << " " << event->Roi << " " << sz << " " << sizeof(*data) << endl;
1351
1352 data->Roi = event->Roi;
1353 data->EventNum = event->EventNum;
1354 data->TriggerType = event->TriggerType;
1355 data->PCTime = event->PCTime;
1356 data->BoardTime = event->BoardTime[0];
1357 data->StartPix = event->StartPix[0];
1358 data->StartTM = event->StartTM[0];
1359
1360 memcpy(data->Adc_Data, event->Adc_Data, event->Roi*2*1440);
1361
1362 fDimEventData.setData(data, sz);
1363 fDimEventData.updateService();
1364
1365 //delete data;
1366
1367 return 0;
1368 }
1369
1370 map<boost::thread::id, string> fLastMessage;
1371
1372 void factOut(int severity, int err, const char *message)
1373 {
1374 if (!fDebugLog && severity==99)
1375 return;
1376
1377 ostringstream str;
1378 //str << boost::this_thread::get_id() << " ";
1379 str << "EventBuilder(";
1380 if (err<0)
1381 str << "---";
1382 else
1383 str << err;
1384 str << "): " << message;
1385
1386 string &old = fLastMessage[boost::this_thread::get_id()];
1387
1388 if (str.str()==old)
1389 return;
1390 old = str.str();
1391
1392 fMsg.Update(str, severity);
1393 }
1394/*
1395 void factStat(int64_t *stat, int len)
1396 {
1397 if (len!=7)
1398 {
1399 fMsg.Warn("factStat received unknown number of values.");
1400 return;
1401 }
1402
1403 vector<int64_t> data(1, g_maxMem);
1404 data.insert(data.end(), stat, stat+len);
1405
1406 static vector<int64_t> last(8);
1407 if (data==last)
1408 return;
1409 last = data;
1410
1411 fDimStatistics.Update(data);
1412
1413 // len ist die Laenge des arrays.
1414 // array[4] enthaelt wieviele bytes im Buffer aktuell belegt sind; daran
1415 // kannst Du pruefen, ob die 100MB voll sind ....
1416
1417 ostringstream str;
1418 str
1419 << "Wait=" << stat[0] << " "
1420 << "Skip=" << stat[1] << " "
1421 << "Del=" << stat[2] << " "
1422 << "Tot=" << stat[3] << " "
1423 << "Mem=" << stat[4] << "/" << g_maxMem << " "
1424 << "Read=" << stat[5] << " "
1425 << "Conn=" << stat[6];
1426
1427 fMsg.Info(str);
1428 }
1429 */
1430
1431 void factStat(const EVT_STAT &stat)
1432 {
1433 fDimStatistics2.Update(stat);
1434 /*
1435 //some info about what happened since start of program (or last 'reset')
1436 uint32_t reset ; //#if increased, reset all counters
1437 uint32_t numRead[MAX_SOCK] ; //how often succesfull read from N sockets per loop
1438
1439 uint64_t gotByte[NBOARDS] ; //#Bytes read per Board
1440 uint32_t gotErr[NBOARDS] ; //#Communication Errors per Board
1441 uint32_t evtGet; //#new Start of Events read
1442 uint32_t evtTot; //#complete Events read
1443 uint32_t evtErr; //#Events with Errors
1444 uint32_t evtSkp; //#Events incomplete (timeout)
1445
1446 uint32_t procTot; //#Events processed
1447 uint32_t procErr; //#Events showed problem in processing
1448 uint32_t procTrg; //#Events accepted by SW trigger
1449 uint32_t procSkp; //#Events rejected by SW trigger
1450
1451 uint32_t feedTot; //#Events used for feedBack system
1452 uint32_t feedErr; //#Events rejected by feedBack
1453
1454 uint32_t wrtTot; //#Events written to disk
1455 uint32_t wrtErr; //#Events with write-error
1456
1457 uint32_t runOpen; //#Runs opened
1458 uint32_t runClose; //#Runs closed
1459 uint32_t runErr; //#Runs with open/close errors
1460
1461
1462 //info about current connection status
1463 uint8_t numConn[NBOARDS] ; //#Sockets succesfully open per board
1464 */
1465 }
1466
1467 void factStat(const GUI_STAT &stat)
1468 {
1469 fDimStatistics1.Update(stat);
1470 /*
1471 //info about status of the main threads
1472 int32_t readStat ; //read thread
1473 int32_t procStat ; //processing thread(s)
1474 int32_t writStat ; //write thread
1475
1476 //info about some rates
1477 int32_t deltaT ; //time in milli-seconds for rates
1478 int32_t readEvt ; //#events read
1479 int32_t procEvt ; //#events processed
1480 int32_t writEvt ; //#events written
1481 int32_t skipEvt ; //#events skipped
1482
1483 //some info about current state of event buffer (snapspot)
1484 int32_t evtBuf; //#Events currently waiting in Buffer
1485 uint64_t totMem; //#Bytes available in Buffer
1486 uint64_t usdMem; //#Bytes currently used
1487 uint64_t maxMem; //max #Bytes used during past Second
1488 */
1489 }
1490
1491
1492 boost::array<FAD::EventHeader, 40> fVecHeader;
1493
1494 template<typename T>
1495 boost::array<T, 42> Compare(const FAD::EventHeader *h, const T *t)
1496 {
1497 const int offset = reinterpret_cast<const char *>(t) - reinterpret_cast<const char *>(h);
1498
1499 const T *min = NULL;
1500 const T *val = NULL;
1501 const T *max = NULL;
1502
1503 boost::array<T, 42> vec;
1504
1505 bool rc = true;
1506 for (int i=0; i<40; i++)
1507 {
1508 const char *base = reinterpret_cast<const char*>(&fVecHeader[i]);
1509 const T *ref = reinterpret_cast<const T*>(base+offset);
1510
1511 vec[i] = *ref;
1512
1513 if (gi_NumConnect[i]!=7)
1514 {
1515 vec[i] = 0;
1516 continue;
1517 }
1518
1519 if (!val)
1520 {
1521 min = ref;
1522 val = ref;
1523 max = ref;
1524 }
1525
1526 if (*val<*min)
1527 min = val;
1528
1529 if (*val>*max)
1530 max = val;
1531
1532 if (*val!=*ref)
1533 rc = false;
1534 }
1535
1536 vec[40] = val ? *min : 0xffffffff;
1537 vec[41] = val ? *max : 0;
1538
1539 return vec;
1540 }
1541
1542 template<typename T>
1543 boost::array<T, 42> CompareBits(const FAD::EventHeader *h, const T *t)
1544 {
1545 const int offset = reinterpret_cast<const char *>(t) - reinterpret_cast<const char *>(h);
1546
1547 T val = 0;
1548 T rc = 0;
1549
1550 boost::array<T, 42> vec;
1551
1552 bool first = true;
1553
1554 for (int i=0; i<40; i++)
1555 {
1556 const char *base = reinterpret_cast<const char*>(&fVecHeader[i]);
1557 const T *ref = reinterpret_cast<const T*>(base+offset);
1558
1559 vec[i+2] = *ref;
1560
1561 if (gi_NumConnect[i]!=7)
1562 {
1563 vec[i+2] = 0;
1564 continue;
1565 }
1566
1567 if (first)
1568 {
1569 first = false;
1570 val = *ref;
1571 rc = 0;
1572 }
1573
1574 rc |= val^*ref;
1575 }
1576
1577 vec[0] = rc;
1578 vec[1] = val;
1579
1580 return vec;
1581 }
1582
1583 template<typename T, size_t N>
1584 void Update(DimDescribedService &svc, const boost::array<T, N> &data, int n=N)
1585 {
1586// svc.setQuality(vec[40]<=vec[41]);
1587 svc.setData(const_cast<T*>(data.data()), sizeof(T)*n);
1588 svc.updateService();
1589 }
1590
1591 template<typename T>
1592 void Print(const char *name, const pair<bool,boost::array<T, 43>> &data)
1593 {
1594 cout << name << "|" << data.first << "|" << data.second[1] << "|" << data.second[0] << "<x<" << data.second[1] << ":";
1595 for (int i=0; i<40;i++)
1596 cout << " " << data.second[i+3];
1597 cout << endl;
1598 }
1599
1600 vector<uint> fNumConnected;
1601
1602 void debugHead(int socket, const FAD::EventHeader &h)
1603 {
1604 const uint16_t id = h.Id();
1605 if (id>39)
1606 return;
1607
1608 if (fNumConnected.size()!=40)
1609 fNumConnected.resize(40);
1610
1611 const vector<uint> con(gi_NumConnect, gi_NumConnect+40);
1612
1613 const bool changed = con!=fNumConnected || !IsThreadRunning();
1614
1615 fNumConnected = con;
1616
1617 const FAD::EventHeader old = fVecHeader[id];
1618 fVecHeader[id] = h;
1619
1620 if (old.fVersion != h.fVersion || changed)
1621 {
1622 const boost::array<uint16_t,42> ver = Compare(&h, &h.fVersion);
1623
1624 boost::array<float,42> data;
1625 for (int i=0; i<42; i++)
1626 {
1627 ostringstream str;
1628 str << (ver[i]>>8) << '.' << (ver[i]&0xff);
1629 data[i] = atof(str.str().c_str());
1630 }
1631 Update(fDimFwVersion, data);
1632 }
1633
1634 if (old.fRunNumber != h.fRunNumber || changed)
1635 {
1636 const boost::array<uint32_t,42> run = Compare(&h, &h.fRunNumber);
1637 fDimRunNumber.Update(run);
1638 }
1639
1640 if (old.fDNA != h.fDNA || changed)
1641 {
1642 const boost::array<uint64_t,42> dna = Compare(&h, &h.fDNA);
1643 Update(fDimDNA, dna, 40);
1644 }
1645
1646 if (old.fStatus != h.fStatus || changed)
1647 {
1648 const boost::array<uint16_t,42> sts = CompareBits(&h, &h.fStatus);
1649 Update(fDimStatus, sts);
1650 }
1651
1652 // -----------
1653
1654 static Time oldt(boost::date_time::neg_infin);
1655 Time newt;
1656
1657 if (newt>oldt+boost::posix_time::seconds(1))
1658 {
1659 oldt = newt;
1660
1661 // --- RefClock
1662
1663 const boost::array<uint32_t,42> clk = Compare(&h, &h.fFreqRefClock);
1664 Update(fDimRefClock, clk);
1665
1666 // --- Temperatures
1667
1668 const boost::array<int16_t,42> tmp[4] =
1669 {
1670 Compare(&h, &h.fTempDrs[0]),
1671 Compare(&h, &h.fTempDrs[1]),
1672 Compare(&h, &h.fTempDrs[2]),
1673 Compare(&h, &h.fTempDrs[3])
1674 };
1675
1676 vector<int16_t> data;
1677 data.reserve(82);
1678 data.push_back(tmp[0][0]);
1679 data.insert(data.end(), tmp[0].data()+2, tmp[0].data()+42);
1680 data.push_back(tmp[0][1]);
1681 data.insert(data.end(), tmp[0].data()+2, tmp[0].data()+42);
1682
1683 for (int j=0; j<=3; j++)
1684 {
1685 const boost::array<int16_t,42> &ref = tmp[j];
1686
1687 // Gloabl min
1688 if (ref[40]<data[0])
1689 data[0] = ref[40];
1690
1691 // Global max
1692 if (ref[41]>data[40])
1693 data[40] = ref[41];
1694
1695 for (int i=0; i<40; i++)
1696 {
1697 // min per board
1698 if (ref[i]<data[i+1])
1699 data[i+1] = ref[i];
1700
1701 // max per board
1702 if (ref[i]>data[i+41])
1703 data[i+41] = ref[i];
1704 }
1705 }
1706
1707 vector<float> deg(82);
1708 for (int i=0; i<82; i++)
1709 deg[i] = data[i]/16.;
1710 fDimTemperature.Update(deg);
1711 }
1712
1713 /*
1714 uint16_t fTriggerType;
1715 uint32_t fTriggerId;
1716 uint32_t fEventCounter;
1717 uint16_t fAdcClockPhaseShift;
1718 uint16_t fNumTriggersToGenerate;
1719 uint16_t fTriggerGeneratorPrescaler;
1720 uint32_t fTimeStamp;
1721 int16_t fTempDrs[kNumTemp]; // In units of 1/16 deg(?)
1722 uint16_t fDac[kNumDac];
1723 */
1724 }
1725};
1726
1727EventBuilderWrapper *EventBuilderWrapper::This = 0;
1728
1729// ----------- Event builder callbacks implementation ---------------
1730extern "C"
1731{
1732 FileHandle_t runOpen(uint32_t irun, RUN_HEAD *runhd, size_t len)
1733 {
1734 return EventBuilderWrapper::This->runOpen(irun, runhd, len);
1735 }
1736
1737 int runWrite(FileHandle_t fileId, EVENT *event, size_t len)
1738 {
1739 return EventBuilderWrapper::This->runWrite(fileId, event, len);
1740 }
1741
1742 int runClose(FileHandle_t fileId, RUN_TAIL *runth, size_t len)
1743 {
1744 return EventBuilderWrapper::This->runClose(fileId, runth, len);
1745 }
1746
1747 void factOut(int severity, int err, const char *message)
1748 {
1749 EventBuilderWrapper::This->factOut(severity, err, message);
1750 }
1751
1752 void factStat(GUI_STAT stat)
1753 {
1754 EventBuilderWrapper::This->factStat(stat);
1755 }
1756
1757 void factStatNew(EVT_STAT stat)
1758 {
1759 EventBuilderWrapper::This->factStat(stat);
1760 }
1761
1762 void debugHead(int socket, int/*board*/, void *buf)
1763 {
1764 const uint16_t *ptr = reinterpret_cast<uint16_t*>(buf);
1765
1766 EventBuilderWrapper::This->debugHead(socket, FAD::EventHeader(ptr));
1767 }
1768
1769 void debugStream(int isock, void *buf, int len)
1770 {
1771 return EventBuilderWrapper::This->debugStream(isock, buf, len);
1772 }
1773
1774 void debugRead(int isock, int ibyte, int32_t event, int32_t ftmevt, int32_t runno, int state, uint32_t tsec, uint32_t tusec)
1775 {
1776 EventBuilderWrapper::This->debugRead(isock, ibyte, event, ftmevt, runno, state, tsec, tusec);
1777 }
1778
1779 int eventCheck(PEVNT_HEADER *fadhd, EVENT *event)
1780 {
1781 return EventBuilderWrapper::This->eventCheck(fadhd, event);
1782 }
1783}
1784
1785#endif
Note: See TracBrowser for help on using the repository browser.