CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_6_1_1/src/CondTools/DT/src/DTHVStatusHandler.cc

Go to the documentation of this file.
00001 /*
00002  *  See header file for a description of this class.
00003  *
00004  *  $Date: 2012/01/29 11:23:50 $
00005  *  $Revision: 1.13 $
00006  *  \author Paolo Ronchese INFN Padova
00007  *
00008  */
00009 
00010 //-----------------------
00011 // This Class' Header --
00012 //-----------------------
00013 #include "CondTools/DT/interface/DTHVStatusHandler.h"
00014 
00015 //-------------------------------
00016 // Collaborating Class Headers --
00017 //-------------------------------
00018 #include "CondTools/DT/interface/DTHVAbstractCheck.h"
00019 #include "CondFormats/DTObjects/interface/DTHVStatus.h"
00020 
00021 
00022 #include "CondCore/DBCommon/interface/DbSession.h"
00023 #include "CondCore/DBCommon/interface/DbTransaction.h"
00024 
00025 #include "DataFormats/Provenance/interface/Timestamp.h"
00026 #include "DataFormats/MuonDetId/interface/DTWireId.h"
00027 #include "FWCore/Framework/interface/ESHandle.h"
00028 #include "FWCore/Framework/interface/MakerMacros.h"
00029 #include "RelationalAccess/ISchema.h"
00030 #include "RelationalAccess/ITable.h"
00031 #include "RelationalAccess/ICursor.h"
00032 #include "RelationalAccess/IQuery.h"
00033 #include "RelationalAccess/TableDescription.h"
00034 #include "RelationalAccess/ITableDataEditor.h"
00035 #include "CoralBase/AttributeList.h"
00036 #include "CoralBase/AttributeSpecification.h"
00037 #include "CoralBase/Attribute.h"
00038 #include "CoralBase/TimeStamp.h"
00039 
00040 //---------------
00041 // C++ Headers --
00042 //---------------
00043 #include <map>
00044 #include <sys/time.h>
00045 
00046 //-------------------
00047 // Initializations --
00048 //-------------------
00049 
00050 
00051 //----------------
00052 // Constructors --
00053 //----------------
00054 DTHVStatusHandler::DTHVStatusHandler( const edm::ParameterSet& ps ) :
00055  dataTag(               ps.getParameter<std::string> ( "tag" ) ),
00056  onlineConnect(         ps.getParameter<std::string> ( "onlineDB" ) ),
00057  utilConnect(           ps.getParameter<std::string> ( "utilDB" ) ),
00058  onlineAuthentication(  ps.getParameter<std::string> ( 
00059                         "onlineAuthentication" ) ),
00060  bufferConnect(         ps.getParameter<std::string> ( "bufferDB" ) ),
00061  ySince(                ps.getParameter<int> ( "sinceYear"   ) ),
00062  mSince(                ps.getParameter<int> ( "sinceMonth"  ) ),
00063  dSince(                ps.getParameter<int> ( "sinceDay"    ) ),
00064  hSince(                ps.getParameter<int> ( "sinceHour"   ) ),
00065  pSince(                ps.getParameter<int> ( "sinceMinute" ) ),
00066  sSince(                ps.getParameter<int> ( "sinceSecond" ) ),
00067  yUntil(                ps.getParameter<int> ( "untilYear"   ) ),
00068  mUntil(                ps.getParameter<int> ( "untilMonth"  ) ),
00069  dUntil(                ps.getParameter<int> ( "untilDay"    ) ),
00070  hUntil(                ps.getParameter<int> ( "untilHour"   ) ),
00071  pUntil(                ps.getParameter<int> ( "untilMinute" ) ),
00072  sUntil(                ps.getParameter<int> ( "untilSecond" ) ),
00073  dumpAtStart(           ps.getParameter<bool>( "dumpAtStart" ) ),
00074  dumpAtEnd(             ps.getParameter<bool>( "dumpAtEnd"   ) ),
00075  bwdTime(               ps.getParameter<long long int> ( "bwdTime" ) ),
00076  fwdTime(               ps.getParameter<long long int> ( "fwdTime" ) ),
00077  minTime(               ps.getParameter<long long int> ( "minTime" ) ),
00078  omds_conn(),
00079  util_conn(),
00080  buff_conn(),
00081  omds_session(),
00082  util_session(),
00083  buff_session(),
00084  mapVersion(            ps.getParameter<std::string> ( "mapVersion"   ) ),
00085  splitVersion(          ps.getParameter<std::string> ( "splitVersion" ) ) {
00086   std::cout << " PopCon application for DT HV data export "
00087             << onlineAuthentication
00088             << std::endl;
00089   hvChecker = DTHVAbstractCheck::getInstance();
00090   maxPayload = 1000;
00091 }
00092 
00093 //--------------
00094 // Destructor --
00095 //--------------
00096 DTHVStatusHandler::~DTHVStatusHandler() {
00097 }
00098 
00099 //--------------
00100 // Operations --
00101 //--------------
00102 void DTHVStatusHandler::getNewObjects() {
00103 
00104   std::cout << "get new objects..." << std::endl;
00105 
00106   // online DB connection - data
00107   std::cout << "configure omds DbConnection" << std::endl;
00108   //  conn->configure( cond::CmsDefaults );
00109   omds_conn.configuration().setAuthenticationPath( onlineAuthentication );
00110   omds_conn.configure();
00111   std::cout << "create omds DbSession" << std::endl;
00112   omds_session = omds_conn.createSession();
00113   std::cout << "open omds session" << std::endl;
00114   omds_session.open( onlineConnect );
00115   std::cout << "start omds transaction" << std::endl;
00116   omds_session.transaction().start();
00117   std::cout << "" << std::endl;
00118 
00119   // online DB connection - util
00120   std::cout << "configure util DbConnection" << std::endl;
00121   //  conn->configure( cond::CmsDefaults );
00122   util_conn.configuration().setAuthenticationPath( onlineAuthentication );
00123   util_conn.configure();
00124   std::cout << "create util DbSession" << std::endl;
00125   util_session = util_conn.createSession();
00126   std::cout << "open util session" << std::endl;
00127   util_session.open( onlineConnect );
00128   std::cout << "startutil  transaction" << std::endl;
00129   util_session.transaction().start();
00130   std::cout << "" << std::endl;
00131 
00132   // buffer DB connection
00133   std::cout << "configure buffer DbConnection" << std::endl;
00134   buff_conn.configuration().setAuthenticationPath( onlineAuthentication );
00135   buff_conn.configure();
00136   std::cout << "create buffer DbSession" << std::endl;
00137   buff_session = buff_conn.createSession();
00138   std::cout << "open buffer session" << std::endl;
00139   buff_session.open( bufferConnect );
00140   std::cout << "start buffer transaction" << std::endl;
00141   buff_session.transaction().start();
00142 
00143   // offline info
00144 
00145   //to access the information on the tag inside the offline database:
00146   cond::TagInfo const & ti = tagInfo();
00147   cond::Time_t last = ti.lastInterval.first;
00148   std::cout << "latest DCS data (HV) already copied until: "
00149             << last << std::endl;
00150 
00151   coral::TimeStamp coralSince( ySince, mSince, dSince,
00152                                hSince, pSince, sSince, 0 );
00153   procSince = condTime( coralSince );
00154   coral::TimeStamp coralUntil( yUntil, mUntil, dUntil,
00155                                hUntil, pUntil, sUntil, 0 );
00156   procUntil = condTime( coralUntil );
00157   lastFound = 0;
00158   nextFound = 0;
00159   timeLimit = 0;
00160   lastStamp = 0;
00161 
00162   if ( last == 0 ) {
00163     DTHVStatus* dummyStatus = new DTHVStatus( dataTag );
00164     cond::Time_t snc = 1;
00165     m_to_transfer.push_back( std::make_pair( dummyStatus, snc ) );
00166     last = procSince + 1;
00167     std::cout << "no old data... " << last << std::endl;
00168   }
00169   else {
00170     Ref payload = lastPayload();
00171     DTHVStatus::const_iterator paylIter = payload->begin();
00172     DTHVStatus::const_iterator paylIend = payload->end();
00173     while ( paylIter != paylIend ) {
00174       const std::pair<DTHVStatusId,DTHVStatusData>& entry = *paylIter++;
00175       const DTHVStatusId&   chan = entry.first;
00176       const DTHVStatusData& data = entry.second;
00177       DTWireId id( chan.wheelId, chan.stationId, chan.sectorId,
00178                    chan.   slId, chan.  layerId, chan.  partId + 10 );
00179       hvChecker->setStatus( id.rawId(),
00180                             data.flagA, data.flagC, data.flagS,
00181                             snapshotValues,
00182                             aliasMap, layerMap );
00183     }
00184   }
00185   coral::TimeStamp coralLast = coralTime( last );
00186   coral::TimeStamp coralProc = coral::TimeStamp::now();
00187   cond::Time_t condProc = condTime( coralProc );
00188 
00189   if ( procSince > condProc ) {
00190       std::cout << "Required time interval in the future: "
00191                                                        << std::endl
00192                 << " copy since " << ySince << " "
00193                                   << mSince << " "
00194                                   << dSince
00195                 << " ( "          << procSince << " )" << std::endl
00196                 << " current time " << coralProc.year( ) << " "
00197                                     << coralProc.month() << " "
00198                                     << coralProc.day(  ) << std::endl;
00199   }
00200   if ( procUntil > condProc ) procUntil = condProc;
00201   if ( last > procSince ) {
00202     if ( last < procUntil ) {
00203       procSince = last;
00204       checkNewData();
00205     }
00206     else {
00207       std::cout << "Required time interval already copied: "
00208                                                        << std::endl
00209                 << " copy until " << yUntil << " "
00210                                   << mUntil << " "
00211                                   << dUntil
00212                 << " ( "          << procUntil << " )" << std::endl
00213                 << " data until " << coralLast.year( ) << " "
00214                                   << coralLast.month() << " "
00215                                   << coralLast.day(  ) << std::endl;
00216     }
00217   }
00218   else {
00219     std::cout << "Required time interval not contiguous with copied data: "
00220                                                      << std::endl
00221               << " data until " << coralLast.year( ) << " "
00222                                 << coralLast.month() << " "
00223                                 << coralLast.day(  ) << std::endl
00224               << " copy since " << ySince << " "
00225                                 << mSince << " "
00226                                 << dSince
00227               << " ( "          << procSince << " )" << std::endl;
00228   }
00229 
00230   buff_session.transaction().commit();
00231   buff_session.close();
00232   omds_session.close();
00233   util_session.close();
00234 
00235   return;
00236 
00237 }
00238 
00239 
00240 void DTHVStatusHandler::checkNewData() {
00241 
00242   //to access the information on last successful log entry for this tag:
00243 //  cond::LogDBEntry const & lde = logDBEntry();     
00244 
00245   //to access the lastest payload (Ref is a smart pointer)
00246 //  Ref payload = lastPayload();
00247 
00248   std::cout << "check for new data since "
00249             << procSince << " "
00250             << coralTime( procSince ).total_nanoseconds() << " "
00251             << coralTime( procSince ).year(  ) << " "
00252             << coralTime( procSince ).month( ) << " "
00253             << coralTime( procSince ).day(   ) << " "
00254             << coralTime( procSince ).hour(  ) << " "
00255             << coralTime( procSince ).minute() << " "
00256             << coralTime( procSince ).second() << std::endl;
00257   std::cout << "                   until "
00258             << procUntil << " "
00259             << coralTime( procUntil ).total_nanoseconds() << " "
00260             << coralTime( procUntil ).year(  ) << " "
00261             << coralTime( procUntil ).month( ) << " "
00262             << coralTime( procUntil ).day(   ) << " "
00263             << coralTime( procUntil ).hour(  ) << " "
00264             << coralTime( procUntil ).minute() << " "
00265             << coralTime( procUntil ).second() << std::endl;
00266 
00267   std::set<std::string> omds_lt( omds_session.nominalSchema().listTables() );
00268   std::set<std::string>::const_iterator omds_iter = omds_lt.begin();
00269   std::set<std::string>::const_iterator omds_iend = omds_lt.end();
00270   while ( omds_iter != omds_iend ) {
00271     const std::string& istr = *omds_iter++;
00272     std::cout << "TABLE: " << istr << std::endl;
00273   }
00274 
00275   std::set<std::string> util_lt( util_session.nominalSchema().listTables() );
00276   std::set<std::string>::const_iterator util_iter = util_lt.begin();
00277   std::set<std::string>::const_iterator util_iend = util_lt.end();
00278   while ( util_iter != util_iend ) {
00279     const std::string& istr = *util_iter++;
00280     std::cout << "TABLE: " << istr << std::endl;
00281   }
00282 
00283   getLayerSplit();
00284   getChannelMap();
00285   getChannelSplit();
00286 
00287   std::cout << "open buffer db..." << std::endl;
00288 
00289   if ( !( buff_session.nominalSchema().existsTable( "HVSNAPSHOT" ) ) )
00290       createSnapshot();
00291   updateHVStatus();
00292 
00293   return;
00294 
00295 }
00296 
00297 std::string DTHVStatusHandler::id() const {
00298   return "DTHVStatusHandler";
00299 }
00300 
00301 
00302 void DTHVStatusHandler::getChannelMap() {
00303 
00304   if ( !( buff_session.nominalSchema().existsTable( "HVALIASES" ) ) ) {
00305     dumpHVAliases();
00306   }
00307   else {
00308     std::cout << "retrieve aliases table..." << std::endl;
00309     coral::ITable& hvalTable =
00310       buff_session.nominalSchema().tableHandle( "HVALIASES" );
00311     std::auto_ptr<coral::IQuery> hvalQuery( hvalTable.newQuery() );
00312     hvalQuery->addToOutputList( "DETID" );
00313     hvalQuery->addToOutputList(  "DPID" );
00314     coral::ICursor& hvalCursor = hvalQuery->execute();
00315     int chId;
00316     int dpId;
00317     while ( hvalCursor.next() ) {
00318       chId = hvalCursor.currentRow()["DETID"].data<int>();
00319       dpId = hvalCursor.currentRow()[ "DPID"].data<int>();
00320       aliasMap.insert( std::pair<int,int>( dpId, chId ) );
00321       layerMap.insert( std::pair<int,int>( chId, dpId ) );
00322     }
00323   }
00324 
00325   return;
00326 
00327 }
00328 
00329 
00330 void DTHVStatusHandler::getLayerSplit() {
00331   std::cout << "retrieve layer split table..." << std::endl;
00332   int whe;
00333   int sec;
00334   int sta;
00335   int qua;
00336   int lay;
00337   int l_p;
00338   int f_c;
00339   int l_c;
00340   coral::ITable& lsplTable =
00341     util_session.nominalSchema().tableHandle( "DT_HV_LAYER_SPLIT" );
00342   std::cout << "         layer split table got..." << std::endl;
00343   std::auto_ptr<coral::IQuery> lsplQuery( lsplTable.newQuery() );
00344   coral::AttributeList versionBindVariableList;
00345   versionBindVariableList.extend( "version", typeid(std::string) );
00346   versionBindVariableList["version"].data<std::string>() = mapVersion;
00347   lsplQuery->setCondition( "VERSION=:version", versionBindVariableList );
00348   lsplQuery->addToOutputList( "WHEEL" );
00349   lsplQuery->addToOutputList( "SECTOR" );
00350   lsplQuery->addToOutputList( "STATION" );
00351   lsplQuery->addToOutputList( "SUPERLAYER" );
00352   lsplQuery->addToOutputList( "LAYER" );
00353   lsplQuery->addToOutputList( "PART" );
00354   lsplQuery->addToOutputList( "FIRST_CELL" );
00355   lsplQuery->addToOutputList( "LAST_CELL" );
00356   coral::ICursor& lsplCursor = lsplQuery->execute();
00357   while ( lsplCursor.next() ) {
00358     whe = lsplCursor.currentRow()["WHEEL"     ].data<int>();
00359     sec = lsplCursor.currentRow()["SECTOR"    ].data<int>();
00360     sta = lsplCursor.currentRow()["STATION"   ].data<int>();
00361     qua = lsplCursor.currentRow()["SUPERLAYER"].data<int>();
00362     lay = lsplCursor.currentRow()["LAYER"     ].data<int>();
00363     l_p = lsplCursor.currentRow()["PART"      ].data<int>();
00364     f_c = lsplCursor.currentRow()["FIRST_CELL"].data<int>();
00365     l_c = lsplCursor.currentRow()[ "LAST_CELL"].data<int>();
00366     DTWireId wireId( whe, sta, sec, qua, lay, 10 + l_p );
00367     laySplit.insert( std::pair<int,int>( wireId.rawId(), 
00368                                          ( f_c * 10000 ) + l_c ) );
00369   }
00370   std::cout << "channel split table retrieved" << std::endl;
00371   return;
00372 }
00373 
00374 
00375 void DTHVStatusHandler::getChannelSplit() {
00376   std::cout << "retrieve channel split table..." << std::endl;
00377   int pwhe;
00378   int psec;
00379   int psta;
00380   int pqua;
00381   int play;
00382   int pl_p;
00383   int swhe;
00384   int ssec;
00385   int ssta;
00386   int squa;
00387   int slay;
00388   int sl_p;
00389   coral::ITable& csplTable =
00390     util_session.nominalSchema().tableHandle( "DT_HV_CHANNEL_SPLIT" );
00391   std::auto_ptr<coral::IQuery> csplQuery( csplTable.newQuery() );
00392   coral::AttributeList versionBindVariableList;
00393   versionBindVariableList.extend( "version", typeid(std::string) );
00394   versionBindVariableList["version"].data<std::string>() = splitVersion;
00395   csplQuery->setCondition( "VERSION=:version", versionBindVariableList );
00396   csplQuery->addToOutputList( "P_WHEEL" );
00397   csplQuery->addToOutputList( "P_SECTOR" );
00398   csplQuery->addToOutputList( "P_STATION" );
00399   csplQuery->addToOutputList( "P_SUPERLAYER" );
00400   csplQuery->addToOutputList( "P_LAYER" );
00401   csplQuery->addToOutputList( "P_PART" );
00402   csplQuery->addToOutputList( "S_NUMBER" );
00403   csplQuery->addToOutputList( "S_WHEEL" );
00404   csplQuery->addToOutputList( "S_SECTOR" );
00405   csplQuery->addToOutputList( "S_STATION" );
00406   csplQuery->addToOutputList( "S_SUPERLAYER" );
00407   csplQuery->addToOutputList( "S_LAYER" );
00408   csplQuery->addToOutputList( "S_PART" );
00409   coral::ICursor& csplCursor = csplQuery->execute();
00410   while ( csplCursor.next() ) {
00411     pwhe = csplCursor.currentRow()["P_WHEEL"     ].data<int>();
00412     psec = csplCursor.currentRow()["P_SECTOR"    ].data<int>();
00413     psta = csplCursor.currentRow()["P_STATION"   ].data<int>();
00414     pqua = csplCursor.currentRow()["P_SUPERLAYER"].data<int>();
00415     play = csplCursor.currentRow()["P_LAYER"     ].data<int>();
00416     pl_p = csplCursor.currentRow()["P_PART"      ].data<int>();
00417     csplCursor.currentRow()["S_NUMBER"    ].data<int>();
00418     swhe = csplCursor.currentRow()["S_WHEEL"     ].data<int>();
00419     ssec = csplCursor.currentRow()["S_SECTOR"    ].data<int>();
00420     ssta = csplCursor.currentRow()["S_STATION"   ].data<int>();
00421     squa = csplCursor.currentRow()["S_SUPERLAYER"].data<int>();
00422     slay = csplCursor.currentRow()["S_LAYER"     ].data<int>();
00423     sl_p = csplCursor.currentRow()["S_PART"      ].data<int>();
00424     DTWireId pId( pwhe, psta, psec, pqua, play, 10 + pl_p );
00425     DTWireId sId( swhe, ssta, ssec, squa, slay, 10 + sl_p );
00426     int pRaw = pId.rawId();
00427     int sRaw = sId.rawId();
00428     std::vector<int>* splitList = 0;
00429     std::map< int,std::vector<int>* >::iterator iter =
00430                                                 channelSplit.find( pRaw );
00431     std::map< int,std::vector<int>* >::iterator iend =
00432                                                 channelSplit.end();
00433     if ( iter == iend ) {
00434       channelSplit.insert( std::pair< int,
00435                                       std::vector<int>* >( pRaw, splitList =
00436                                       new std::vector<int> ) );
00437     }
00438     else {
00439       splitList = iter->second;
00440     }
00441     splitList->push_back( sRaw );
00442   }
00443   return;
00444 }
00445 
00446 
00447 void DTHVStatusHandler::dumpHVAliases() {
00448 
00449   std::cout << "DTHVStatusHandler::dumpHVAliases - begin" << std::endl;
00450 
00451   std::cout << "create aliases description..." << std::endl;
00452   coral::TableDescription hvalDesc;
00453   hvalDesc.setName( "HVALIASES" );
00454   hvalDesc.insertColumn( "DETID",
00455                          coral::AttributeSpecification::typeNameForId( 
00456                          typeid(int) ) );
00457   hvalDesc.insertColumn(  "DPID",
00458                          coral::AttributeSpecification::typeNameForId( 
00459                          typeid(int) ) );
00460   std::cout << "create aliases table..." << std::endl;
00461   coral::ITable& hvalTable = 
00462   buff_session.nominalSchema().createTable( hvalDesc );
00463 
00464   std::cout << "open DPNAME table..." << std::endl;
00465   std::map<int,std::string> idMap;
00466   coral::ITable& dpidTable =
00467     omds_session.nominalSchema().tableHandle( "DP_NAME2ID" );
00468   std::auto_ptr<coral::IQuery> dpidQuery( dpidTable.newQuery() );
00469   dpidQuery->addToOutputList( "ID" );
00470   dpidQuery->addToOutputList( "DPNAME" );
00471   coral::ICursor& dpidCursor = dpidQuery->execute();
00472   while( dpidCursor.next() ) {
00473     const coral::AttributeList& row = dpidCursor.currentRow();
00474     int id         = static_cast<int>( 0.01 +
00475                      row["ID"    ].data<float>() );
00476     std::string dp = row["DPNAME"].data<std::string>();
00477     idMap.insert( std::pair<int,std::string>( id, dp ) );
00478   }
00479   std::cout << "DPNAME table read... " << idMap.size() << std::endl;
00480 
00481   std::cout << "open ALIASES table..." << std::endl;
00482   std::map<std::string,std::string> cnMap;
00483   coral::ITable& nameTable =
00484     omds_session.nominalSchema().tableHandle( "ALIASES" );
00485   std::auto_ptr<coral::IQuery> nameQuery( nameTable.newQuery() );
00486   nameQuery->addToOutputList( "DPE_NAME" );
00487   nameQuery->addToOutputList( "ALIAS" );
00488   coral::ICursor& nameCursor = nameQuery->execute();
00489   while( nameCursor.next() ) {
00490     const coral::AttributeList& row = nameCursor.currentRow();
00491     std::string dp = row["DPE_NAME"].data<std::string>();
00492     std::string an = row["ALIAS"   ].data<std::string>();
00493     if ( an.length() < 20 ) continue;
00494     cnMap.insert( std::pair<std::string,std::string>( dp, an ) );
00495   }
00496   std::cout << "ALIASES table read... " << cnMap.size() << std::endl;
00497 
00498   std::map<int,std::string>::const_iterator idIter = idMap.begin();
00499   std::map<int,std::string>::const_iterator idIend = idMap.end();
00500   std::string outChk( "/outputChannel" );
00501   while ( idIter != idIend ) {
00502     const std::pair<int,std::string>& ientry = *idIter++;
00503     int dpId       = ientry.first;
00504     std::string dp = ientry.second;
00505     int ldp = dp.length();
00506     if ( ldp < 20 ) continue;
00507     std::string subOut( dp.substr( ldp - 17, 17 ) );
00508     std::string subChk( subOut.substr( 0, 14 ) );
00509     if ( subChk != outChk ) continue;
00510     std::string chName( dp.substr( 0, ldp - 17 ) );
00511     chName += ".actual.OvC";
00512     int chCode = subOut.c_str()[16] - '0';
00513     std::map<std::string,std::string>::const_iterator jter =
00514                                                       cnMap.find( chName );
00515     if ( jter == cnMap.end() ) continue;
00516     const std::pair<std::string,std::string>& jentry = *jter;
00517     std::cout << dp << std::endl << chName << " " << chCode << std::endl;
00518     std::string an( jentry.second );
00519     int al = an.length();
00520     int iofw = 7 + an.find( "DT_HV_W", 0 );
00521     int iofc = 3 + an.find( "_MB", 0 );
00522     int iofs = 2 + an.find( "_S" , 0 );
00523     int iofq = 3 + an.find( "_SL", 0 );
00524     int iofl = 2 + an.find( "_L" , 0 );
00525     if ( ( iofw == al ) ||
00526          ( iofc == al ) ||
00527          ( iofs == al ) ||
00528          ( iofq == al ) ||
00529          ( iofl == al ) ) {
00530       break;
00531     }
00532     int ioew = an.find( "_", iofw );
00533     int ioec = an.find( "_", iofc );
00534     int ioes = an.find( "_", iofs );
00535     int ioeq = an.find( "_", iofq );
00536     int ioel = an.find( "_", iofl );
00537     std::string swhe( an.substr( iofw, ioew - iofw ) );
00538     const char* cwhe = swhe.c_str();
00539     int whe = cwhe[1] - '0';
00540     if ( *cwhe != 'P' ) whe = -whe;
00541 
00542     std::string scha( an.substr( iofc, ioec - iofc ) );
00543     const char* ccha = scha.c_str();
00544     int cha = *ccha - '0';
00545 
00546     std::string ssec( an.substr( iofs, ioes - iofs ) );
00547     const char* csec = ssec.c_str();
00548     int sec = ( ( *csec - '0' ) * 10 ) + ( csec[1] - '0' );
00549     if ( ( csec[2] == 'R' ) && ( sec == 10 ) ) sec = 14;
00550     if ( ( csec[2] == 'L' ) && ( sec ==  4 ) ) sec = 13;
00551 
00552     std::string squa( an.substr( iofq, ioeq - iofq ) );
00553     const char* cqua = squa.c_str();
00554     int qua = *cqua - '0';
00555 
00556     std::string slay( an.substr( iofl, ioel - iofl ) );
00557     const char* clay = slay.c_str();
00558     int lay = *clay - '0';
00559 
00560     DTWireId wireId( whe, cha, sec, qua, lay, 10 + chCode );
00561     int chId = wireId.rawId();
00562     coral::AttributeList newChan;
00563     newChan.extend( "DETID", typeid(int) );
00564     newChan.extend(  "DPID", typeid(int) );
00565     newChan["DETID"].data<int>() = chId;
00566     newChan[ "DPID"].data<int>() = dpId;
00567     hvalTable.dataEditor().insertRow( newChan );
00568     aliasMap.insert( std::pair<int,int>( dpId, chId ) );
00569     layerMap.insert( std::pair<int,int>( chId, dpId ) );
00570   }
00571 
00572   std::cout << "DTHVStatusHandler::dumpHVAliases - end" << std::endl;
00573   return;
00574 }
00575 
00576 
00577 void DTHVStatusHandler::createSnapshot() {
00578   std::cout << "create snapshot description..." << std::endl;
00579   coral::TableDescription hvssDesc;
00580   hvssDesc.setName( "HVSNAPSHOT" );
00581   hvssDesc.insertColumn( "TIME",
00582                          coral::AttributeSpecification::typeNameForId( 
00583                          typeid(coral::TimeStamp) ) );
00584   hvssDesc.insertColumn( "WHEEL",
00585                          coral::AttributeSpecification::typeNameForId( 
00586                          typeid(int) ) );
00587   hvssDesc.insertColumn( "STATION",
00588                          coral::AttributeSpecification::typeNameForId( 
00589                          typeid(int) ) );
00590   hvssDesc.insertColumn( "SECTOR",
00591                          coral::AttributeSpecification::typeNameForId( 
00592                          typeid(int) ) );
00593   hvssDesc.insertColumn( "SUPERLAYER",
00594                          coral::AttributeSpecification::typeNameForId( 
00595                          typeid(int) ) );
00596   hvssDesc.insertColumn( "LAYER",
00597                          coral::AttributeSpecification::typeNameForId( 
00598                          typeid(int) ) );
00599   hvssDesc.insertColumn( "CHAN",
00600                          coral::AttributeSpecification::typeNameForId( 
00601                          typeid(int) ) );
00602   hvssDesc.insertColumn( "TYPE",
00603                          coral::AttributeSpecification::typeNameForId( 
00604                          typeid(int) ) );
00605   hvssDesc.insertColumn( "VALUE",
00606                          coral::AttributeSpecification::typeNameForId( 
00607                          typeid(float) ) );
00608   std::cout << "create snapshot table..." << std::endl;
00609   buff_session.nominalSchema().createTable( hvssDesc );
00610   coral::ITable& bufferTable = 
00611     buff_session.nominalSchema().tableHandle( "HVSNAPSHOT" );
00612   coral::AttributeList newMeas;
00613   newMeas.extend( "TIME",       typeid(coral::TimeStamp) );
00614   newMeas.extend( "WHEEL",      typeid(int) );
00615   newMeas.extend( "STATION",    typeid(int) );
00616   newMeas.extend( "SECTOR",     typeid(int) );
00617   newMeas.extend( "SUPERLAYER", typeid(int) );
00618   newMeas.extend( "LAYER",      typeid(int) );
00619   newMeas.extend( "CHAN",       typeid(int) );
00620   newMeas.extend( "TYPE",       typeid(int) );
00621   newMeas.extend( "VALUE",      typeid(float) );
00622 
00623   long long int zeroTime = 0LL;
00624   newMeas["TIME"     ].data<coral::TimeStamp>() =
00625                             coral::TimeStamp( zeroTime );
00626   newMeas["VALUE"    ].data<float>() = -999999.0;
00627 
00628   std::map<int,int>::const_iterator iter = aliasMap.begin();
00629   std::map<int,int>::const_iterator iend = aliasMap.end();
00630   while ( iter != iend ) {
00631     const std::pair<int,int>& entry= *iter++;
00632     int detId = entry.second;
00633     DTWireId chlId( detId );
00634     newMeas["WHEEL"     ].data<int>() = chlId.wheel     ();
00635     newMeas["STATION"   ].data<int>() = chlId.station   ();
00636     newMeas["SECTOR"    ].data<int>() = chlId.sector    ();
00637     newMeas["SUPERLAYER"].data<int>() = chlId.superLayer();
00638     newMeas["LAYER"     ].data<int>() = chlId.layer     ();
00639     newMeas["CHAN"      ].data<int>() = chlId.wire      () - 10;
00640     int itype;
00641     for ( itype = 1; itype <= 2; itype++ ) {
00642       newMeas["TYPE"      ].data<int>() = itype;
00643       bufferTable.dataEditor().insertRow( newMeas );
00644     }
00645   }
00646 
00647   std::cout << "create logging info..." << std::endl;
00648   if ( buff_session.nominalSchema().existsTable( "LOG" ) )
00649        buff_session.nominalSchema().  dropTable( "LOG" );
00650   coral::TableDescription infoDesc;
00651   infoDesc.setName( "LOG" );
00652   infoDesc.insertColumn( "EXECTIME",
00653                          coral::AttributeSpecification::typeNameForId( 
00654                          typeid(coral::TimeStamp) ) );
00655   infoDesc.insertColumn( "SNAPSHOT",
00656                          coral::AttributeSpecification::typeNameForId( 
00657                          typeid(coral::TimeStamp) ) );
00658   buff_session.nominalSchema().createTable( infoDesc );
00659   coral::AttributeList newInfo;
00660   newInfo.extend( "EXECTIME", typeid(coral::TimeStamp) );
00661   newInfo.extend( "SNAPSHOT", typeid(coral::TimeStamp) );
00662   newInfo["EXECTIME"].data<coral::TimeStamp>() =
00663                            coral::TimeStamp( zeroTime );
00664   newInfo["SNAPSHOT"].data<coral::TimeStamp>() =
00665                            coral::TimeStamp( zeroTime );
00666   coral::ITable& infoTable = 
00667     buff_session.nominalSchema().tableHandle( "LOG" );
00668   infoTable.dataEditor().insertRow( newInfo );
00669 
00670   return;
00671 
00672 }
00673 
00674 
00675 void DTHVStatusHandler::updateHVStatus() {
00676   int missingChannels = recoverSnapshot();
00677   cond::Time_t snapshotTime = recoverLastTime();
00678   std::cout << " snapshot at " << snapshotTime << " ( "
00679                                << coralTime( snapshotTime )
00680                                   .total_nanoseconds() << " ) "
00681                                << std::endl;
00682   if ( snapshotTime > procSince ) {
00683     coral::TimeStamp coralSnap = coralTime( snapshotTime );
00684     std::cout << "too recent snapshot: " << std::endl
00685               << " snapshot at " << coralSnap.year( ) << " "
00686                                  << coralSnap.month() << " "
00687                                  << coralSnap.day(  ) << std::endl
00688               << " copy since " << ySince << " "
00689                                 << mSince << " "
00690                                 << dSince
00691               << " ( "          << procSince << " )" << std::endl;
00692     return;
00693   }
00694   long long int dTime = bwdTime;
00695   dTime <<= 32;
00696   cond::Time_t condUntil = procSince;
00697   cond::Time_t condSince = condUntil - dTime;
00698 
00699   while ( missingChannels ) {
00700     std::cout << "back iteration: "
00701               << condSince << " ( " << coralTime( condSince )
00702                                        .total_nanoseconds() << " ) -> "
00703               << condUntil << " ( " << coralTime( condUntil )
00704                                        .total_nanoseconds() << " ) "
00705               << std::endl;
00706     if ( condSince <= snapshotTime ) condSince = snapshotTime;
00707     std::cout << "corrected since: "
00708               << condSince << " ( " << coralTime( condSince )
00709                                        .total_nanoseconds() << " ) "
00710               << std::endl;
00711     if ( condSince >= condUntil    ) break;
00712     std::cout << "missing... " << missingChannels << std::endl;
00713     checkForPeriod( condSince, condUntil, missingChannels, false );
00714     condUntil = condSince;
00715     condSince = condUntil - dTime;
00716   }
00717 
00718   if ( dumpAtStart ) dumpSnapshot( coralTime( procSince ) );
00719 
00720   copyHVData();
00721 
00722   if ( dumpAtEnd   ) dumpSnapshot( coralTime( lastFound ) );
00723 
00724   return;
00725 }
00726 
00727 
00728 int DTHVStatusHandler::recoverSnapshot() {
00729   int missingChannels = 0;
00730   std::map<int,int>::const_iterator layIter = layerMap.begin();
00731   std::map<int,int>::const_iterator layIend = layerMap.end();
00732   std::cout << "retrieve snapshot table..." << std::endl;
00733   coral::ITable& hvssTable =
00734          buff_session.nominalSchema().tableHandle( "HVSNAPSHOT" );
00735   std::auto_ptr<coral::IQuery> hvssQuery( hvssTable.newQuery() );
00736   hvssQuery->addToOutputList( "TIME" );
00737   hvssQuery->addToOutputList( "WHEEL" );
00738   hvssQuery->addToOutputList( "STATION" );
00739   hvssQuery->addToOutputList( "SECTOR" );
00740   hvssQuery->addToOutputList( "SUPERLAYER" );
00741   hvssQuery->addToOutputList( "LAYER" );
00742   hvssQuery->addToOutputList( "CHAN" );
00743   hvssQuery->addToOutputList( "TYPE" );
00744   hvssQuery->addToOutputList( "VALUE" );
00745   coral::ICursor& hvssCursor = hvssQuery->execute();
00746   while ( hvssCursor.next() ) {
00747     coral::TimeStamp time =
00748            hvssCursor.currentRow()["TIME"].data<coral::TimeStamp>();
00749     int     whe = hvssCursor.currentRow()["WHEEL"     ].data<int>();
00750     int     sta = hvssCursor.currentRow()["STATION"   ].data<int>();
00751     int     sec = hvssCursor.currentRow()["SECTOR"    ].data<int>();
00752     int     qua = hvssCursor.currentRow()["SUPERLAYER"].data<int>();
00753     int     lay = hvssCursor.currentRow()["LAYER"     ].data<int>();
00754     int     l_p = hvssCursor.currentRow()["CHAN"      ].data<int>();
00755     int     mty = hvssCursor.currentRow()["TYPE"      ].data<int>();
00756     float value = hvssCursor.currentRow()["VALUE"     ].data<float>();
00757     if ( mty > 2 ) continue;
00758     DTWireId wireId( whe, sta, sec, qua, lay, 10 + l_p );
00759     layIter = layerMap.find( wireId.rawId() );
00760     if ( layIter == layIend ) {
00761       continue;
00762     }
00763     int dpId = ( layIter->second * 10 ) + mty;
00764     snapshotValues.insert( std::pair<int,timedMeasurement>( 
00765                                    dpId, timedMeasurement( 
00766                                    time.total_nanoseconds(), value ) ) );
00767     missingChannels++;
00768   }
00769   return missingChannels;
00770 }
00771 
00772 
00773 cond::Time_t DTHVStatusHandler::recoverLastTime() {
00774   long long int lastTime = 0LL;
00775   long long int chanTime = 0LL;
00776   std::map<int,timedMeasurement>::iterator mapIter = snapshotValues.begin();
00777   std::map<int,timedMeasurement>::iterator mapIend = snapshotValues.end();
00778   while ( mapIter != mapIend ) {
00779     const std::pair<int,timedMeasurement>& entry = *mapIter++;
00780     chanTime = entry.second.first;
00781     if ( lastTime < chanTime ) lastTime = chanTime;
00782   }
00783   return condTime( lastTime );
00784 /*
00785   coral::ITable& infoTable =
00786          buff_session.nominalSchema().tableHandle( "LOG" );
00787   std::auto_ptr<coral::IQuery> infoQuery( infoTable.newQuery() );
00788   infoQuery->addToOutputList( "SNAPSHOT" );
00789   coral::ICursor& infoCursor = infoQuery->execute();
00790   coral::TimeStamp time;
00791   while ( infoCursor.next() ) {
00792     time = infoCursor.currentRow()["SNAPSHOT"].data<coral::TimeStamp>();
00793   }
00794   return condTime( time );
00795 */
00796 }
00797 
00798 
00799 void DTHVStatusHandler::dumpSnapshot( const coral::TimeStamp& time ) {
00800 
00801   std::cout << "dump snapshot to buffer db..." << std::endl;
00802   std::string emptyCondition( "" );
00803   coral::AttributeList emptyBindVariableList;
00804   std::map<int,int>::const_iterator mapIter = aliasMap.begin();
00805   std::map<int,int>::const_iterator mapIend = aliasMap.end();
00806   coral::ITable& hvssTable =
00807          buff_session.nominalSchema().tableHandle( "HVSNAPSHOT" );
00808   coral::ITableDataEditor& hvssEditor( hvssTable.dataEditor() );
00809   long nRows = hvssEditor.deleteRows( emptyCondition, emptyBindVariableList );
00810   std::cout << nRows << " rows deleted" << std::endl;
00811 
00812   coral::AttributeList newMeas;
00813   newMeas.extend( "TIME",       typeid(coral::TimeStamp) );
00814   newMeas.extend( "WHEEL",      typeid(int) );
00815   newMeas.extend( "STATION",    typeid(int) );
00816   newMeas.extend( "SECTOR",     typeid(int) );
00817   newMeas.extend( "SUPERLAYER", typeid(int) );
00818   newMeas.extend( "LAYER",      typeid(int) );
00819   newMeas.extend( "CHAN",       typeid(int) );
00820   newMeas.extend( "TYPE",       typeid(int) );
00821   newMeas.extend( "VALUE",      typeid(float) );
00822 
00823   nRows = 0;
00824   std::map<int,timedMeasurement>::const_iterator ssvIter =
00825                                   snapshotValues.begin();
00826   std::map<int,timedMeasurement>::const_iterator ssvIend =
00827                                   snapshotValues.end();
00828   while ( ssvIter != ssvIend ) {
00829     const std::pair<int,timedMeasurement>& entry = *ssvIter++;
00830     int dpty = entry.first;
00831     int dpId = dpty / 10;
00832     int type = dpty % 10;
00833     mapIter = aliasMap.find( dpId );
00834     if ( mapIter == mapIend ) continue;
00835     DTWireId chlId( mapIter->second );
00836     const timedMeasurement& tMeas = entry.second;
00837     long long int newTime = tMeas.first;
00838     newMeas["TIME"      ].data<coral::TimeStamp>() =
00839                                coral::TimeStamp( newTime );
00840     newMeas["WHEEL"     ].data<int>() = chlId.wheel     ();
00841     newMeas["STATION"   ].data<int>() = chlId.station   ();
00842     newMeas["SECTOR"    ].data<int>() = chlId.sector    ();
00843     newMeas["SUPERLAYER"].data<int>() = chlId.superLayer();
00844     newMeas["LAYER"     ].data<int>() = chlId.layer     ();
00845     newMeas["CHAN"      ].data<int>() = chlId.wire      () - 10;
00846     newMeas["TYPE"      ].data<int>() = type;
00847     newMeas["VALUE"     ].data<float>() = tMeas.second;
00848     hvssEditor.insertRow( newMeas );
00849     nRows++;
00850   }
00851   std::cout << nRows << " rows updated" << std::endl;
00852 
00853   std::cout << "create logging info..." << std::endl;
00854   if ( buff_session.nominalSchema().existsTable( "LOG" ) )
00855        buff_session.nominalSchema().  dropTable( "LOG" );
00856   coral::TableDescription infoDesc;
00857   infoDesc.setName( "LOG" );
00858   infoDesc.insertColumn( "EXECTIME",
00859                          coral::AttributeSpecification::typeNameForId( 
00860                          typeid(coral::TimeStamp) ) );
00861   infoDesc.insertColumn( "SNAPSHOT",
00862                          coral::AttributeSpecification::typeNameForId( 
00863                          typeid(coral::TimeStamp) ) );
00864   buff_session.nominalSchema().createTable( infoDesc );
00865   coral::AttributeList newInfo;
00866   newInfo.extend( "EXECTIME", typeid(coral::TimeStamp) );
00867   newInfo.extend( "SNAPSHOT", typeid(coral::TimeStamp) );
00868   newInfo["EXECTIME"].data<coral::TimeStamp>() = coral::TimeStamp::now();
00869   newInfo["SNAPSHOT"].data<coral::TimeStamp>() = time;
00870   coral::ITable& infoTable = 
00871     buff_session.nominalSchema().tableHandle( "LOG" );
00872   infoTable.dataEditor().insertRow( newInfo );
00873 
00874   return;
00875 
00876 }
00877 
00878 
00879 int DTHVStatusHandler::checkForPeriod( cond::Time_t condSince,
00880                                        cond::Time_t condUntil,
00881                                        int& missingChannels,
00882                                        bool copyOffline ) {
00883 
00884   std::map<int,timedMeasurement>::iterator mapIter = snapshotValues.begin();
00885   std::map<int,timedMeasurement>::iterator mapIend = snapshotValues.end();
00886 
00887   std::map<long long int,channelValue> periodBuffer;
00888 
00889   coral::ITable& fwccTable =
00890     omds_session.nominalSchema().tableHandle( "FWCAENCHANNEL" );
00891   std::auto_ptr<coral::IQuery> fwccQuery( fwccTable.newQuery() );
00892   fwccQuery->addToOutputList( "DPID"          );
00893   fwccQuery->addToOutputList( "CHANGE_DATE"   );
00894   fwccQuery->addToOutputList( "ACTUAL_VMON"   );
00895   fwccQuery->addToOutputList( "ACTUAL_IMON"   );
00896   fwccQuery->addToOutputList( "ACTUAL_ISON"   );
00897   fwccQuery->addToOutputList( "ACTUAL_STATUS" );
00898   fwccQuery->addToOutputList( "ACTUAL_OVC"    );
00899   coral::AttributeList timeBindVariableList;
00900   timeBindVariableList.extend( "since", typeid(coral::TimeStamp) );
00901   timeBindVariableList.extend( "until", typeid(coral::TimeStamp) );
00902   coral::TimeStamp coralSince = coralTime( condSince );
00903   coral::TimeStamp coralUntil = coralTime( condUntil );
00904   std::cout << "look for data since "            
00905             << coralSince.year(  ) << " "
00906             << coralSince.month( ) << " "
00907             << coralSince.day(   ) << " "
00908             << coralSince.hour(  ) << ":"
00909             << coralSince.minute() << ":"
00910             << coralSince.second() << " until "
00911             << coralUntil.year(  ) << " "
00912             << coralUntil.month( ) << " "
00913             << coralUntil.day(   ) << " "
00914             << coralUntil.hour(  ) << ":"
00915             << coralUntil.minute() << ":"
00916             << coralUntil.second() << std::endl;
00917   timeBindVariableList["since"].data<coral::TimeStamp>() =
00918                                      coralTime( condSince );
00919   timeBindVariableList["until"].data<coral::TimeStamp>() =
00920                                      coralTime( condUntil );
00921   fwccQuery->setCondition( "CHANGE_DATE>:since and CHANGE_DATE<:until",
00922                            timeBindVariableList );
00923   fwccQuery->addToOrderList( "CHANGE_DATE" );
00924   coral::ICursor& fwccCursor = fwccQuery->execute();
00925   int nrows = 0;
00926   while ( fwccCursor.next() ) {
00927     nrows++;
00928     const coral::Attribute& dp     = fwccCursor.currentRow()["DPID"         ];
00929     const coral::Attribute& vmon   = fwccCursor.currentRow()["ACTUAL_VMON"  ];
00930     const coral::Attribute& imon   = fwccCursor.currentRow()["ACTUAL_IMON"  ];
00931     coral::TimeStamp changeTime =
00932            fwccCursor.currentRow()["CHANGE_DATE"].data<coral::TimeStamp>();
00933     long long int cTimeValue = changeTime.total_nanoseconds();
00934     if ( !copyOffline ) cTimeValue = -cTimeValue;
00935     if ( dp.isNull() ) {
00936       std::cout << "------- " << nrows << std::endl;
00937       continue;
00938     }
00939     int dpId = 10 * static_cast<int>( 0.01 +
00940            fwccCursor.currentRow()["DPID"].data<float>() );
00941     if ( !( vmon.isNull() ) ) {
00942       while ( periodBuffer.find( cTimeValue ) !=
00943               periodBuffer.end() ) cTimeValue++;
00944       int chan = dpId + 1;
00945       periodBuffer.insert( std::pair<long long int,channelValue> (
00946                                      cTimeValue, channelValue( chan,
00947                                                  vmon.data<float>() ) ) );
00948     }
00949     if ( !( imon.isNull() ) ) {
00950       while ( periodBuffer.find( cTimeValue ) !=
00951               periodBuffer.end() ) cTimeValue++;
00952       int chan = dpId + 2;
00953       periodBuffer.insert( std::pair<long long int,channelValue> (
00954                                      cTimeValue, channelValue( chan,
00955                                                  imon.data<float>() ) ) );
00956     }
00957   }
00958 
00959   long long int dTime = minTime;
00960   dTime <<= 32;
00961   std::cout << "data found in period: " << periodBuffer.size() << std::endl;
00962   std::map<long long int,channelValue>::const_iterator bufIter =
00963                                                        periodBuffer.begin();
00964   std::map<long long int,channelValue>::const_iterator bufIend =
00965                                                        periodBuffer.end();
00966 
00967   bool changedStatus = false;
00968   while ( bufIter != bufIend ) {
00969     const std::pair<long long int,channelValue>& entry = *bufIter++;
00970     long long int mTime = entry.first;
00971     if ( !copyOffline ) mTime = -mTime;
00972     channelValue cValue = entry.second;
00973     int   chan = cValue.first;
00974     float cont = cValue.second;
00975     mapIter = snapshotValues.find( chan );
00976     if ( ( mapIter != mapIend ) &&
00977          ( mapIter->second.first < mTime ) ) {
00978       nextFound = condTime( mTime );
00979       if ( changedStatus ) {
00980         if ( nextFound > timeLimit ) {
00981           DTHVStatus* hvStatus = offlineList();
00982           std::cout << "new payload "
00983                     << hvStatus->end() - hvStatus->begin() << std::endl;
00984           tmpContainer.push_back( std::make_pair( hvStatus, lastFound ) );
00985           changedStatus = false;
00986           if ( !( --maxPayload ) ) {
00987             procUntil = lastFound;
00988             std::cout << "max payload number reached" << std::endl;
00989             break;
00990           }
00991         }
00992       }
00993       if ( copyOffline && !changedStatus &&
00994            checkStatusChange( chan, mapIter->second.second, cont ) ) {
00995         timeLimit = nextFound + dTime;
00996         changedStatus = true;
00997       }
00998       mapIter->second = timedMeasurement( lastStamp = mTime, cont );
00999       lastFound = nextFound;
01000       missingChannels--;
01001     }
01002   }
01003 
01004   std::cout << nrows << std::endl;
01005   return nrows;
01006 
01007 }
01008 
01009 
01010 void DTHVStatusHandler::copyHVData() {
01011   long long int dTime = fwdTime;
01012   dTime <<= 32;
01013 
01014   cond::Time_t condSince = procSince;
01015   cond::Time_t condUntil = condSince + dTime;
01016   if ( condUntil > procUntil ) condUntil = procUntil;
01017 
01018   int dum = 0;
01019   lastStatus = 0;
01020   while ( condSince < condUntil ) {
01021     checkForPeriod( condSince, condUntil, dum, true );
01022     condSince = condUntil;
01023     condUntil = condSince + dTime;
01024     if ( condUntil > procUntil ) condUntil = procUntil;
01025   }
01026   std::cout << "call filterData " << std::endl;
01027   filterData();
01028   std::cout << "filterData return "
01029             << switchOff  << " "
01030             << lastFound  << " "
01031             << maxPayload << " "
01032             << m_to_transfer.size() << std::endl;
01033   if ( switchOff || ( ( lastFound != 0 ) && ( maxPayload > 0 ) ) ) {
01034     DTHVStatus* hvStatus = offlineList();
01035     m_to_transfer.push_back( std::make_pair( hvStatus, lastFound ) );
01036   }
01037 
01038   return;
01039 }
01040 
01041 
01042 DTHVStatus* DTHVStatusHandler::offlineList() {
01043   DTHVStatus* hv = new DTHVStatus( dataTag );
01044   int type;
01045   float valueA = 0.0;
01046   float valueL = 0.0;
01047   float valueR = 0.0;
01048   float valueS = 0.0;
01049   float valueC = 0.0;
01050   std::map<int,int>::const_iterator layerIter = layerMap.begin();
01051   std::map<int,int>::const_iterator layerIend = layerMap.end();
01052   while ( layerIter != layerIend ) {
01053     const std::pair<int,int>& chanEntry = *layerIter++;
01054     int rawId = chanEntry.first;
01055     DTWireId chlId( rawId );
01056     int whe = chlId.wheel     ();
01057     int sta = chlId.station   ();
01058     int sec = chlId.sector    ();
01059     int qua = chlId.superLayer();
01060     int lay = chlId.layer     ();
01061     int l_p = chlId.wire();
01062     if ( l_p != 10 ) continue;
01063     for ( type = 1; type <= 2; type++ ) {
01064       getLayerValues( rawId, type, valueL, valueR, valueS, valueC );
01065       for ( l_p = 0; l_p <= 1; l_p++ ) {
01066         int rPart = layerId( rawId, l_p ).rawId();
01067         switch ( l_p ) {
01068         case 0:
01069           valueA = valueL;
01070           break;
01071         case 1:
01072           valueA = valueR;
01073           break;
01074         default:
01075           break;
01076         }
01077 //  std::cout << "layer values: " << type << " " << valueA << " "
01078 //                                               << valueS << " "
01079 //                                               << valueC << std::endl;
01080         DTHVAbstractCheck::flag flag = hvChecker->checkCurrentStatus(
01081                                                   rPart, type,
01082                                                   valueA, valueC, valueS,
01083                                                   snapshotValues,
01084                                                   aliasMap, layerMap );
01085         if ( !flag.a && !flag.c && !flag.s ) continue;
01086         setChannelFlag( hv, whe, sta, sec, qua, lay, l_p, flag );
01087         std::map< int,std::vector<int>* >::const_iterator m_iter =
01088                                            channelSplit.find( rPart );
01089         std::map< int,std::vector<int>* >::const_iterator m_iend =
01090                                            channelSplit.end();
01091         if ( m_iter != m_iend ) {
01092           std::vector<int>* cList = m_iter->second;
01093           std::vector<int>::const_iterator l_iter = cList->begin();
01094           std::vector<int>::const_iterator l_iend = cList->end();
01095           while ( l_iter != l_iend ) {
01096             DTWireId chlId( *l_iter++ );
01097             int wh2 = chlId.wheel     ();
01098             int st2 = chlId.station   ();
01099             int se2 = chlId.sector    ();
01100             int qu2 = chlId.superLayer();
01101             int la2 = chlId.layer     ();
01102             int lp2 = chlId.wire() - 10;
01103 //          std::cout << "duplicate "
01104 //                      << whe << " " << sta << " " << sec << " "
01105 //                      << qua << " " << lay << " " << l_p << " ---> "
01106 //                      << wh2 << " " << st2 << " " << se2 << " "
01107 //                      << qu2 << " " << la2 << " " << lp2 << std::endl;
01108             setChannelFlag( hv, wh2, st2, se2, qu2, la2, lp2, flag );
01109           }
01110         }
01111       }
01112     }
01113   }
01114   return hv;
01115 }
01116 
01117 
01118 void DTHVStatusHandler::getLayerValues( int rawId, int type,
01119                                         float& valueL, float& valueR,
01120                                         float& valueS, float& valueC ) {
01121   valueL =
01122   valueR =
01123   valueS =
01124   valueC = 0.0;
01125   DTWireId chlId( rawId );
01126   std::map<int,timedMeasurement>::const_iterator snapIter =
01127                                                  snapshotValues.begin();
01128   std::map<int,timedMeasurement>::const_iterator snapIend =
01129                                                  snapshotValues.end();
01130   int rawL = layerId( rawId, 0 ).rawId();
01131   int rawR = layerId( rawId, 1 ).rawId();
01132   int rawS = layerId( rawId, 2 ).rawId();
01133   int rawC = layerId( rawId, 3 ).rawId();
01134   std::map<int,int>::const_iterator layerIter;
01135   std::map<int,int>::const_iterator layerIend = layerMap.end();
01136   if ( ( layerIter = layerMap.find( rawL ) ) != layerIend ) {
01137     const std::pair<int,int>& layerEntry = *layerIter;
01138     int dpId = layerEntry.second;
01139     snapIter = snapshotValues.find( ( dpId * 10 ) + type );
01140     if ( snapIter != snapIend ) {
01141       const std::pair<int,timedMeasurement>& snapEntry = *snapIter;
01142       valueL = snapEntry.second.second;
01143     }
01144     else std::cout << "snapR not found" << std::endl;
01145   }
01146   else std::cout << "rawR not found" << std::endl;
01147   if ( ( layerIter = layerMap.find( rawR ) ) != layerIend ) {
01148     const std::pair<int,int>& layerEntry = *layerIter;
01149     int dpId = layerEntry.second;
01150     snapIter = snapshotValues.find( ( dpId * 10 ) + type );
01151     if ( snapIter != snapIend ) {
01152       const std::pair<int,timedMeasurement>& snapEntry = *snapIter;
01153       valueR = snapEntry.second.second;
01154     }
01155     else std::cout << "snapL not found" << std::endl;
01156   }
01157   else std::cout << "rawL not found" << std::endl;
01158   if ( ( layerIter = layerMap.find( rawS ) ) != layerIend ) {
01159     const std::pair<int,int>& layerEntry = *layerIter;
01160     int dpId = layerEntry.second;
01161     snapIter = snapshotValues.find( ( dpId * 10 ) + type );
01162     if ( snapIter != snapIend ) {
01163       const std::pair<int,timedMeasurement>& snapEntry = *snapIter;
01164       valueS = snapEntry.second.second;
01165     }
01166     else std::cout << "snapS not found" << std::endl;
01167   }
01168   else std::cout << "rawS not found" << std::endl;
01169   if ( ( layerIter = layerMap.find( rawC ) ) != layerIend ) {
01170     const std::pair<int,int>& layerEntry = *layerIter;
01171     int dpId = layerEntry.second;
01172     snapIter = snapshotValues.find( ( dpId * 10 ) + type );
01173     if ( snapIter != snapIend ) {
01174       const std::pair<int,timedMeasurement>& snapEntry = *snapIter;
01175       valueC = snapEntry.second.second;
01176     }
01177     else std::cout << "snapC not found" << std::endl;
01178   }
01179   else std::cout << "rawC not found" << std::endl;
01180 //  std::cout << "layer values... " << type << " " << valueL << " "
01181 //                                                 << valueR << " "
01182 //                                                 << valueS << " "
01183 //                                                 << valueC << std::endl;
01184   return;
01185 }
01186 
01187 
01188 void DTHVStatusHandler::setChannelFlag( DTHVStatus* hv,
01189                                         int whe, int sta, int sec,
01190                                         int qua, int lay, int l_p,
01191                                         const DTHVAbstractCheck::flag& flag ) {
01192   int fCell = 0;
01193   int lCell = 99;
01194   int flagA = 0;
01195   int flagC = 0;
01196   int flagS = 0;
01197   int searchStatus = hv->get( whe, sta, sec, qua, lay, l_p,
01198                               fCell, lCell, flagA, flagC, flagS );
01199   if ( searchStatus ) {
01200     DTWireId wireId( whe, sta, sec, qua, lay, 10 + l_p );
01201     std::map<int,int>::const_iterator splitIter =
01202                                       laySplit.find( wireId.rawId() );
01203     std::map<int,int>::const_iterator splitIend =
01204                                       laySplit.end();
01205     if ( splitIter != splitIend ) {
01206       int code = splitIter->second;
01207       fCell = code / 10000;
01208       lCell = code % 10000;
01209     }
01210   }
01211   flagA |= flag.a;
01212   flagC |= flag.c;
01213   flagS |= flag.s;
01214   hv->set( whe, sta, sec, qua, lay, l_p,
01215            fCell, lCell, flagA, flagC, flagS );
01216   return;
01217 }
01218 
01219 
01220 int DTHVStatusHandler::checkStatusChange( int chan,
01221                                           float oldValue, float newValue ) {
01222   int dpId = chan / 10;
01223   int type = chan % 10;
01224   std::map<int,int>::const_iterator aliasIter = aliasMap.find( dpId );
01225   std::map<int,int>::const_iterator aliasIend = aliasMap.end();
01226   if ( aliasIter == aliasIend ) return false;
01227   int rawId = aliasIter->second;
01228   DTWireId chlId( rawId );
01229   int l_p = chlId.wire();
01230   float valueL = 0.0;
01231   float valueR = 0.0;
01232   float valueS = 0.0;
01233   float valueC = 0.0;
01234   getLayerValues( rawId, type, valueL, valueR, valueS, valueC );
01235 //  std::cout << "layer values: " << type << " " << valueL << " "
01236 //                                               << valueR << " "
01237 //                                               << valueS << " "
01238 //                                               << valueC << std::endl;
01239   DTHVAbstractCheck::flag
01240       oldStatusL = hvChecker->checkCurrentStatus( layerId( rawId, 0 ).rawId(),
01241                                                   type,
01242                                                   valueL, valueC, valueS,
01243                                                   snapshotValues,
01244                                                   aliasMap, layerMap );
01245   DTHVAbstractCheck::flag
01246       oldStatusR = hvChecker->checkCurrentStatus( layerId( rawId, 1 ).rawId(),
01247                                                   type,
01248                                                   valueR, valueC, valueS,
01249                                                   snapshotValues,
01250                                                   aliasMap, layerMap );
01251   switch ( l_p ) {
01252   case 10:
01253     if ( valueL != oldValue ) std::cout << "*** INCONSISTENT DATA!!!!! "
01254                                         << type << " " << l_p << " "
01255                                         << oldValue << " " << valueL << " "
01256                                         << std::endl;
01257     valueL = newValue;
01258     break;
01259   case 11:
01260     if ( valueR != oldValue ) std::cout << "*** INCONSISTENT DATA!!!!! "
01261                                         << type << " " << l_p << " "
01262                                         << oldValue << " " << valueR << " "
01263                                         << std::endl;
01264     valueR = newValue;
01265     break;
01266   case 12:
01267     if ( valueS != oldValue ) std::cout << "*** INCONSISTENT DATA!!!!! "
01268                                         << type << " " << l_p << " "
01269                                         << oldValue << " " << valueS << " "
01270                                         << std::endl;
01271     valueS = newValue;
01272     break;
01273   case 13:
01274     if ( valueC != oldValue ) std::cout << "*** INCONSISTENT DATA!!!!! "
01275                                         << type << " " << l_p << " "
01276                                         << oldValue << " " << valueC << " "
01277                                         << std::endl;
01278     valueC = newValue;
01279     break;
01280   default:
01281     break;
01282   }
01283   DTHVAbstractCheck::flag
01284       newStatusL = hvChecker->checkCurrentStatus( layerId( rawId, 0 ).rawId(),
01285                                                   type,
01286                                                   valueL, valueC, valueS,
01287                                                   snapshotValues,
01288                                                   aliasMap, layerMap );
01289   DTHVAbstractCheck::flag
01290       newStatusR = hvChecker->checkCurrentStatus( layerId( rawId, 1 ).rawId(),
01291                                                   type,
01292                                                   valueR, valueC, valueS,
01293                                                   snapshotValues,
01294                                                   aliasMap, layerMap );
01295 
01296   if ( DTHVAbstractCheck::compare( newStatusL, oldStatusL ) &&
01297        DTHVAbstractCheck::compare( newStatusR, oldStatusR ) ) return 0;
01298   std::cout << "changed status: " << chan << " from "
01299             << oldValue << " to " << newValue << std::endl;
01300   return 1;
01301 }
01302 
01303 
01304 void DTHVStatusHandler::filterData() {
01305 
01306   int maxTime = 100;
01307   int maxTtot = 600;
01308   int minDiff = 88;
01309 
01310   int iTime = 0;
01311   int pTime = 0;
01312   int nTime = 0;
01313   int iSize;
01314   int pSize;
01315   int nSize;
01316 
01317   std::vector< std::pair<DTHVStatus*, cond::Time_t> >::const_iterator iter =
01318                                                        tmpContainer.begin();
01319   std::vector< std::pair<DTHVStatus*, cond::Time_t> >::const_iterator iend =
01320                                                        tmpContainer.end();
01321   std::vector< std::pair<DTHVStatus*, cond::Time_t> >::const_iterator prev;
01322   std::vector< std::pair<DTHVStatus*, cond::Time_t> >::const_iterator next;
01323 
01324   while ( iter != iend ) {
01325     switchOff = false;
01326     next = iter;
01327     prev = next++;
01328     if ( next == iend ) next = prev;
01329     const DTHVStatus* iPtr = iter->first;
01330     const DTHVStatus* pPtr = prev->first;
01331     const DTHVStatus* nPtr = next->first;
01332     iSize = std::distance( iPtr->begin(), iPtr->end() );
01333     pSize = std::distance( pPtr->begin(), pPtr->end() );
01334     nSize = std::distance( nPtr->begin(), nPtr->end() );
01335     int dtot = nSize - pSize;
01336     prev = next;
01337     while ( ++next != iend ) {
01338       pPtr = prev->first;
01339       nPtr = next->first;
01340       pSize = std::distance( pPtr->begin(), pPtr->end() );
01341       nSize = std::distance( nPtr->begin(), nPtr->end() );
01342       int diff = nSize - pSize;
01343       iTime = static_cast<int>( ( iter->second >> 32 ) & 0xffffffff );
01344       pTime = static_cast<int>( ( prev->second >> 32 ) & 0xffffffff );
01345       nTime = static_cast<int>( ( next->second >> 32 ) & 0xffffffff );
01346       if ( ( nTime - pTime ) > maxTime ) break;
01347       if ( ( nTime - iTime ) > maxTtot ) break;
01348       if ( ( dtot * diff ) < 0 ) break;
01349       prev = next;
01350     }
01351     pPtr = prev->first;
01352     iSize = std::distance( iPtr->begin(), iPtr->end() );
01353     pSize = std::distance( pPtr->begin(), pPtr->end() );
01354     dtot = pSize - iSize;
01355     int dist = pTime - iTime;
01356     if ( ( dtot < -minDiff ) &&
01357          ( dist <  maxTtot ) ) {
01358       std::cout << "  ******** SWITCH ON "
01359                 << std::distance( iter, prev ) << " "
01360                 << iTime << " " << pTime << " "
01361                 << iSize << " " << pSize << std::endl;
01362       m_to_transfer.push_back( std::make_pair( prev->first, prev->second ) );
01363       while ( iter != prev ) delete ( iter++->first );
01364     }
01365     if ( ( dtot >  minDiff ) &&
01366          ( dist <  maxTtot ) ) {
01367       std::cout << "  ******** SWITCH OFF "
01368                 << std::distance( iter, prev ) << " "
01369                 << iTime << " " << pTime << " "
01370                 << iSize << " " << pSize << std::endl;
01371       m_to_transfer.push_back( std::make_pair( prev->first, iter->second ) );
01372       switchOff = true;
01373       while ( iter != prev ) delete ( iter++->first );
01374     }
01375     if ( ( ( dtot >= -minDiff ) && ( dtot <= minDiff ) ) ||
01376          ( dist >= maxTtot ) ) {
01377       while ( iter != next ) {
01378         const std::pair<DTHVStatus*, cond::Time_t>& entry = *iter++;
01379         m_to_transfer.push_back( std::make_pair( entry.first, entry.second ) );
01380       }
01381     }
01382     iter = next;
01383   }
01384 
01385 }
01386 
01387 
01388 DTWireId DTHVStatusHandler::layerId( int rawId, int l_p ) {
01389   DTWireId chlId( rawId );
01390   int whe = chlId.wheel     ();
01391   int sta = chlId.station   ();
01392   int sec = chlId.sector    ();
01393   int qua = chlId.superLayer();
01394   int lay = chlId.layer     ();
01395   DTWireId chl( whe, sta, sec, qua, lay, 10 + l_p );
01396   return chl;
01397 }
01398 
01399 
01400 coral::TimeStamp DTHVStatusHandler::coralTime( const  cond::Time_t&    time ) {
01401   long long int iTime = ( ( ( ( time >> 32 ) & 0xFFFFFFFF ) * 1000000000 ) +
01402                           ( (   time         & 0xFFFFFFFF ) * 1000       ) );
01403   coral::TimeStamp cTime( iTime );
01404   return cTime;
01405 }
01406 
01407 
01408 cond::Time_t     DTHVStatusHandler::condTime(  const coral::TimeStamp& time ) {
01409   cond::Time_t cTime = ( ( time.total_nanoseconds() / 1000000000 )  << 32 ) + 
01410                        ( ( time.total_nanoseconds() % 1000000000 ) / 1000 );
01411   return cTime;
01412 }
01413 
01414 
01415 cond::Time_t     DTHVStatusHandler::condTime(  long long int           time ) {
01416   cond::Time_t cTime = ( ( time                     / 1000000000 )  << 32 ) + 
01417                        ( ( time                     % 1000000000 ) / 1000 );
01418   return cTime;
01419 }
01420 
01421