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

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