26 #include "hadaq/TdcProcessor.h"
30 dabc::ModuleAsync(name, cmd),
63 double dlow =
Cfg(
"TrigDWindowLow", cmd).
AsDouble();
64 double dhigh =
Cfg(
"TrigDWindowHigh", cmd).
AsDouble();
65 if (dlow < dhigh-1) hadaq::TdcProcessor::SetTriggerDWindow(dlow, dhigh);
68 std::vector<uint64_t> caltr =
Cfg(
"CalibrTrigger", cmd).
AsUIntVect();
79 int portid = cmd.
GetInt(
"portid", 0);
85 hadaq::HldProcessor* hld = (hadaq::HldProcessor*) cmd.
GetPtr(
"HLDProc");
87 int hfill =
Cfg(
"HistFilling", cmd).
AsInt(1);
98 for (
unsigned n=0;n<hubid.size();n++)
100 unsigned hubmin =
Cfg(
"HUBmin", cmd).
AsUInt();
101 unsigned hubmax =
Cfg(
"HUBmax", cmd).
AsUInt();
102 for (
unsigned n=hubmin;n<hubmax;n++)
108 DOUT0(
"TRB 0x%04x creates TDCs %s", (
unsigned)
fTRB,
Cfg(
"TDC", cmd).AsStr().c_str());
110 for(
unsigned n=0;n<
fTDCs.size();n++) {
116 tdc->UseExplicitCalibration();
129 for (
unsigned n=0;n<
fTdcMin.size();++n)
134 if ((caltr.size() > 0) && (caltr[0] != 0xffff)) {
136 for (
unsigned n=0;n<caltr.size();n++)
177 base::ProcMgr::ClearInstancePointer(
fProcMgr);
201 if (fOwnProcMgr)
delete fProcMgr;
208 fRecheckTdcs = (fAutoTdcMode > 0);
209 if (fWarningCnt >= 0) fWarningCnt--;
213 bool change_progress,
214 int *res_progress,
double *res_quality,
215 std::string *res_state, std::vector<std::string> *res_msgs,
216 bool acknowledge_quality)
218 if (item.
null() || (trb==0))
return;
222 std::vector<int64_t>
tdcs;
223 std::vector<int64_t> tdc_progr;
224 std::vector<double> tdc_quality;
225 std::vector<std::string> status;
227 double p0(0), p1(1), worse_quality(1), worse_progress(1e10);
228 bool ready(
true), explicitmode(
true), is_any_progress(
false);
229 std::string worse_status =
"Ready";
231 for (
unsigned n=0;n<trb->NumberOfTDC();n++) {
232 hadaq::TdcProcessor* tdc = trb->GetTDCWithIndex(n);
237 if (acknowledge_quality)
238 tdc->AcknowledgeCalibrQuality(0.9);
240 double progr = tdc->GetCalibrProgress();
241 std::string sname = tdc->GetCalibrStatus();
242 double quality = tdc->GetCalibrQuality();
243 int mode = tdc->GetExplicitCalibrationMode();
245 if (!logitem.
null()) {
246 auto errlog = tdc->TakeCalibrLog();
247 for (
auto &item : errlog) {
250 if (res_msgs) res_msgs->push_back(item);
256 if (quality < worse_quality) {
257 worse_quality = quality;
258 worse_status = sname;
262 explicitmode =
false;
264 if (sname.find(
"Ready")==0) {
265 if (p1 > progr) p1 = progr;
267 if (p0 < progr) p0 = progr;
271 if ((progr > 0) && (progr < worse_progress)) {
272 worse_progress = progr;
273 is_any_progress =
true;
277 tdcs.push_back(tdc->GetID());
278 tdc_progr.push_back((
int) (progr*100.));
279 status.push_back(sname);
280 tdc_quality.push_back(quality);
283 tdc_progr.push_back(0);
284 status.push_back(
"Init");
285 tdc_quality.push_back(0);
290 worse_progress = ready ? p1 : -p0;
291 is_any_progress =
true;
293 if (worse_progress > 0) {
294 worse_status =
"Ready";
296 worse_status =
"Init";
300 if (!logitem.
null() && acknowledge_quality) {
301 std::string item =
"Acknowledge quality";
304 if (res_msgs) res_msgs->push_back(item);
307 if (!is_any_progress) worse_progress = 0;
308 if (worse_progress > 1.) worse_progress = 1.;
310 if (!change_progress) {
311 if (res_progress) worse_progress = *res_progress / 100.;
312 if (res_quality) worse_quality = *res_quality;
313 if (res_state) worse_status = *res_state;
316 item.
SetField(
"value", worse_status);
317 item.
SetField(
"progress", (
int)(fabs(worse_progress)*100));
318 item.
SetField(
"quality", worse_quality);
320 item.
SetField(
"tdc_progr", tdc_progr);
321 item.
SetField(
"tdc_status", status);
322 item.
SetField(
"tdc_quality", tdc_quality);
326 if (change_progress) {
327 if (res_progress) *res_progress = (int) (fabs(worse_progress)*100);
328 if (res_quality) *res_quality = worse_quality;
329 if (res_state) *res_state = worse_status;
336 tdc->SetCalibrTriggerMask(fCalibrMask);
338 for (
unsigned n=0;n<fDisabledCh.size();n++)
339 tdc->DisableCalibrationFor(fDisabledCh[n]);
341 tdc->SetAutoCalibration(fAutoCalibr);
343 tdc->SetLinearNumPoints(fLinearNumPoints);
345 if (!fCalibrFile.empty()) {
347 tdc->SetWriteCalibration(fCalibrFile.c_str(),
true);
348 tdc->LoadCalibration(fCalibrFile.c_str());
351 if (fAutoTdcMode==1) tdc->SetUseLinear();
352 if (fAutoToTRange==1) tdc->SetToTRange(20., 30., 60.);
354 if (fTotStatLimit > 0) tdc->SetTotStatLimit(fTotStatLimit);
355 if (fTotRMSLimit > 0) tdc->SetTotRMSLimit(fTotRMSLimit);
357 tdc->UseExplicitCalibration();
359 fTDCs.emplace_back(tdc->GetID());
360 DOUT0(
"TRB 0x%04x created TDC 0x%04x", (
unsigned) fTRB, tdc->GetID());
365 if (dataid == 0x5555)
return false;
366 for (
unsigned n=0;n<fTdcMin.size();++n)
367 if ((dataid>=fTdcMin[n]) && (dataid<fTdcMax[n]))
return true;
378 if (CanSend() && CanRecv()) {
380 if (!fReplace && !CanTakeBuffer())
return false;
384 if (fDebug) Par(
"DataRate").SetValue(buf.
GetTotalSize()/1024./1024.);
386 if (fDummy &&
false) {
393 if (fAutoCalibr>0) fProgress = (int) (100*fDummyCounter/fAutoCalibr);
else
394 if (fDoingTdcCalibr) fProgress = (int) (100*fDummyCounter/1000);
395 item.
SetField(
"progress", fProgress);
398 if (fProgress > 0) fQuality = 0.7 + fProgress*1e-3;
400 if (fProgress >= 100) {
402 if (fAutoCalibr>0) fDummyCounter = 0;
408 std::vector<int64_t> progr;
409 progr.assign(fTDCs.size(), fProgress);
412 std::vector<std::string> status;
414 item.
SetField(
"tdc_status", status);
416 std::vector<double> tdc_quality;
417 tdc_quality.assign(fTDCs.size(), fQuality);
418 item.
SetField(
"tdc_quality", tdc_quality);
429 }
else if (fTrbProc) {
441 bool auto_create = (fAutoTdcMode > 0) && (fTDCs.size() == 0) && (fTdcMin.size() > 0) && !fDummy;
446 fTrbProc->SetCalibrTriggerMask(fCalibrMask);
450 std::vector<unsigned> ids;
461 fTrbProc->CollectMissingTDCs((hadaqs::RawSubevent *)iter0.
subevnt(), ids);
468 for (
unsigned indx = 0; indx < ids.size(); ++indx) {
469 if (MatchTdcId(ids[indx])) {
470 hadaq::TdcProcessor *tdc =
new hadaq::TdcProcessor(fTrbProc, ids[indx], fNumCh, fEdges);
472 ConfigureNewTDC(tdc);
477 fTrbProc->CreatePerTDCHistos();
480 fWorkerHierarchy.GetHChild(
"Status").SetField(
"tdc", fTDCs);
482 if ((numtdc==0) && (fWarningCnt <= 0)) {
483 DOUT0(
"No any TDC found in %s - please disable Mode in XML file", GetName());
490 cmd.
SetStr(
"mode",
"start");
494 fRecheckTdcs =
false;
501 unsigned char* tgt =
nullptr;
502 unsigned tgtlen(0), reslen(0);
505 resbuf = TakeBuffer();
510 std::vector<unsigned> newids;
535 sublen = fTrbProc->EmulateTransform((hadaqs::RawSubevent*)iter.
subevnt(), fDummyCounter);
537 hadaqs::RawSubevent *sub = (hadaqs::RawSubevent *) iter.
subevnt();
539 if ((sub->Alignment()!=4) || !sub->IsSwapped()) {
540 EOUT(
"UNEXPECTED TRB DATA FORMAT align %u swap %s - ABORT!!!\n", sub->Alignment(),
DBOOL(sub->IsSwapped()));
544 sublen = fTrbProc->TransformSubEvent(sub, tgt, tgtlen - reslen, (fAutoTdcMode==0), fRecheckTdcs ? &newids :
nullptr);
554 fRecheckTdcs =
false;
556 for (
unsigned indx = 0; indx < newids.size(); ++indx) {
557 if (MatchTdcId(newids[indx])) {
558 hadaq::TdcProcessor *tdc =
new hadaq::TdcProcessor(fTrbProc, newids[indx], fNumCh, fEdges);
560 ConfigureNewTDC(tdc);
564 fWorkerHierarchy.GetHChild(
"Status").SetField(
"tdc", fTDCs);
565 fTrbProc->ClearFastTDCVector();
581 if (fLastCalibr.Expired(1.)) {
582 fLastCalibr.GetNow();
588 SetTRBStatus(item, logitem, fTrbProc, fEnableProgressUpdate, &fProgress, &fQuality, &fState, &fLogMessages);
611 if (fOwnProcMgr && fProcMgr && fProcMgr->ExecuteHCommand(cmd))
return dabc::cmd_true;
613 if (cmd.
IsName(
"ResetTransportStat")) {
615 fTrbProc->ClearDAQHistos();
617 if (SubmitCommandToTransport(InputName(), cmd))
622 if (cmd.
IsName(
"HCMD_AcknowledgeQuality")) {
627 fEnableProgressUpdate =
true;
629 SetTRBStatus(item, logitem, fTrbProc, fEnableProgressUpdate, &fProgress, &fQuality, &fState, &fLogMessages,
true);
631 RecordTRBStatus(
true, logitem);
636 if (cmd.
IsName(
"GetCalibrState")) {
639 cmd.
SetInt(
"progress", fProgress);
641 cmd.
SetStr(
"state", fState);
645 if (cmd.
IsName(
"GetHadaqTransportInfo")) {
647 cmd.
SetStr(
"CalibrModule", ItemName());
652 if (cmd.
IsName(
"TdcCalibrations")) {
655 fDoingTdcCalibr = (cmd.
GetStr(
"mode") ==
"start");
657 if (fDoingTdcCalibr) fLogMessages.clear();
659 fEnableProgressUpdate =
true;
661 std::string subdir = cmd.
GetStr(
"rundir");
663 DOUT0(
"%s ENTER CALIBRATION Mode %s subdir %s\n", GetName(), cmd.
GetStr(
"mode").c_str(), subdir.c_str());
664 if (!subdir.empty()) subdir.append(fCalibrFile);
666 unsigned numtdc = fTrbProc->NumberOfTDC();
668 if (cmd.
GetStr(
"mode") ==
"start")
669 DOUT0(
"%s START CALIBRATIONS autotdc %d NumTDC %u", GetName(), fAutoTdcMode, numtdc);
671 DOUT0(
"%s STORE CALIBRATIONS IN %s %s NumTDC %u", GetName(), fCalibrFile.c_str(), subdir.c_str(), numtdc);
673 for (
unsigned indx = 0; indx < numtdc; ++indx) {
674 hadaq::TdcProcessor *tdc = fTrbProc->GetTDCWithIndex(indx);
676 if (cmd.
GetStr(
"mode") ==
"start") {
677 tdc->BeginCalibration(fAutoTdcMode==1 ? fCountLinear : fCountNormal);
680 std::string s1 =
dabc::format(
"BEFORE mode %d Progress %5.4f Quality %5.4f state %s", tdc->GetExplicitCalibrationMode(), tdc->GetCalibrProgress(), tdc->GetCalibrQuality(), tdc->GetCalibrStatus().c_str());
682 tdc->CompleteCalibration(fDummy, fCalibrFile, subdir);
684 std::string s2 =
dabc::format(
"AFTER mode %d Progress %5.4f Quality %5.4f state %s", tdc->GetExplicitCalibrationMode(), tdc->GetCalibrProgress(), tdc->GetCalibrQuality(), tdc->GetCalibrStatus().c_str());
686 DOUT0(
"TDC %04x edges %u %s %s", tdc->GetID(), tdc->GetEdgeMask(), s1.c_str(), s2.c_str());
690 fLastCalibr.GetNow();
695 std::string msg = fDoingTdcCalibr ?
"Performing calibration: " :
"Complete calibration: ";
699 if (fDoingTdcCalibr) {
700 msg +=
" quality = ";
701 msg += std::to_string(fQuality);
703 fLogMessages.push_back(msg);
705 SetTRBStatus(item, logitem, fTrbProc, fEnableProgressUpdate, &fProgress, &fQuality, &fState, &fLogMessages);
707 RecordTRBStatus(
true, logitem);
711 DOUT0(
"RESULT!!! %s PROGR %d QUALITY %5.3f STATE %s", GetName(), fProgress, fQuality, fState.c_str());
716 if (cmd.
IsName(
"CalibrRefresh")) {
726 std::string fname = GetName();
727 fname.append(
".txt");
729 FILE *f = fopen(fname.c_str(), do_write ?
"w" :
"r");
731 EOUT(
"FAIL to open file %s for %s", fname.c_str(), do_write ?
"writing" :
"reading");
739 fprintf(f,
"%lu\n", (
long unsigned) tm.
AsJSDate());
740 fprintf(f,
"%s\n", fState.c_str());
741 fprintf(f,
"%f\n", fQuality);
742 fprintf(f,
"%d\n", fProgress);
743 if (fLogMessages.size() > 1000)
744 fLogMessages.erase(fLogMessages.begin(), fLogMessages.end() - 1000);
745 for (
auto &item: fLogMessages)
746 fprintf(f,
"%s\n", item.c_str());
750 long unsigned tm_js = 0;
751 fgets(sbuf,
sizeof(sbuf), f);
752 if (sscanf(sbuf,
"%lu", &tm_js) != 1)
EOUT(
"Fail to get time from %s file", fname.c_str());
755 fgets(sbuf,
sizeof(sbuf), f);
758 fgets(sbuf,
sizeof(sbuf), f);
759 if (sscanf(sbuf,
"%lf", &fQuality) != 1)
EOUT(
"Fail to get quality from %s file", fname.c_str());
761 fgets(sbuf,
sizeof(sbuf), f);
762 if (sscanf(sbuf,
"%d", &fProgress) != 1)
EOUT(
"Fail to get progress from %s file", fname.c_str());
765 while (fgets(sbuf,
sizeof(sbuf), f) && (cnt-- > 0)) {
766 fLogMessages.push_back(sbuf);
783 logitem.
SetField(
"value", std::string(
"Starting calibration module ") + GetName() +
" at " +
dabc::DateTime().GetNow().AsJSString());
799 cmd.
SetStr(
"mode",
"stop");
Reference on memory from memory pool.
unsigned SegmentSize(unsigned n=0) const
Returns size on the segment, no any boundary checks.
void SetTotalSize(BufferSize_t len)
Set total length of the buffer to specified value Size cannot be bigger than original size of the buf...
unsigned GetTypeId() const
BufferSize_t GetTotalSize() const
Return total size of all buffer segments.
void SetTypeId(unsigned tid)
void * SegmentPtr(unsigned n=0) const
Returns pointer on the segment, no any boundary checks.
Represents command with its arguments.
bool SetStr(const std::string &name, const char *value)
bool SetInt(const std::string &name, int v)
std::string GetStr(const std::string &name, const std::string &dflt="") const
bool SetUInt(const std::string &name, unsigned v)
bool SetDouble(const std::string &name, double v)
int GetInt(const std::string &name, int dflt=0) const
void * GetPtr(const std::string &name, void *deflt=0) const
Get pointer argument from the command.
Class for holding GMT time with precision of nanoseconds.
std::string OnlyTimeAsString(const char *separ=nullptr, bool localtime=false) const
Fills only time as string.
std::string AsJSString(int ndecimal=3) const
convert string into sec.frac format, can be interpret directly in JavaScript ISO 8601 standard is use...
void SetJSDate(uint64_t jsdate)
Set value in form of JS date - milliseconds since 1.1.1970.
uint64_t AsJSDate() const
Return date and time in JS format - number of millisecond since 1.1.1970.
Represents objects hierarchy of remote (or local) DABC process.
void MarkChangedItems(uint64_t tm=0)
If any field was modified, item will be marked with new version.
Hierarchy CreateHChild(const std::string &name, bool allowslahes=false, bool sortorder=false)
Create child item in hierarchy with specified name If allowslahes enabled, instead of subfolders item...
Hierarchy GetHChild(const std::string &name, bool allowslahes=false, bool force=false, bool sortorder=false)
Return child, if necessary creates with full subfolder If force specified, missing childs and folders...
void Create(const std::string &name, bool withmutex=false)
Create top-level object with specified name.
void EnableHistory(unsigned length=100, bool withchilds=false)
Activate history production for selected element and its childs.
virtual Parameter CreatePar(const std::string &name, const std::string &kind="")
unsigned CreatePoolHandle(const std::string &poolname, unsigned queue=10)
Creates handle for memory pool, which preserves reference on memory pool and provides fast access to ...
virtual int ExecuteCommand(Command cmd)
Main method where commands are executed.
unsigned CreateTimer(const std::string &name, double period_sec=-1., bool synchron=false)
const char * GetName() const
Returns name of the object, thread safe
Parameter & SetUnits(const std::string &unit)
Set units field of parameter.
Parameter & SetRatemeter(bool synchron=false, double interval=1.0)
Converts parameter in ratemeter - all values will be summed up and divided on specified interval.
std::vector< uint64_t > AsUIntVect() const
uint64_t AsUInt(uint64_t dflt=0) const
std::vector< int64_t > AsIntVect() const
bool AsBool(bool dflt=false) const
std::string AsStr(const std::string &dflt="") const
int64_t AsInt(int64_t dflt=0) const
double AsDouble(double dflt=0.) const
RecordField GetField(const std::string &name) const
bool SetField(const std::string &name, const RecordField &v)
bool IsName(const char *name) const
Returns true if object name is the same as specified one.
unsigned NumChilds() const
Return number of childs in referenced object.
bool null() const
Returns true if reference contains nullptr.
Hierarchy fWorkerHierarchy
place for publishing of worker parameters
RecordField Cfg(const std::string &name, Command cmd=nullptr) const
Returns configuration field of specified name Configuration value of specified name searched in follo...
virtual bool Publish(const Hierarchy &h, const std::string &path)
Read iterator for HADAQ events/subevents.
hadaq::RawSubevent * subevnt() const
unsigned rawdata_maxsize() const
Try to define maximal length for the raw data.
unsigned remained_size() const
Returns size used by current event plus rest.
bool NextSubEvent()
Used for sub-events iteration inside current block.
bool NextSubeventsBlock()
Depending from buffer type calls NextHadTu() or NextEvent()
void SetTop(dabc::Hierarchy &top, bool withcmds=false)
std::vector< uint64_t > fTDCs
remember TDCs in the beginning
bool fEnableProgressUpdate
set true to enable trb progress update
int fCountLinear
number of count for liner calibrations when starting explicitly
unsigned fCalibrMask
mask to used for triggers
int fTotStatLimit
limit for ToT statistic
int fLinearNumPoints
number of points used in linear calibration
bool fOwnProcMgr
if created in the module
int fFineMin
configure min value
static void SetTRBStatus(dabc::Hierarchy &item, dabc::Hierarchy &logitem, hadaq::TrbProcessor *trb, bool change_progress=true, int *res_progress=nullptr, double *res_quality=nullptr, std::string *res_state=nullptr, std::vector< std::string > *res_msgs=nullptr, bool acknowledge_quality=false)
int ExecuteCommand(dabc::Command cmd) override
Main method where commands are executed.
std::string fState
current state
bool RecordTRBStatus(bool do_store, dabc::Hierarchy &logitem)
int fNumCh
configured number of channel
int fAutoTdcMode
automatic mode of TDC creation 0 - off, 1 - with linear calibr, 2 - with normal calibr
bool MatchTdcId(uint32_t tdcid)
dabc::TimeStamp fLastCalibr
use not to check for calibration very often
DabcProcMgr * fProcMgr
stream process manager
unsigned fTRB
remember TRB id, used in module name
int fAutoToTRange
ToT range, 0 - normal, 1 - DiRICH.
virtual ~TdcCalibrationModule()
void ProcessTimerEvent(unsigned) override
Method called by framework when timer event is produced.
void AfterModuleStop() override
int fEdges
configured edges
std::vector< uint64_t > fTdcMax
configured max TDC id
std::string fCalibrFile
names to load/store calibrations
void BeforeModuleStart() override
double fTotRMSLimit
limit for ToT RMS calibration
hadaq::TrbProcessor * fTrbProc
TRB processor.
int fAutoCalibr
amount of statistic for the auto calibration in channels
std::vector< int64_t > fDisabledCh
disabled for calibrations channels
int fFineMax
configure max value
int fCountNormal
number of counts for normal calibrations when starting explicitly
bool fReplace
replace hit messages (true) or add calibration messages (false)
void ConfigureNewTDC(hadaq::TdcProcessor *tdc)
bool fDummy
module creates all TDCs but do not perform any transformation
int fDebug
when specified, provides more debug output and special mode
std::vector< uint64_t > fTdcMin
configured min TDC id
TdcCalibrationModule(const std::string &name, dabc::Command cmd=nullptr)
std::vector< unsigned > tdcs
std::string format(const char *fmt,...)
void GetNow()
Method to acquire current time stamp.
uint32_t GetPaddedSize() const