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

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