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

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