Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-02-14 12:51:47

0001 /*
0002  *  See header file for a description of this class.
0003  *
0004  *  $Date: 2011/01/27 15:36:19 $
0005  *  $Revision: 1.12 $
0006  *  \author Paolo Ronchese INFN Padova
0007  *
0008  */
0009 
0010 //-----------------------
0011 // This Class' Header --
0012 //-----------------------
0013 #include "CondTools/DT/interface/DTHVStatusHandler.h"
0014 
0015 //-------------------------------
0016 // Collaborating Class Headers --
0017 //-------------------------------
0018 #include "CondTools/DT/interface/DTHVAbstractCheck.h"
0019 #include "CondFormats/DTObjects/interface/DTHVStatus.h"
0020 
0021 #include "CondCore/CondDB/interface/ConnectionPool.h"
0022 
0023 #include "DataFormats/Provenance/interface/Timestamp.h"
0024 #include "DataFormats/MuonDetId/interface/DTWireId.h"
0025 #include "RelationalAccess/ISchema.h"
0026 #include "RelationalAccess/ITable.h"
0027 #include "RelationalAccess/ICursor.h"
0028 #include "RelationalAccess/IQuery.h"
0029 #include "RelationalAccess/TableDescription.h"
0030 #include "RelationalAccess/ITableDataEditor.h"
0031 #include "CoralBase/AttributeList.h"
0032 #include "CoralBase/AttributeSpecification.h"
0033 #include "CoralBase/Attribute.h"
0034 #include "CoralBase/TimeStamp.h"
0035 
0036 //---------------
0037 // C++ Headers --
0038 //---------------
0039 #include <map>
0040 #include <sys/time.h>
0041 
0042 //-------------------
0043 // Initializations --
0044 //-------------------
0045 
0046 //----------------
0047 // Constructors --
0048 //----------------
0049 DTHVStatusHandler::DTHVStatusHandler(const edm::ParameterSet& ps)
0050     : dataTag(ps.getParameter<std::string>("tag")),
0051       onlineConnect(ps.getParameter<std::string>("onlineDB")),
0052       utilConnect(ps.getParameter<std::string>("utilDB")),
0053       onlineAuthentication(ps.getParameter<std::string>("onlineAuthentication")),
0054       bufferConnect(ps.getParameter<std::string>("bufferDB")),
0055       ySince(ps.getParameter<int>("sinceYear")),
0056       mSince(ps.getParameter<int>("sinceMonth")),
0057       dSince(ps.getParameter<int>("sinceDay")),
0058       hSince(ps.getParameter<int>("sinceHour")),
0059       pSince(ps.getParameter<int>("sinceMinute")),
0060       sSince(ps.getParameter<int>("sinceSecond")),
0061       yUntil(ps.getParameter<int>("untilYear")),
0062       mUntil(ps.getParameter<int>("untilMonth")),
0063       dUntil(ps.getParameter<int>("untilDay")),
0064       hUntil(ps.getParameter<int>("untilHour")),
0065       pUntil(ps.getParameter<int>("untilMinute")),
0066       sUntil(ps.getParameter<int>("untilSecond")),
0067       dumpAtStart(ps.getParameter<bool>("dumpAtStart")),
0068       dumpAtEnd(ps.getParameter<bool>("dumpAtEnd")),
0069       bwdTime(ps.getParameter<long long int>("bwdTime")),
0070       fwdTime(ps.getParameter<long long int>("fwdTime")),
0071       minTime(ps.getParameter<long long int>("minTime")),
0072       omds_session(),
0073       util_session(),
0074       buff_session(),
0075       mapVersion(ps.getParameter<std::string>("mapVersion")),
0076       splitVersion(ps.getParameter<std::string>("splitVersion")) {
0077   std::cout << " PopCon application for DT HV data export " << onlineAuthentication << std::endl;
0078   hvChecker = DTHVAbstractCheck::getInstance();
0079   maxPayload = 1000;
0080 }
0081 
0082 //--------------
0083 // Destructor --
0084 //--------------
0085 DTHVStatusHandler::~DTHVStatusHandler() {}
0086 
0087 //--------------
0088 // Operations --
0089 //--------------
0090 void DTHVStatusHandler::getNewObjects() {
0091   std::cout << "get new objects..." << std::endl;
0092 
0093   // online DB connection - data
0094   std::cout << "configure omds DbConnection" << std::endl;
0095   cond::persistency::ConnectionPool connection;
0096   //  conn->configure( cond::CmsDefaults );
0097   connection.setAuthenticationPath(onlineAuthentication);
0098   connection.configure();
0099   std::cout << "create omds DbSession" << std::endl;
0100   omds_session = connection.createSession(onlineConnect);
0101   std::cout << "start omds transaction" << std::endl;
0102   omds_session.transaction().start();
0103   std::cout << "" << std::endl;
0104 
0105   // online DB connection - util
0106   std::cout << "create util DbSession" << std::endl;
0107   util_session = connection.createSession(onlineConnect);
0108   std::cout << "startutil  transaction" << std::endl;
0109   util_session.transaction().start();
0110   std::cout << "" << std::endl;
0111 
0112   // buffer DB connection
0113   std::cout << "create buffer DbSession" << std::endl;
0114   buff_session = connection.createSession(bufferConnect);
0115   std::cout << "start buffer transaction" << std::endl;
0116   buff_session.transaction().start();
0117 
0118   // offline info
0119 
0120   //to access the information on the tag inside the offline database:
0121   cond::TagInfo_t const& ti = tagInfo();
0122   cond::Time_t last = ti.lastInterval.since;
0123   std::cout << "latest DCS data (HV) already copied until: " << last << std::endl;
0124 
0125   coral::TimeStamp coralSince(ySince, mSince, dSince, hSince, pSince, sSince, 0);
0126   procSince = condTime(coralSince);
0127   coral::TimeStamp coralUntil(yUntil, mUntil, dUntil, hUntil, pUntil, sUntil, 0);
0128   procUntil = condTime(coralUntil);
0129   lastFound = 0;
0130   nextFound = 0;
0131   timeLimit = 0;
0132   lastStamp = 0;
0133 
0134   if (last == 0) {
0135     DTHVStatus* dummyStatus = new DTHVStatus(dataTag);
0136     cond::Time_t snc = 1;
0137     m_to_transfer.push_back(std::make_pair(dummyStatus, snc));
0138     last = procSince + 1;
0139     std::cout << "no old data... " << last << std::endl;
0140   } else {
0141     Ref payload = lastPayload();
0142     DTHVStatus::const_iterator paylIter = payload->begin();
0143     DTHVStatus::const_iterator paylIend = payload->end();
0144     while (paylIter != paylIend) {
0145       const std::pair<DTHVStatusId, DTHVStatusData>& entry = *paylIter++;
0146       const DTHVStatusId& chan = entry.first;
0147       const DTHVStatusData& data = entry.second;
0148       DTWireId id(chan.wheelId, chan.stationId, chan.sectorId, chan.slId, chan.layerId, chan.partId + 10);
0149       hvChecker->setStatus(id.rawId(), data.flagA, data.flagC, data.flagS, snapshotValues, aliasMap, layerMap);
0150     }
0151   }
0152   coral::TimeStamp coralLast = coralTime(last);
0153   coral::TimeStamp coralProc = coral::TimeStamp::now();
0154   cond::Time_t condProc = condTime(coralProc);
0155 
0156   if (procSince > condProc) {
0157     std::cout << "Required time interval in the future: " << std::endl
0158               << " copy since " << ySince << " " << mSince << " " << dSince << " ( " << procSince << " )" << std::endl
0159               << " current time " << coralProc.year() << " " << coralProc.month() << " " << coralProc.day()
0160               << std::endl;
0161   }
0162   if (procUntil > condProc)
0163     procUntil = condProc;
0164   if (last > procSince) {
0165     if (last < procUntil) {
0166       procSince = last;
0167       checkNewData();
0168     } else {
0169       std::cout << "Required time interval already copied: " << std::endl
0170                 << " copy until " << yUntil << " " << mUntil << " " << dUntil << " ( " << procUntil << " )" << std::endl
0171                 << " data until " << coralLast.year() << " " << coralLast.month() << " " << coralLast.day()
0172                 << std::endl;
0173     }
0174   } else {
0175     std::cout << "Required time interval not contiguous with copied data: " << std::endl
0176               << " data until " << coralLast.year() << " " << coralLast.month() << " " << coralLast.day() << std::endl
0177               << " copy since " << ySince << " " << mSince << " " << dSince << " ( " << procSince << " )" << std::endl;
0178   }
0179 
0180   buff_session.transaction().commit();
0181   buff_session.close();
0182   omds_session.close();
0183   util_session.close();
0184 
0185   return;
0186 }
0187 
0188 void DTHVStatusHandler::checkNewData() {
0189   //to access the information on last successful log entry for this tag:
0190   //  cond::LogDBEntry const & lde = logDBEntry();
0191 
0192   //to access the lastest payload (Ref is a smart pointer)
0193   //  Ref payload = lastPayload();
0194 
0195   std::cout << "check for new data since " << procSince << " " << coralTime(procSince).total_nanoseconds() << " "
0196             << coralTime(procSince).year() << " " << coralTime(procSince).month() << " " << coralTime(procSince).day()
0197             << " " << coralTime(procSince).hour() << " " << coralTime(procSince).minute() << " "
0198             << coralTime(procSince).second() << std::endl;
0199   std::cout << "                   until " << procUntil << " " << coralTime(procUntil).total_nanoseconds() << " "
0200             << coralTime(procUntil).year() << " " << coralTime(procUntil).month() << " " << coralTime(procUntil).day()
0201             << " " << coralTime(procUntil).hour() << " " << coralTime(procUntil).minute() << " "
0202             << coralTime(procUntil).second() << std::endl;
0203 
0204   std::set<std::string> omds_lt(omds_session.nominalSchema().listTables());
0205   std::set<std::string>::const_iterator omds_iter = omds_lt.begin();
0206   std::set<std::string>::const_iterator omds_iend = omds_lt.end();
0207   while (omds_iter != omds_iend) {
0208     const std::string& istr = *omds_iter++;
0209     std::cout << "TABLE: " << istr << std::endl;
0210   }
0211 
0212   std::set<std::string> util_lt(util_session.nominalSchema().listTables());
0213   std::set<std::string>::const_iterator util_iter = util_lt.begin();
0214   std::set<std::string>::const_iterator util_iend = util_lt.end();
0215   while (util_iter != util_iend) {
0216     const std::string& istr = *util_iter++;
0217     std::cout << "TABLE: " << istr << std::endl;
0218   }
0219 
0220   getLayerSplit();
0221   getChannelMap();
0222   getChannelSplit();
0223 
0224   std::cout << "open buffer db..." << std::endl;
0225 
0226   if (!(buff_session.nominalSchema().existsTable("HVSNAPSHOT")))
0227     createSnapshot();
0228   updateHVStatus();
0229 
0230   return;
0231 }
0232 
0233 std::string DTHVStatusHandler::id() const { return "DTHVStatusHandler"; }
0234 
0235 void DTHVStatusHandler::getChannelMap() {
0236   if (!(buff_session.nominalSchema().existsTable("HVALIASES"))) {
0237     dumpHVAliases();
0238   } else {
0239     std::cout << "retrieve aliases table..." << std::endl;
0240     coral::ITable& hvalTable = buff_session.nominalSchema().tableHandle("HVALIASES");
0241     std::unique_ptr<coral::IQuery> hvalQuery(hvalTable.newQuery());
0242     hvalQuery->addToOutputList("DETID");
0243     hvalQuery->addToOutputList("DPID");
0244     coral::ICursor& hvalCursor = hvalQuery->execute();
0245     int chId;
0246     int dpId;
0247     while (hvalCursor.next()) {
0248       chId = hvalCursor.currentRow()["DETID"].data<int>();
0249       dpId = hvalCursor.currentRow()["DPID"].data<int>();
0250       aliasMap.insert(std::pair<int, int>(dpId, chId));
0251       layerMap.insert(std::pair<int, int>(chId, dpId));
0252     }
0253   }
0254 
0255   return;
0256 }
0257 
0258 void DTHVStatusHandler::getLayerSplit() {
0259   std::cout << "retrieve layer split table..." << std::endl;
0260   int whe;
0261   int sec;
0262   int sta;
0263   int qua;
0264   int lay;
0265   int l_p;
0266   int f_c;
0267   int l_c;
0268   coral::ITable& lsplTable = util_session.nominalSchema().tableHandle("DT_HV_LAYER_SPLIT");
0269   std::cout << "         layer split table got..." << std::endl;
0270   std::unique_ptr<coral::IQuery> lsplQuery(lsplTable.newQuery());
0271   coral::AttributeList versionBindVariableList;
0272   versionBindVariableList.extend("version", typeid(std::string));
0273   versionBindVariableList["version"].data<std::string>() = mapVersion;
0274   lsplQuery->setCondition("VERSION=:version", versionBindVariableList);
0275   lsplQuery->addToOutputList("WHEEL");
0276   lsplQuery->addToOutputList("SECTOR");
0277   lsplQuery->addToOutputList("STATION");
0278   lsplQuery->addToOutputList("SUPERLAYER");
0279   lsplQuery->addToOutputList("LAYER");
0280   lsplQuery->addToOutputList("PART");
0281   lsplQuery->addToOutputList("FIRST_CELL");
0282   lsplQuery->addToOutputList("LAST_CELL");
0283   coral::ICursor& lsplCursor = lsplQuery->execute();
0284   while (lsplCursor.next()) {
0285     whe = lsplCursor.currentRow()["WHEEL"].data<int>();
0286     sec = lsplCursor.currentRow()["SECTOR"].data<int>();
0287     sta = lsplCursor.currentRow()["STATION"].data<int>();
0288     qua = lsplCursor.currentRow()["SUPERLAYER"].data<int>();
0289     lay = lsplCursor.currentRow()["LAYER"].data<int>();
0290     l_p = lsplCursor.currentRow()["PART"].data<int>();
0291     f_c = lsplCursor.currentRow()["FIRST_CELL"].data<int>();
0292     l_c = lsplCursor.currentRow()["LAST_CELL"].data<int>();
0293     DTWireId wireId(whe, sta, sec, qua, lay, 10 + l_p);
0294     laySplit.insert(std::pair<int, int>(wireId.rawId(), (f_c * 10000) + l_c));
0295   }
0296   std::cout << "channel split table retrieved" << std::endl;
0297   return;
0298 }
0299 
0300 void DTHVStatusHandler::getChannelSplit() {
0301   std::cout << "retrieve channel split table..." << std::endl;
0302   int pwhe;
0303   int psec;
0304   int psta;
0305   int pqua;
0306   int play;
0307   int pl_p;
0308   int swhe;
0309   int ssec;
0310   int ssta;
0311   int squa;
0312   int slay;
0313   int sl_p;
0314   coral::ITable& csplTable = util_session.nominalSchema().tableHandle("DT_HV_CHANNEL_SPLIT");
0315   std::unique_ptr<coral::IQuery> csplQuery(csplTable.newQuery());
0316   coral::AttributeList versionBindVariableList;
0317   versionBindVariableList.extend("version", typeid(std::string));
0318   versionBindVariableList["version"].data<std::string>() = splitVersion;
0319   csplQuery->setCondition("VERSION=:version", versionBindVariableList);
0320   csplQuery->addToOutputList("P_WHEEL");
0321   csplQuery->addToOutputList("P_SECTOR");
0322   csplQuery->addToOutputList("P_STATION");
0323   csplQuery->addToOutputList("P_SUPERLAYER");
0324   csplQuery->addToOutputList("P_LAYER");
0325   csplQuery->addToOutputList("P_PART");
0326   csplQuery->addToOutputList("S_NUMBER");
0327   csplQuery->addToOutputList("S_WHEEL");
0328   csplQuery->addToOutputList("S_SECTOR");
0329   csplQuery->addToOutputList("S_STATION");
0330   csplQuery->addToOutputList("S_SUPERLAYER");
0331   csplQuery->addToOutputList("S_LAYER");
0332   csplQuery->addToOutputList("S_PART");
0333   coral::ICursor& csplCursor = csplQuery->execute();
0334   while (csplCursor.next()) {
0335     pwhe = csplCursor.currentRow()["P_WHEEL"].data<int>();
0336     psec = csplCursor.currentRow()["P_SECTOR"].data<int>();
0337     psta = csplCursor.currentRow()["P_STATION"].data<int>();
0338     pqua = csplCursor.currentRow()["P_SUPERLAYER"].data<int>();
0339     play = csplCursor.currentRow()["P_LAYER"].data<int>();
0340     pl_p = csplCursor.currentRow()["P_PART"].data<int>();
0341     csplCursor.currentRow()["S_NUMBER"].data<int>();
0342     swhe = csplCursor.currentRow()["S_WHEEL"].data<int>();
0343     ssec = csplCursor.currentRow()["S_SECTOR"].data<int>();
0344     ssta = csplCursor.currentRow()["S_STATION"].data<int>();
0345     squa = csplCursor.currentRow()["S_SUPERLAYER"].data<int>();
0346     slay = csplCursor.currentRow()["S_LAYER"].data<int>();
0347     sl_p = csplCursor.currentRow()["S_PART"].data<int>();
0348     DTWireId pId(pwhe, psta, psec, pqua, play, 10 + pl_p);
0349     DTWireId sId(swhe, ssta, ssec, squa, slay, 10 + sl_p);
0350     int pRaw = pId.rawId();
0351     int sRaw = sId.rawId();
0352     std::vector<int>* splitList = nullptr;
0353     std::map<int, std::vector<int>*>::iterator iter = channelSplit.find(pRaw);
0354     std::map<int, std::vector<int>*>::iterator iend = channelSplit.end();
0355     if (iter == iend) {
0356       channelSplit.insert(std::pair<int, std::vector<int>*>(pRaw, splitList = new std::vector<int>));
0357     } else {
0358       splitList = iter->second;
0359     }
0360     splitList->push_back(sRaw);
0361   }
0362   return;
0363 }
0364 
0365 void DTHVStatusHandler::dumpHVAliases() {
0366   std::cout << "DTHVStatusHandler::dumpHVAliases - begin" << std::endl;
0367 
0368   std::cout << "create aliases description..." << std::endl;
0369   coral::TableDescription hvalDesc;
0370   hvalDesc.setName("HVALIASES");
0371   hvalDesc.insertColumn("DETID", coral::AttributeSpecification::typeNameForId(typeid(int)));
0372   hvalDesc.insertColumn("DPID", coral::AttributeSpecification::typeNameForId(typeid(int)));
0373   std::cout << "create aliases table..." << std::endl;
0374   coral::ITable& hvalTable = buff_session.nominalSchema().createTable(hvalDesc);
0375 
0376   std::cout << "open DPNAME table..." << std::endl;
0377   std::map<int, std::string> idMap;
0378   coral::ITable& dpidTable = omds_session.nominalSchema().tableHandle("DP_NAME2ID");
0379   std::unique_ptr<coral::IQuery> dpidQuery(dpidTable.newQuery());
0380   dpidQuery->addToOutputList("ID");
0381   dpidQuery->addToOutputList("DPNAME");
0382   coral::ICursor& dpidCursor = dpidQuery->execute();
0383   while (dpidCursor.next()) {
0384     const coral::AttributeList& row = dpidCursor.currentRow();
0385     int id = static_cast<int>(0.01 + row["ID"].data<float>());
0386     std::string dp = row["DPNAME"].data<std::string>();
0387     idMap.insert(std::pair<int, std::string>(id, dp));
0388   }
0389   std::cout << "DPNAME table read... " << idMap.size() << std::endl;
0390 
0391   std::cout << "open ALIASES table..." << std::endl;
0392   std::map<std::string, std::string> cnMap;
0393   coral::ITable& nameTable = omds_session.nominalSchema().tableHandle("ALIASES");
0394   std::unique_ptr<coral::IQuery> nameQuery(nameTable.newQuery());
0395   nameQuery->addToOutputList("DPE_NAME");
0396   nameQuery->addToOutputList("ALIAS");
0397   coral::ICursor& nameCursor = nameQuery->execute();
0398   while (nameCursor.next()) {
0399     const coral::AttributeList& row = nameCursor.currentRow();
0400     std::string dp = row["DPE_NAME"].data<std::string>();
0401     std::string an = row["ALIAS"].data<std::string>();
0402     if (an.length() < 20)
0403       continue;
0404     cnMap.insert(std::pair<std::string, std::string>(dp, an));
0405   }
0406   std::cout << "ALIASES table read... " << cnMap.size() << std::endl;
0407 
0408   std::map<int, std::string>::const_iterator idIter = idMap.begin();
0409   std::map<int, std::string>::const_iterator idIend = idMap.end();
0410   std::string outChk("/outputChannel");
0411   while (idIter != idIend) {
0412     const std::pair<int, std::string>& ientry = *idIter++;
0413     int dpId = ientry.first;
0414     std::string dp = ientry.second;
0415     int ldp = dp.length();
0416     if (ldp < 20)
0417       continue;
0418     std::string subOut(dp.substr(ldp - 17, 17));
0419     std::string subChk(subOut.substr(0, 14));
0420     if (subChk != outChk)
0421       continue;
0422     std::string chName(dp.substr(0, ldp - 17));
0423     chName += ".actual.OvC";
0424     int chCode = subOut.c_str()[16] - '0';
0425     std::map<std::string, std::string>::const_iterator jter = cnMap.find(chName);
0426     if (jter == cnMap.end())
0427       continue;
0428     const std::pair<std::string, std::string>& jentry = *jter;
0429     std::cout << dp << std::endl << chName << " " << chCode << std::endl;
0430     std::string an(jentry.second);
0431     int al = an.length();
0432     int iofw = 7 + an.find("DT_HV_W", 0);
0433     int iofc = 3 + an.find("_MB", 0);
0434     int iofs = 2 + an.find("_S", 0);
0435     int iofq = 3 + an.find("_SL", 0);
0436     int iofl = 2 + an.find("_L", 0);
0437     if ((iofw == al) || (iofc == al) || (iofs == al) || (iofq == al) || (iofl == al)) {
0438       break;
0439     }
0440     int ioew = an.find('_', iofw);
0441     int ioec = an.find('_', iofc);
0442     int ioes = an.find('_', iofs);
0443     int ioeq = an.find('_', iofq);
0444     int ioel = an.find('_', iofl);
0445     std::string swhe(an.substr(iofw, ioew - iofw));
0446     const char* cwhe = swhe.c_str();
0447     int whe = cwhe[1] - '0';
0448     if (*cwhe != 'P')
0449       whe = -whe;
0450 
0451     std::string scha(an.substr(iofc, ioec - iofc));
0452     const char* ccha = scha.c_str();
0453     int cha = *ccha - '0';
0454 
0455     std::string ssec(an.substr(iofs, ioes - iofs));
0456     const char* csec = ssec.c_str();
0457     int sec = ((*csec - '0') * 10) + (csec[1] - '0');
0458     if ((csec[2] == 'R') && (sec == 10))
0459       sec = 14;
0460     if ((csec[2] == 'L') && (sec == 4))
0461       sec = 13;
0462 
0463     std::string squa(an.substr(iofq, ioeq - iofq));
0464     const char* cqua = squa.c_str();
0465     int qua = *cqua - '0';
0466 
0467     std::string slay(an.substr(iofl, ioel - iofl));
0468     const char* clay = slay.c_str();
0469     int lay = *clay - '0';
0470 
0471     DTWireId wireId(whe, cha, sec, qua, lay, 10 + chCode);
0472     int chId = wireId.rawId();
0473     coral::AttributeList newChan;
0474     newChan.extend("DETID", typeid(int));
0475     newChan.extend("DPID", typeid(int));
0476     newChan["DETID"].data<int>() = chId;
0477     newChan["DPID"].data<int>() = dpId;
0478     hvalTable.dataEditor().insertRow(newChan);
0479     aliasMap.insert(std::pair<int, int>(dpId, chId));
0480     layerMap.insert(std::pair<int, int>(chId, dpId));
0481   }
0482 
0483   std::cout << "DTHVStatusHandler::dumpHVAliases - end" << std::endl;
0484   return;
0485 }
0486 
0487 void DTHVStatusHandler::createSnapshot() {
0488   std::cout << "create snapshot description..." << std::endl;
0489   coral::TableDescription hvssDesc;
0490   hvssDesc.setName("HVSNAPSHOT");
0491   hvssDesc.insertColumn("TIME", coral::AttributeSpecification::typeNameForId(typeid(coral::TimeStamp)));
0492   hvssDesc.insertColumn("WHEEL", coral::AttributeSpecification::typeNameForId(typeid(int)));
0493   hvssDesc.insertColumn("STATION", coral::AttributeSpecification::typeNameForId(typeid(int)));
0494   hvssDesc.insertColumn("SECTOR", coral::AttributeSpecification::typeNameForId(typeid(int)));
0495   hvssDesc.insertColumn("SUPERLAYER", coral::AttributeSpecification::typeNameForId(typeid(int)));
0496   hvssDesc.insertColumn("LAYER", coral::AttributeSpecification::typeNameForId(typeid(int)));
0497   hvssDesc.insertColumn("CHAN", coral::AttributeSpecification::typeNameForId(typeid(int)));
0498   hvssDesc.insertColumn("TYPE", coral::AttributeSpecification::typeNameForId(typeid(int)));
0499   hvssDesc.insertColumn("VALUE", coral::AttributeSpecification::typeNameForId(typeid(float)));
0500   std::cout << "create snapshot table..." << std::endl;
0501   buff_session.nominalSchema().createTable(hvssDesc);
0502   coral::ITable& bufferTable = buff_session.nominalSchema().tableHandle("HVSNAPSHOT");
0503   coral::AttributeList newMeas;
0504   newMeas.extend("TIME", typeid(coral::TimeStamp));
0505   newMeas.extend("WHEEL", typeid(int));
0506   newMeas.extend("STATION", typeid(int));
0507   newMeas.extend("SECTOR", typeid(int));
0508   newMeas.extend("SUPERLAYER", typeid(int));
0509   newMeas.extend("LAYER", typeid(int));
0510   newMeas.extend("CHAN", typeid(int));
0511   newMeas.extend("TYPE", typeid(int));
0512   newMeas.extend("VALUE", typeid(float));
0513 
0514   long long int zeroTime = 0LL;
0515   newMeas["TIME"].data<coral::TimeStamp>() = coral::TimeStamp(zeroTime);
0516   newMeas["VALUE"].data<float>() = -999999.0;
0517 
0518   std::map<int, int>::const_iterator iter = aliasMap.begin();
0519   std::map<int, int>::const_iterator iend = aliasMap.end();
0520   while (iter != iend) {
0521     const std::pair<int, int>& entry = *iter++;
0522     int detId = entry.second;
0523     DTWireId chlId(detId);
0524     newMeas["WHEEL"].data<int>() = chlId.wheel();
0525     newMeas["STATION"].data<int>() = chlId.station();
0526     newMeas["SECTOR"].data<int>() = chlId.sector();
0527     newMeas["SUPERLAYER"].data<int>() = chlId.superLayer();
0528     newMeas["LAYER"].data<int>() = chlId.layer();
0529     newMeas["CHAN"].data<int>() = chlId.wire() - 10;
0530     int itype;
0531     for (itype = 1; itype <= 2; itype++) {
0532       newMeas["TYPE"].data<int>() = itype;
0533       bufferTable.dataEditor().insertRow(newMeas);
0534     }
0535   }
0536 
0537   std::cout << "create logging info..." << std::endl;
0538   if (buff_session.nominalSchema().existsTable("LOG"))
0539     buff_session.nominalSchema().dropTable("LOG");
0540   coral::TableDescription infoDesc;
0541   infoDesc.setName("LOG");
0542   infoDesc.insertColumn("EXECTIME", coral::AttributeSpecification::typeNameForId(typeid(coral::TimeStamp)));
0543   infoDesc.insertColumn("SNAPSHOT", coral::AttributeSpecification::typeNameForId(typeid(coral::TimeStamp)));
0544   buff_session.nominalSchema().createTable(infoDesc);
0545   coral::AttributeList newInfo;
0546   newInfo.extend("EXECTIME", typeid(coral::TimeStamp));
0547   newInfo.extend("SNAPSHOT", typeid(coral::TimeStamp));
0548   newInfo["EXECTIME"].data<coral::TimeStamp>() = coral::TimeStamp(zeroTime);
0549   newInfo["SNAPSHOT"].data<coral::TimeStamp>() = coral::TimeStamp(zeroTime);
0550   coral::ITable& infoTable = buff_session.nominalSchema().tableHandle("LOG");
0551   infoTable.dataEditor().insertRow(newInfo);
0552 
0553   return;
0554 }
0555 
0556 void DTHVStatusHandler::updateHVStatus() {
0557   int missingChannels = recoverSnapshot();
0558   cond::Time_t snapshotTime = recoverLastTime();
0559   std::cout << " snapshot at " << snapshotTime << " ( " << coralTime(snapshotTime).total_nanoseconds() << " ) "
0560             << std::endl;
0561   if (snapshotTime > procSince) {
0562     coral::TimeStamp coralSnap = coralTime(snapshotTime);
0563     std::cout << "too recent snapshot: " << std::endl
0564               << " snapshot at " << coralSnap.year() << " " << coralSnap.month() << " " << coralSnap.day() << std::endl
0565               << " copy since " << ySince << " " << mSince << " " << dSince << " ( " << procSince << " )" << std::endl;
0566     return;
0567   }
0568   long long int dTime = bwdTime;
0569   dTime <<= 32;
0570   cond::Time_t condUntil = procSince;
0571   cond::Time_t condSince = condUntil - dTime;
0572 
0573   while (missingChannels) {
0574     std::cout << "back iteration: " << condSince << " ( " << coralTime(condSince).total_nanoseconds() << " ) -> "
0575               << condUntil << " ( " << coralTime(condUntil).total_nanoseconds() << " ) " << std::endl;
0576     if (condSince <= snapshotTime)
0577       condSince = snapshotTime;
0578     std::cout << "corrected since: " << condSince << " ( " << coralTime(condSince).total_nanoseconds() << " ) "
0579               << std::endl;
0580     if (condSince >= condUntil)
0581       break;
0582     std::cout << "missing... " << missingChannels << std::endl;
0583     checkForPeriod(condSince, condUntil, missingChannels, false);
0584     condUntil = condSince;
0585     condSince = condUntil - dTime;
0586   }
0587 
0588   if (dumpAtStart)
0589     dumpSnapshot(coralTime(procSince));
0590 
0591   copyHVData();
0592 
0593   if (dumpAtEnd)
0594     dumpSnapshot(coralTime(lastFound));
0595 
0596   return;
0597 }
0598 
0599 int DTHVStatusHandler::recoverSnapshot() {
0600   int missingChannels = 0;
0601   std::map<int, int>::const_iterator layIter = layerMap.begin();
0602   std::map<int, int>::const_iterator layIend = layerMap.end();
0603   std::cout << "retrieve snapshot table..." << std::endl;
0604   coral::ITable& hvssTable = buff_session.nominalSchema().tableHandle("HVSNAPSHOT");
0605   std::unique_ptr<coral::IQuery> hvssQuery(hvssTable.newQuery());
0606   hvssQuery->addToOutputList("TIME");
0607   hvssQuery->addToOutputList("WHEEL");
0608   hvssQuery->addToOutputList("STATION");
0609   hvssQuery->addToOutputList("SECTOR");
0610   hvssQuery->addToOutputList("SUPERLAYER");
0611   hvssQuery->addToOutputList("LAYER");
0612   hvssQuery->addToOutputList("CHAN");
0613   hvssQuery->addToOutputList("TYPE");
0614   hvssQuery->addToOutputList("VALUE");
0615   coral::ICursor& hvssCursor = hvssQuery->execute();
0616   while (hvssCursor.next()) {
0617     coral::TimeStamp time = hvssCursor.currentRow()["TIME"].data<coral::TimeStamp>();
0618     int whe = hvssCursor.currentRow()["WHEEL"].data<int>();
0619     int sta = hvssCursor.currentRow()["STATION"].data<int>();
0620     int sec = hvssCursor.currentRow()["SECTOR"].data<int>();
0621     int qua = hvssCursor.currentRow()["SUPERLAYER"].data<int>();
0622     int lay = hvssCursor.currentRow()["LAYER"].data<int>();
0623     int l_p = hvssCursor.currentRow()["CHAN"].data<int>();
0624     int mty = hvssCursor.currentRow()["TYPE"].data<int>();
0625     float value = hvssCursor.currentRow()["VALUE"].data<float>();
0626     if (mty > 2)
0627       continue;
0628     DTWireId wireId(whe, sta, sec, qua, lay, 10 + l_p);
0629     layIter = layerMap.find(wireId.rawId());
0630     if (layIter == layIend) {
0631       continue;
0632     }
0633     int dpId = (layIter->second * 10) + mty;
0634     snapshotValues.insert(std::pair<int, timedMeasurement>(dpId, timedMeasurement(time.total_nanoseconds(), value)));
0635     missingChannels++;
0636   }
0637   return missingChannels;
0638 }
0639 
0640 cond::Time_t DTHVStatusHandler::recoverLastTime() {
0641   long long int lastTime = 0LL;
0642   long long int chanTime = 0LL;
0643   std::map<int, timedMeasurement>::iterator mapIter = snapshotValues.begin();
0644   std::map<int, timedMeasurement>::iterator mapIend = snapshotValues.end();
0645   while (mapIter != mapIend) {
0646     const std::pair<int, timedMeasurement>& entry = *mapIter++;
0647     chanTime = entry.second.first;
0648     if (lastTime < chanTime)
0649       lastTime = chanTime;
0650   }
0651   return condTime(lastTime);
0652   /*
0653   coral::ITable& infoTable =
0654          buff_session.nominalSchema().tableHandle( "LOG" );
0655   std::unique_ptr<coral::IQuery> infoQuery( infoTable.newQuery() );
0656   infoQuery->addToOutputList( "SNAPSHOT" );
0657   coral::ICursor& infoCursor = infoQuery->execute();
0658   coral::TimeStamp time;
0659   while ( infoCursor.next() ) {
0660     time = infoCursor.currentRow()["SNAPSHOT"].data<coral::TimeStamp>();
0661   }
0662   return condTime( time );
0663 */
0664 }
0665 
0666 void DTHVStatusHandler::dumpSnapshot(const coral::TimeStamp& time) {
0667   std::cout << "dump snapshot to buffer db..." << std::endl;
0668   std::string emptyCondition("");
0669   coral::AttributeList emptyBindVariableList;
0670   std::map<int, int>::const_iterator mapIter = aliasMap.begin();
0671   std::map<int, int>::const_iterator mapIend = aliasMap.end();
0672   coral::ITable& hvssTable = buff_session.nominalSchema().tableHandle("HVSNAPSHOT");
0673   coral::ITableDataEditor& hvssEditor(hvssTable.dataEditor());
0674   long nRows = hvssEditor.deleteRows(emptyCondition, emptyBindVariableList);
0675   std::cout << nRows << " rows deleted" << std::endl;
0676 
0677   coral::AttributeList newMeas;
0678   newMeas.extend("TIME", typeid(coral::TimeStamp));
0679   newMeas.extend("WHEEL", typeid(int));
0680   newMeas.extend("STATION", typeid(int));
0681   newMeas.extend("SECTOR", typeid(int));
0682   newMeas.extend("SUPERLAYER", typeid(int));
0683   newMeas.extend("LAYER", typeid(int));
0684   newMeas.extend("CHAN", typeid(int));
0685   newMeas.extend("TYPE", typeid(int));
0686   newMeas.extend("VALUE", typeid(float));
0687 
0688   nRows = 0;
0689   std::map<int, timedMeasurement>::const_iterator ssvIter = snapshotValues.begin();
0690   std::map<int, timedMeasurement>::const_iterator ssvIend = snapshotValues.end();
0691   while (ssvIter != ssvIend) {
0692     const std::pair<int, timedMeasurement>& entry = *ssvIter++;
0693     int dpty = entry.first;
0694     int dpId = dpty / 10;
0695     int type = dpty % 10;
0696     mapIter = aliasMap.find(dpId);
0697     if (mapIter == mapIend)
0698       continue;
0699     DTWireId chlId(mapIter->second);
0700     const timedMeasurement& tMeas = entry.second;
0701     long long int newTime = tMeas.first;
0702     newMeas["TIME"].data<coral::TimeStamp>() = coral::TimeStamp(newTime);
0703     newMeas["WHEEL"].data<int>() = chlId.wheel();
0704     newMeas["STATION"].data<int>() = chlId.station();
0705     newMeas["SECTOR"].data<int>() = chlId.sector();
0706     newMeas["SUPERLAYER"].data<int>() = chlId.superLayer();
0707     newMeas["LAYER"].data<int>() = chlId.layer();
0708     newMeas["CHAN"].data<int>() = chlId.wire() - 10;
0709     newMeas["TYPE"].data<int>() = type;
0710     newMeas["VALUE"].data<float>() = tMeas.second;
0711     hvssEditor.insertRow(newMeas);
0712     nRows++;
0713   }
0714   std::cout << nRows << " rows updated" << std::endl;
0715 
0716   std::cout << "create logging info..." << std::endl;
0717   if (buff_session.nominalSchema().existsTable("LOG"))
0718     buff_session.nominalSchema().dropTable("LOG");
0719   coral::TableDescription infoDesc;
0720   infoDesc.setName("LOG");
0721   infoDesc.insertColumn("EXECTIME", coral::AttributeSpecification::typeNameForId(typeid(coral::TimeStamp)));
0722   infoDesc.insertColumn("SNAPSHOT", coral::AttributeSpecification::typeNameForId(typeid(coral::TimeStamp)));
0723   buff_session.nominalSchema().createTable(infoDesc);
0724   coral::AttributeList newInfo;
0725   newInfo.extend("EXECTIME", typeid(coral::TimeStamp));
0726   newInfo.extend("SNAPSHOT", typeid(coral::TimeStamp));
0727   newInfo["EXECTIME"].data<coral::TimeStamp>() = coral::TimeStamp::now();
0728   newInfo["SNAPSHOT"].data<coral::TimeStamp>() = time;
0729   coral::ITable& infoTable = buff_session.nominalSchema().tableHandle("LOG");
0730   infoTable.dataEditor().insertRow(newInfo);
0731 
0732   return;
0733 }
0734 
0735 int DTHVStatusHandler::checkForPeriod(cond::Time_t condSince,
0736                                       cond::Time_t condUntil,
0737                                       int& missingChannels,
0738                                       bool copyOffline) {
0739   std::map<int, timedMeasurement>::iterator mapIter = snapshotValues.begin();
0740   std::map<int, timedMeasurement>::iterator mapIend = snapshotValues.end();
0741 
0742   std::map<long long int, channelValue> periodBuffer;
0743 
0744   coral::ITable& fwccTable = omds_session.nominalSchema().tableHandle("FWCAENCHANNEL");
0745   std::unique_ptr<coral::IQuery> fwccQuery(fwccTable.newQuery());
0746   fwccQuery->addToOutputList("DPID");
0747   fwccQuery->addToOutputList("CHANGE_DATE");
0748   fwccQuery->addToOutputList("ACTUAL_VMON");
0749   fwccQuery->addToOutputList("ACTUAL_IMON");
0750   fwccQuery->addToOutputList("ACTUAL_ISON");
0751   fwccQuery->addToOutputList("ACTUAL_STATUS");
0752   fwccQuery->addToOutputList("ACTUAL_OVC");
0753   coral::AttributeList timeBindVariableList;
0754   timeBindVariableList.extend("since", typeid(coral::TimeStamp));
0755   timeBindVariableList.extend("until", typeid(coral::TimeStamp));
0756   coral::TimeStamp coralSince = coralTime(condSince);
0757   coral::TimeStamp coralUntil = coralTime(condUntil);
0758   std::cout << "look for data since " << coralSince.year() << " " << coralSince.month() << " " << coralSince.day()
0759             << " " << coralSince.hour() << ":" << coralSince.minute() << ":" << coralSince.second() << " until "
0760             << coralUntil.year() << " " << coralUntil.month() << " " << coralUntil.day() << " " << coralUntil.hour()
0761             << ":" << coralUntil.minute() << ":" << coralUntil.second() << std::endl;
0762   timeBindVariableList["since"].data<coral::TimeStamp>() = coralTime(condSince);
0763   timeBindVariableList["until"].data<coral::TimeStamp>() = coralTime(condUntil);
0764   fwccQuery->setCondition("CHANGE_DATE>:since and CHANGE_DATE<:until", timeBindVariableList);
0765   fwccQuery->addToOrderList("CHANGE_DATE");
0766   coral::ICursor& fwccCursor = fwccQuery->execute();
0767   int nrows = 0;
0768   while (fwccCursor.next()) {
0769     nrows++;
0770     const coral::Attribute& dp = fwccCursor.currentRow()["DPID"];
0771     const coral::Attribute& vmon = fwccCursor.currentRow()["ACTUAL_VMON"];
0772     const coral::Attribute& imon = fwccCursor.currentRow()["ACTUAL_IMON"];
0773     coral::TimeStamp changeTime = fwccCursor.currentRow()["CHANGE_DATE"].data<coral::TimeStamp>();
0774     long long int cTimeValue = changeTime.total_nanoseconds();
0775     if (!copyOffline)
0776       cTimeValue = -cTimeValue;
0777     if (dp.isNull()) {
0778       std::cout << "------- " << nrows << std::endl;
0779       continue;
0780     }
0781     int dpId = 10 * static_cast<int>(0.01 + fwccCursor.currentRow()["DPID"].data<float>());
0782     if (!(vmon.isNull())) {
0783       while (periodBuffer.find(cTimeValue) != periodBuffer.end())
0784         cTimeValue++;
0785       int chan = dpId + 1;
0786       periodBuffer.insert(std::pair<long long int, channelValue>(cTimeValue, channelValue(chan, vmon.data<float>())));
0787     }
0788     if (!(imon.isNull())) {
0789       while (periodBuffer.find(cTimeValue) != periodBuffer.end())
0790         cTimeValue++;
0791       int chan = dpId + 2;
0792       periodBuffer.insert(std::pair<long long int, channelValue>(cTimeValue, channelValue(chan, imon.data<float>())));
0793     }
0794   }
0795 
0796   long long int dTime = minTime;
0797   dTime <<= 32;
0798   std::cout << "data found in period: " << periodBuffer.size() << std::endl;
0799   std::map<long long int, channelValue>::const_iterator bufIter = periodBuffer.begin();
0800   std::map<long long int, channelValue>::const_iterator bufIend = periodBuffer.end();
0801 
0802   bool changedStatus = false;
0803   while (bufIter != bufIend) {
0804     const std::pair<long long int, channelValue>& entry = *bufIter++;
0805     long long int mTime = entry.first;
0806     if (!copyOffline)
0807       mTime = -mTime;
0808     channelValue cValue = entry.second;
0809     int chan = cValue.first;
0810     float cont = cValue.second;
0811     mapIter = snapshotValues.find(chan);
0812     if ((mapIter != mapIend) && (mapIter->second.first < mTime)) {
0813       nextFound = condTime(mTime);
0814       if (changedStatus) {
0815         if (nextFound > timeLimit) {
0816           DTHVStatus* hvStatus = offlineList();
0817           std::cout << "new payload " << hvStatus->end() - hvStatus->begin() << std::endl;
0818           tmpContainer.push_back(std::make_pair(hvStatus, lastFound));
0819           changedStatus = false;
0820           if (!(--maxPayload)) {
0821             procUntil = lastFound;
0822             std::cout << "max payload number reached" << std::endl;
0823             break;
0824           }
0825         }
0826       }
0827       if (copyOffline && !changedStatus && checkStatusChange(chan, mapIter->second.second, cont)) {
0828         timeLimit = nextFound + dTime;
0829         changedStatus = true;
0830       }
0831       mapIter->second = timedMeasurement(lastStamp = mTime, cont);
0832       lastFound = nextFound;
0833       missingChannels--;
0834     }
0835   }
0836 
0837   std::cout << nrows << std::endl;
0838   return nrows;
0839 }
0840 
0841 void DTHVStatusHandler::copyHVData() {
0842   long long int dTime = fwdTime;
0843   dTime <<= 32;
0844 
0845   cond::Time_t condSince = procSince;
0846   cond::Time_t condUntil = condSince + dTime;
0847   if (condUntil > procUntil)
0848     condUntil = procUntil;
0849 
0850   int dum = 0;
0851   lastStatus = nullptr;
0852   while (condSince < condUntil) {
0853     checkForPeriod(condSince, condUntil, dum, true);
0854     condSince = condUntil;
0855     condUntil = condSince + dTime;
0856     if (condUntil > procUntil)
0857       condUntil = procUntil;
0858   }
0859   std::cout << "call filterData " << std::endl;
0860   filterData();
0861   std::cout << "filterData return " << switchOff << " " << lastFound << " " << maxPayload << " " << m_to_transfer.size()
0862             << std::endl;
0863   if (switchOff || ((lastFound != 0) && (maxPayload > 0))) {
0864     DTHVStatus* hvStatus = offlineList();
0865     m_to_transfer.push_back(std::make_pair(hvStatus, lastFound));
0866   }
0867 
0868   return;
0869 }
0870 
0871 DTHVStatus* DTHVStatusHandler::offlineList() {
0872   DTHVStatus* hv = new DTHVStatus(dataTag);
0873   int type;
0874   float valueA = 0.0;
0875   float valueL = 0.0;
0876   float valueR = 0.0;
0877   float valueS = 0.0;
0878   float valueC = 0.0;
0879   std::map<int, int>::const_iterator layerIter = layerMap.begin();
0880   std::map<int, int>::const_iterator layerIend = layerMap.end();
0881   while (layerIter != layerIend) {
0882     const std::pair<int, int>& chanEntry = *layerIter++;
0883     int rawId = chanEntry.first;
0884     DTWireId chlId(rawId);
0885     int whe = chlId.wheel();
0886     int sta = chlId.station();
0887     int sec = chlId.sector();
0888     int qua = chlId.superLayer();
0889     int lay = chlId.layer();
0890     int l_p = chlId.wire();
0891     if (l_p != 10)
0892       continue;
0893     for (type = 1; type <= 2; type++) {
0894       getLayerValues(rawId, type, valueL, valueR, valueS, valueC);
0895       for (l_p = 0; l_p <= 1; l_p++) {
0896         int rPart = layerId(rawId, l_p).rawId();
0897         switch (l_p) {
0898           case 0:
0899             valueA = valueL;
0900             break;
0901           case 1:
0902             valueA = valueR;
0903             break;
0904           default:
0905             break;
0906         }
0907         //  std::cout << "layer values: " << type << " " << valueA << " "
0908         //                                               << valueS << " "
0909         //                                               << valueC << std::endl;
0910         DTHVAbstractCheck::flag flag =
0911             hvChecker->checkCurrentStatus(rPart, type, valueA, valueC, valueS, snapshotValues, aliasMap, layerMap);
0912         if (!flag.a && !flag.c && !flag.s)
0913           continue;
0914         setChannelFlag(hv, whe, sta, sec, qua, lay, l_p, flag);
0915         std::map<int, std::vector<int>*>::const_iterator m_iter = channelSplit.find(rPart);
0916         std::map<int, std::vector<int>*>::const_iterator m_iend = channelSplit.end();
0917         if (m_iter != m_iend) {
0918           std::vector<int>* cList = m_iter->second;
0919           std::vector<int>::const_iterator l_iter = cList->begin();
0920           std::vector<int>::const_iterator l_iend = cList->end();
0921           while (l_iter != l_iend) {
0922             DTWireId chlId(*l_iter++);
0923             int wh2 = chlId.wheel();
0924             int st2 = chlId.station();
0925             int se2 = chlId.sector();
0926             int qu2 = chlId.superLayer();
0927             int la2 = chlId.layer();
0928             int lp2 = chlId.wire() - 10;
0929             //      std::cout << "duplicate "
0930             //                      << whe << " " << sta << " " << sec << " "
0931             //                      << qua << " " << lay << " " << l_p << " ---> "
0932             //                      << wh2 << " " << st2 << " " << se2 << " "
0933             //                      << qu2 << " " << la2 << " " << lp2 << std::endl;
0934             setChannelFlag(hv, wh2, st2, se2, qu2, la2, lp2, flag);
0935           }
0936         }
0937       }
0938     }
0939   }
0940   return hv;
0941 }
0942 
0943 void DTHVStatusHandler::getLayerValues(int rawId, int type, float& valueL, float& valueR, float& valueS, float& valueC) {
0944   valueL = valueR = valueS = valueC = 0.0;
0945   DTWireId chlId(rawId);
0946   std::map<int, timedMeasurement>::const_iterator snapIter = snapshotValues.begin();
0947   std::map<int, timedMeasurement>::const_iterator snapIend = snapshotValues.end();
0948   int rawL = layerId(rawId, 0).rawId();
0949   int rawR = layerId(rawId, 1).rawId();
0950   int rawS = layerId(rawId, 2).rawId();
0951   int rawC = layerId(rawId, 3).rawId();
0952   std::map<int, int>::const_iterator layerIter;
0953   std::map<int, int>::const_iterator layerIend = layerMap.end();
0954   if ((layerIter = layerMap.find(rawL)) != layerIend) {
0955     const std::pair<int, int>& layerEntry = *layerIter;
0956     int dpId = layerEntry.second;
0957     snapIter = snapshotValues.find((dpId * 10) + type);
0958     if (snapIter != snapIend) {
0959       const std::pair<int, timedMeasurement>& snapEntry = *snapIter;
0960       valueL = snapEntry.second.second;
0961     } else
0962       std::cout << "snapR not found" << std::endl;
0963   } else
0964     std::cout << "rawR not found" << std::endl;
0965   if ((layerIter = layerMap.find(rawR)) != layerIend) {
0966     const std::pair<int, int>& layerEntry = *layerIter;
0967     int dpId = layerEntry.second;
0968     snapIter = snapshotValues.find((dpId * 10) + type);
0969     if (snapIter != snapIend) {
0970       const std::pair<int, timedMeasurement>& snapEntry = *snapIter;
0971       valueR = snapEntry.second.second;
0972     } else
0973       std::cout << "snapL not found" << std::endl;
0974   } else
0975     std::cout << "rawL not found" << std::endl;
0976   if ((layerIter = layerMap.find(rawS)) != layerIend) {
0977     const std::pair<int, int>& layerEntry = *layerIter;
0978     int dpId = layerEntry.second;
0979     snapIter = snapshotValues.find((dpId * 10) + type);
0980     if (snapIter != snapIend) {
0981       const std::pair<int, timedMeasurement>& snapEntry = *snapIter;
0982       valueS = snapEntry.second.second;
0983     } else
0984       std::cout << "snapS not found" << std::endl;
0985   } else
0986     std::cout << "rawS not found" << std::endl;
0987   if ((layerIter = layerMap.find(rawC)) != layerIend) {
0988     const std::pair<int, int>& layerEntry = *layerIter;
0989     int dpId = layerEntry.second;
0990     snapIter = snapshotValues.find((dpId * 10) + type);
0991     if (snapIter != snapIend) {
0992       const std::pair<int, timedMeasurement>& snapEntry = *snapIter;
0993       valueC = snapEntry.second.second;
0994     } else
0995       std::cout << "snapC not found" << std::endl;
0996   } else
0997     std::cout << "rawC not found" << std::endl;
0998   //  std::cout << "layer values... " << type << " " << valueL << " "
0999   //                                                 << valueR << " "
1000   //                                                 << valueS << " "
1001   //                                                 << valueC << std::endl;
1002   return;
1003 }
1004 
1005 void DTHVStatusHandler::setChannelFlag(
1006     DTHVStatus* hv, int whe, int sta, int sec, int qua, int lay, int l_p, const DTHVAbstractCheck::flag& flag) {
1007   int fCell = 0;
1008   int lCell = 99;
1009   int flagA = 0;
1010   int flagC = 0;
1011   int flagS = 0;
1012   int searchStatus = hv->get(whe, sta, sec, qua, lay, l_p, fCell, lCell, flagA, flagC, flagS);
1013   if (searchStatus) {
1014     DTWireId wireId(whe, sta, sec, qua, lay, 10 + l_p);
1015     std::map<int, int>::const_iterator splitIter = laySplit.find(wireId.rawId());
1016     std::map<int, int>::const_iterator splitIend = laySplit.end();
1017     if (splitIter != splitIend) {
1018       int code = splitIter->second;
1019       fCell = code / 10000;
1020       lCell = code % 10000;
1021     }
1022   }
1023   flagA |= flag.a;
1024   flagC |= flag.c;
1025   flagS |= flag.s;
1026   hv->set(whe, sta, sec, qua, lay, l_p, fCell, lCell, flagA, flagC, flagS);
1027   return;
1028 }
1029 
1030 int DTHVStatusHandler::checkStatusChange(int chan, float oldValue, float newValue) {
1031   int dpId = chan / 10;
1032   int type = chan % 10;
1033   std::map<int, int>::const_iterator aliasIter = aliasMap.find(dpId);
1034   std::map<int, int>::const_iterator aliasIend = aliasMap.end();
1035   if (aliasIter == aliasIend)
1036     return false;
1037   int rawId = aliasIter->second;
1038   DTWireId chlId(rawId);
1039   int l_p = chlId.wire();
1040   float valueL = 0.0;
1041   float valueR = 0.0;
1042   float valueS = 0.0;
1043   float valueC = 0.0;
1044   getLayerValues(rawId, type, valueL, valueR, valueS, valueC);
1045   //  std::cout << "layer values: " << type << " " << valueL << " "
1046   //                                               << valueR << " "
1047   //                                               << valueS << " "
1048   //                                               << valueC << std::endl;
1049   DTHVAbstractCheck::flag oldStatusL = hvChecker->checkCurrentStatus(
1050       layerId(rawId, 0).rawId(), type, valueL, valueC, valueS, snapshotValues, aliasMap, layerMap);
1051   DTHVAbstractCheck::flag oldStatusR = hvChecker->checkCurrentStatus(
1052       layerId(rawId, 1).rawId(), type, valueR, valueC, valueS, snapshotValues, aliasMap, layerMap);
1053   switch (l_p) {
1054     case 10:
1055       if (valueL != oldValue)
1056         std::cout << "*** INCONSISTENT DATA!!!!! " << type << " " << l_p << " " << oldValue << " " << valueL << " "
1057                   << std::endl;
1058       valueL = newValue;
1059       break;
1060     case 11:
1061       if (valueR != oldValue)
1062         std::cout << "*** INCONSISTENT DATA!!!!! " << type << " " << l_p << " " << oldValue << " " << valueR << " "
1063                   << std::endl;
1064       valueR = newValue;
1065       break;
1066     case 12:
1067       if (valueS != oldValue)
1068         std::cout << "*** INCONSISTENT DATA!!!!! " << type << " " << l_p << " " << oldValue << " " << valueS << " "
1069                   << std::endl;
1070       valueS = newValue;
1071       break;
1072     case 13:
1073       if (valueC != oldValue)
1074         std::cout << "*** INCONSISTENT DATA!!!!! " << type << " " << l_p << " " << oldValue << " " << valueC << " "
1075                   << std::endl;
1076       valueC = newValue;
1077       break;
1078     default:
1079       break;
1080   }
1081   DTHVAbstractCheck::flag newStatusL = hvChecker->checkCurrentStatus(
1082       layerId(rawId, 0).rawId(), type, valueL, valueC, valueS, snapshotValues, aliasMap, layerMap);
1083   DTHVAbstractCheck::flag newStatusR = hvChecker->checkCurrentStatus(
1084       layerId(rawId, 1).rawId(), type, valueR, valueC, valueS, snapshotValues, aliasMap, layerMap);
1085 
1086   if (DTHVAbstractCheck::compare(newStatusL, oldStatusL) && DTHVAbstractCheck::compare(newStatusR, oldStatusR))
1087     return 0;
1088   std::cout << "changed status: " << chan << " from " << oldValue << " to " << newValue << std::endl;
1089   return 1;
1090 }
1091 
1092 void DTHVStatusHandler::filterData() {
1093   int maxTime = 100;
1094   int maxTtot = 600;
1095   int minDiff = 88;
1096 
1097   int iTime = 0;
1098   int pTime = 0;
1099   int nTime = 0;
1100   int iSize;
1101   int pSize;
1102   int nSize;
1103 
1104   std::vector<std::pair<DTHVStatus*, cond::Time_t> >::const_iterator iter = tmpContainer.begin();
1105   std::vector<std::pair<DTHVStatus*, cond::Time_t> >::const_iterator iend = tmpContainer.end();
1106   std::vector<std::pair<DTHVStatus*, cond::Time_t> >::const_iterator prev;
1107   std::vector<std::pair<DTHVStatus*, cond::Time_t> >::const_iterator next;
1108 
1109   while (iter != iend) {
1110     switchOff = false;
1111     next = iter;
1112     prev = next++;
1113     if (next == iend)
1114       next = prev;
1115     const DTHVStatus* iPtr = iter->first;
1116     const DTHVStatus* pPtr = prev->first;
1117     const DTHVStatus* nPtr = next->first;
1118     iSize = std::distance(iPtr->begin(), iPtr->end());
1119     pSize = std::distance(pPtr->begin(), pPtr->end());
1120     nSize = std::distance(nPtr->begin(), nPtr->end());
1121     int dtot = nSize - pSize;
1122     prev = next;
1123     while (++next != iend) {
1124       pPtr = prev->first;
1125       nPtr = next->first;
1126       pSize = std::distance(pPtr->begin(), pPtr->end());
1127       nSize = std::distance(nPtr->begin(), nPtr->end());
1128       int diff = nSize - pSize;
1129       iTime = static_cast<int>((iter->second >> 32) & 0xffffffff);
1130       pTime = static_cast<int>((prev->second >> 32) & 0xffffffff);
1131       nTime = static_cast<int>((next->second >> 32) & 0xffffffff);
1132       if ((nTime - pTime) > maxTime)
1133         break;
1134       if ((nTime - iTime) > maxTtot)
1135         break;
1136       if ((dtot * diff) < 0)
1137         break;
1138       prev = next;
1139     }
1140     pPtr = prev->first;
1141     iSize = std::distance(iPtr->begin(), iPtr->end());
1142     pSize = std::distance(pPtr->begin(), pPtr->end());
1143     dtot = pSize - iSize;
1144     int dist = pTime - iTime;
1145     if ((dtot < -minDiff) && (dist < maxTtot)) {
1146       std::cout << "  ******** SWITCH ON " << std::distance(iter, prev) << " " << iTime << " " << pTime << " " << iSize
1147                 << " " << pSize << std::endl;
1148       m_to_transfer.push_back(std::make_pair(prev->first, prev->second));
1149       while (iter != prev)
1150         delete (iter++->first);
1151     }
1152     if ((dtot > minDiff) && (dist < maxTtot)) {
1153       std::cout << "  ******** SWITCH OFF " << std::distance(iter, prev) << " " << iTime << " " << pTime << " " << iSize
1154                 << " " << pSize << std::endl;
1155       m_to_transfer.push_back(std::make_pair(prev->first, iter->second));
1156       switchOff = true;
1157       while (iter != prev)
1158         delete (iter++->first);
1159     }
1160     if (((dtot >= -minDiff) && (dtot <= minDiff)) || (dist >= maxTtot)) {
1161       while (iter != next) {
1162         const std::pair<DTHVStatus*, cond::Time_t>& entry = *iter++;
1163         m_to_transfer.push_back(std::make_pair(entry.first, entry.second));
1164       }
1165     }
1166     iter = next;
1167   }
1168 }
1169 
1170 DTWireId DTHVStatusHandler::layerId(int rawId, int l_p) {
1171   DTWireId chlId(rawId);
1172   int whe = chlId.wheel();
1173   int sta = chlId.station();
1174   int sec = chlId.sector();
1175   int qua = chlId.superLayer();
1176   int lay = chlId.layer();
1177   DTWireId chl(whe, sta, sec, qua, lay, 10 + l_p);
1178   return chl;
1179 }
1180 
1181 coral::TimeStamp DTHVStatusHandler::coralTime(const cond::Time_t& time) {
1182   long long int iTime = ((((time >> 32) & 0xFFFFFFFF) * 1000000000) + ((time & 0xFFFFFFFF) * 1000));
1183   coral::TimeStamp cTime(iTime);
1184   return cTime;
1185 }
1186 
1187 cond::Time_t DTHVStatusHandler::condTime(const coral::TimeStamp& time) {
1188   cond::Time_t cTime =
1189       ((time.total_nanoseconds() / 1000000000) << 32) + ((time.total_nanoseconds() % 1000000000) / 1000);
1190   return cTime;
1191 }
1192 
1193 cond::Time_t DTHVStatusHandler::condTime(long long int time) {
1194   cond::Time_t cTime = ((time / 1000000000) << 32) + ((time % 1000000000) / 1000);
1195   return cTime;
1196 }