CMS 3D CMS Logo

/data/doxygen/doxygen-1.7.3/gen/CMSSW_4_2_8/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: 2011/01/27 15:36:19 $
00005  *  $Revision: 1.12 $
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 snum;
00384   int swhe;
00385   int ssec;
00386   int ssta;
00387   int squa;
00388   int slay;
00389   int sl_p;
00390   coral::ITable& csplTable =
00391     util_session.nominalSchema().tableHandle( "DT_HV_CHANNEL_SPLIT" );
00392   std::auto_ptr<coral::IQuery> csplQuery( csplTable.newQuery() );
00393   coral::AttributeList versionBindVariableList;
00394   versionBindVariableList.extend( "version", typeid(std::string) );
00395   versionBindVariableList["version"].data<std::string>() = splitVersion;
00396   csplQuery->setCondition( "VERSION=:version", versionBindVariableList );
00397   csplQuery->addToOutputList( "P_WHEEL" );
00398   csplQuery->addToOutputList( "P_SECTOR" );
00399   csplQuery->addToOutputList( "P_STATION" );
00400   csplQuery->addToOutputList( "P_SUPERLAYER" );
00401   csplQuery->addToOutputList( "P_LAYER" );
00402   csplQuery->addToOutputList( "P_PART" );
00403   csplQuery->addToOutputList( "S_NUMBER" );
00404   csplQuery->addToOutputList( "S_WHEEL" );
00405   csplQuery->addToOutputList( "S_SECTOR" );
00406   csplQuery->addToOutputList( "S_STATION" );
00407   csplQuery->addToOutputList( "S_SUPERLAYER" );
00408   csplQuery->addToOutputList( "S_LAYER" );
00409   csplQuery->addToOutputList( "S_PART" );
00410   coral::ICursor& csplCursor = csplQuery->execute();
00411   while ( csplCursor.next() ) {
00412     pwhe = csplCursor.currentRow()["P_WHEEL"     ].data<int>();
00413     psec = csplCursor.currentRow()["P_SECTOR"    ].data<int>();
00414     psta = csplCursor.currentRow()["P_STATION"   ].data<int>();
00415     pqua = csplCursor.currentRow()["P_SUPERLAYER"].data<int>();
00416     play = csplCursor.currentRow()["P_LAYER"     ].data<int>();
00417     pl_p = csplCursor.currentRow()["P_PART"      ].data<int>();
00418     snum = csplCursor.currentRow()["S_NUMBER"    ].data<int>();
00419     swhe = csplCursor.currentRow()["S_WHEEL"     ].data<int>();
00420     ssec = csplCursor.currentRow()["S_SECTOR"    ].data<int>();
00421     ssta = csplCursor.currentRow()["S_STATION"   ].data<int>();
00422     squa = csplCursor.currentRow()["S_SUPERLAYER"].data<int>();
00423     slay = csplCursor.currentRow()["S_LAYER"     ].data<int>();
00424     sl_p = csplCursor.currentRow()["S_PART"      ].data<int>();
00425     DTWireId pId( pwhe, psta, psec, pqua, play, 10 + pl_p );
00426     DTWireId sId( swhe, ssta, ssec, squa, slay, 10 + sl_p );
00427     int pRaw = pId.rawId();
00428     int sRaw = sId.rawId();
00429     std::vector<int>* splitList = 0;
00430     std::map< int,std::vector<int>* >::iterator iter =
00431                                                 channelSplit.find( pRaw );
00432     std::map< int,std::vector<int>* >::iterator iend =
00433                                                 channelSplit.end();
00434     if ( iter == iend ) {
00435       channelSplit.insert( std::pair< int,
00436                                       std::vector<int>* >( pRaw, splitList =
00437                                       new std::vector<int> ) );
00438     }
00439     else {
00440       splitList = iter->second;
00441     }
00442     splitList->push_back( sRaw );
00443   }
00444   return;
00445 }
00446 
00447 
00448 void DTHVStatusHandler::dumpHVAliases() {
00449 
00450   std::cout << "DTHVStatusHandler::dumpHVAliases - begin" << std::endl;
00451 
00452   std::cout << "create aliases description..." << std::endl;
00453   coral::TableDescription hvalDesc;
00454   hvalDesc.setName( "HVALIASES" );
00455   hvalDesc.insertColumn( "DETID",
00456                          coral::AttributeSpecification::typeNameForId( 
00457                          typeid(int) ) );
00458   hvalDesc.insertColumn(  "DPID",
00459                          coral::AttributeSpecification::typeNameForId( 
00460                          typeid(int) ) );
00461   std::cout << "create aliases table..." << std::endl;
00462   coral::ITable& hvalTable = 
00463   buff_session.nominalSchema().createTable( hvalDesc );
00464 
00465   std::cout << "open DPNAME table..." << std::endl;
00466   std::map<int,std::string> idMap;
00467   coral::ITable& dpidTable =
00468     omds_session.nominalSchema().tableHandle( "DP_NAME2ID" );
00469   std::auto_ptr<coral::IQuery> dpidQuery( dpidTable.newQuery() );
00470   dpidQuery->addToOutputList( "ID" );
00471   dpidQuery->addToOutputList( "DPNAME" );
00472   coral::ICursor& dpidCursor = dpidQuery->execute();
00473   while( dpidCursor.next() ) {
00474     const coral::AttributeList& row = dpidCursor.currentRow();
00475     int id         = static_cast<int>( 0.01 +
00476                      row["ID"    ].data<float>() );
00477     std::string dp = row["DPNAME"].data<std::string>();
00478     idMap.insert( std::pair<int,std::string>( id, dp ) );
00479   }
00480   std::cout << "DPNAME table read... " << idMap.size() << std::endl;
00481 
00482   std::cout << "open ALIASES table..." << std::endl;
00483   std::map<std::string,std::string> cnMap;
00484   coral::ITable& nameTable =
00485     omds_session.nominalSchema().tableHandle( "ALIASES" );
00486   std::auto_ptr<coral::IQuery> nameQuery( nameTable.newQuery() );
00487   nameQuery->addToOutputList( "DPE_NAME" );
00488   nameQuery->addToOutputList( "ALIAS" );
00489   coral::ICursor& nameCursor = nameQuery->execute();
00490   while( nameCursor.next() ) {
00491     const coral::AttributeList& row = nameCursor.currentRow();
00492     std::string dp = row["DPE_NAME"].data<std::string>();
00493     std::string an = row["ALIAS"   ].data<std::string>();
00494     if ( an.length() < 20 ) continue;
00495     cnMap.insert( std::pair<std::string,std::string>( dp, an ) );
00496   }
00497   std::cout << "ALIASES table read... " << cnMap.size() << std::endl;
00498 
00499   std::map<int,std::string>::const_iterator idIter = idMap.begin();
00500   std::map<int,std::string>::const_iterator idIend = idMap.end();
00501   std::string outChk( "/outputChannel" );
00502   while ( idIter != idIend ) {
00503     const std::pair<int,std::string>& ientry = *idIter++;
00504     int dpId       = ientry.first;
00505     std::string dp = ientry.second;
00506     int ldp = dp.length();
00507     if ( ldp < 20 ) continue;
00508     std::string subOut( dp.substr( ldp - 17, 17 ) );
00509     std::string subChk( subOut.substr( 0, 14 ) );
00510     if ( subChk != outChk ) continue;
00511     std::string chName( dp.substr( 0, ldp - 17 ) );
00512     chName += ".actual.OvC";
00513     int chCode = subOut.c_str()[16] - '0';
00514     std::map<std::string,std::string>::const_iterator jter =
00515                                                       cnMap.find( chName );
00516     if ( jter == cnMap.end() ) continue;
00517     const std::pair<std::string,std::string>& jentry = *jter;
00518     std::cout << dp << std::endl << chName << " " << chCode << std::endl;
00519     std::string an( jentry.second );
00520     int al = an.length();
00521     int iofw = 7 + an.find( "DT_HV_W", 0 );
00522     int iofc = 3 + an.find( "_MB", 0 );
00523     int iofs = 2 + an.find( "_S" , 0 );
00524     int iofq = 3 + an.find( "_SL", 0 );
00525     int iofl = 2 + an.find( "_L" , 0 );
00526     if ( ( iofw == al ) ||
00527          ( iofc == al ) ||
00528          ( iofs == al ) ||
00529          ( iofq == al ) ||
00530          ( iofl == al ) ) {
00531       break;
00532     }
00533     int ioew = an.find( "_", iofw );
00534     int ioec = an.find( "_", iofc );
00535     int ioes = an.find( "_", iofs );
00536     int ioeq = an.find( "_", iofq );
00537     int ioel = an.find( "_", iofl );
00538     std::string swhe( an.substr( iofw, ioew - iofw ) );
00539     const char* cwhe = swhe.c_str();
00540     int whe = cwhe[1] - '0';
00541     if ( *cwhe != 'P' ) whe = -whe;
00542 
00543     std::string scha( an.substr( iofc, ioec - iofc ) );
00544     const char* ccha = scha.c_str();
00545     int cha = *ccha - '0';
00546 
00547     std::string ssec( an.substr( iofs, ioes - iofs ) );
00548     const char* csec = ssec.c_str();
00549     int sec = ( ( *csec - '0' ) * 10 ) + ( csec[1] - '0' );
00550     if ( ( csec[2] == 'R' ) && ( sec == 10 ) ) sec = 14;
00551     if ( ( csec[2] == 'L' ) && ( sec ==  4 ) ) sec = 13;
00552 
00553     std::string squa( an.substr( iofq, ioeq - iofq ) );
00554     const char* cqua = squa.c_str();
00555     int qua = *cqua - '0';
00556 
00557     std::string slay( an.substr( iofl, ioel - iofl ) );
00558     const char* clay = slay.c_str();
00559     int lay = *clay - '0';
00560 
00561     DTWireId wireId( whe, cha, sec, qua, lay, 10 + chCode );
00562     int chId = wireId.rawId();
00563     coral::AttributeList newChan;
00564     newChan.extend( "DETID", typeid(int) );
00565     newChan.extend(  "DPID", typeid(int) );
00566     newChan["DETID"].data<int>() = chId;
00567     newChan[ "DPID"].data<int>() = dpId;
00568     hvalTable.dataEditor().insertRow( newChan );
00569     aliasMap.insert( std::pair<int,int>( dpId, chId ) );
00570     layerMap.insert( std::pair<int,int>( chId, dpId ) );
00571   }
00572 
00573   std::cout << "DTHVStatusHandler::dumpHVAliases - end" << std::endl;
00574   return;
00575 }
00576 
00577 
00578 void DTHVStatusHandler::createSnapshot() {
00579   std::cout << "create snapshot description..." << std::endl;
00580   coral::TableDescription hvssDesc;
00581   hvssDesc.setName( "HVSNAPSHOT" );
00582   hvssDesc.insertColumn( "TIME",
00583                          coral::AttributeSpecification::typeNameForId( 
00584                          typeid(coral::TimeStamp) ) );
00585   hvssDesc.insertColumn( "WHEEL",
00586                          coral::AttributeSpecification::typeNameForId( 
00587                          typeid(int) ) );
00588   hvssDesc.insertColumn( "STATION",
00589                          coral::AttributeSpecification::typeNameForId( 
00590                          typeid(int) ) );
00591   hvssDesc.insertColumn( "SECTOR",
00592                          coral::AttributeSpecification::typeNameForId( 
00593                          typeid(int) ) );
00594   hvssDesc.insertColumn( "SUPERLAYER",
00595                          coral::AttributeSpecification::typeNameForId( 
00596                          typeid(int) ) );
00597   hvssDesc.insertColumn( "LAYER",
00598                          coral::AttributeSpecification::typeNameForId( 
00599                          typeid(int) ) );
00600   hvssDesc.insertColumn( "CHAN",
00601                          coral::AttributeSpecification::typeNameForId( 
00602                          typeid(int) ) );
00603   hvssDesc.insertColumn( "TYPE",
00604                          coral::AttributeSpecification::typeNameForId( 
00605                          typeid(int) ) );
00606   hvssDesc.insertColumn( "VALUE",
00607                          coral::AttributeSpecification::typeNameForId( 
00608                          typeid(float) ) );
00609   std::cout << "create snapshot table..." << std::endl;
00610   buff_session.nominalSchema().createTable( hvssDesc );
00611   coral::ITable& bufferTable = 
00612     buff_session.nominalSchema().tableHandle( "HVSNAPSHOT" );
00613   coral::AttributeList newMeas;
00614   newMeas.extend( "TIME",       typeid(coral::TimeStamp) );
00615   newMeas.extend( "WHEEL",      typeid(int) );
00616   newMeas.extend( "STATION",    typeid(int) );
00617   newMeas.extend( "SECTOR",     typeid(int) );
00618   newMeas.extend( "SUPERLAYER", typeid(int) );
00619   newMeas.extend( "LAYER",      typeid(int) );
00620   newMeas.extend( "CHAN",       typeid(int) );
00621   newMeas.extend( "TYPE",       typeid(int) );
00622   newMeas.extend( "VALUE",      typeid(float) );
00623 
00624   long long int zeroTime = 0LL;
00625   newMeas["TIME"     ].data<coral::TimeStamp>() =
00626                             coral::TimeStamp( zeroTime );
00627   newMeas["VALUE"    ].data<float>() = -999999.0;
00628 
00629   std::map<int,int>::const_iterator iter = aliasMap.begin();
00630   std::map<int,int>::const_iterator iend = aliasMap.end();
00631   while ( iter != iend ) {
00632     const std::pair<int,int>& entry= *iter++;
00633     int detId = entry.second;
00634     DTWireId chlId( detId );
00635     newMeas["WHEEL"     ].data<int>() = chlId.wheel     ();
00636     newMeas["STATION"   ].data<int>() = chlId.station   ();
00637     newMeas["SECTOR"    ].data<int>() = chlId.sector    ();
00638     newMeas["SUPERLAYER"].data<int>() = chlId.superLayer();
00639     newMeas["LAYER"     ].data<int>() = chlId.layer     ();
00640     newMeas["CHAN"      ].data<int>() = chlId.wire      () - 10;
00641     int itype;
00642     for ( itype = 1; itype <= 2; itype++ ) {
00643       newMeas["TYPE"      ].data<int>() = itype;
00644       bufferTable.dataEditor().insertRow( newMeas );
00645     }
00646   }
00647 
00648   std::cout << "create logging info..." << std::endl;
00649   if ( buff_session.nominalSchema().existsTable( "LOG" ) )
00650        buff_session.nominalSchema().  dropTable( "LOG" );
00651   coral::TableDescription infoDesc;
00652   infoDesc.setName( "LOG" );
00653   infoDesc.insertColumn( "EXECTIME",
00654                          coral::AttributeSpecification::typeNameForId( 
00655                          typeid(coral::TimeStamp) ) );
00656   infoDesc.insertColumn( "SNAPSHOT",
00657                          coral::AttributeSpecification::typeNameForId( 
00658                          typeid(coral::TimeStamp) ) );
00659   buff_session.nominalSchema().createTable( infoDesc );
00660   coral::AttributeList newInfo;
00661   newInfo.extend( "EXECTIME", typeid(coral::TimeStamp) );
00662   newInfo.extend( "SNAPSHOT", typeid(coral::TimeStamp) );
00663   newInfo["EXECTIME"].data<coral::TimeStamp>() =
00664                            coral::TimeStamp( zeroTime );
00665   newInfo["SNAPSHOT"].data<coral::TimeStamp>() =
00666                            coral::TimeStamp( zeroTime );
00667   coral::ITable& infoTable = 
00668     buff_session.nominalSchema().tableHandle( "LOG" );
00669   infoTable.dataEditor().insertRow( newInfo );
00670 
00671   return;
00672 
00673 }
00674 
00675 
00676 void DTHVStatusHandler::updateHVStatus() {
00677   int missingChannels = recoverSnapshot();
00678   cond::Time_t snapshotTime = recoverLastTime();
00679   std::cout << " snapshot at " << snapshotTime << " ( "
00680                                << coralTime( snapshotTime )
00681                                   .total_nanoseconds() << " ) "
00682                                << std::endl;
00683   if ( snapshotTime > procSince ) {
00684     coral::TimeStamp coralSnap = coralTime( snapshotTime );
00685     std::cout << "too recent snapshot: " << std::endl
00686               << " snapshot at " << coralSnap.year( ) << " "
00687                                  << coralSnap.month() << " "
00688                                  << coralSnap.day(  ) << std::endl
00689               << " copy since " << ySince << " "
00690                                 << mSince << " "
00691                                 << dSince
00692               << " ( "          << procSince << " )" << std::endl;
00693     return;
00694   }
00695   long long int dTime = bwdTime;
00696   dTime <<= 32;
00697   cond::Time_t condUntil = procSince;
00698   cond::Time_t condSince = condUntil - dTime;
00699 
00700   while ( missingChannels ) {
00701     std::cout << "back iteration: "
00702               << condSince << " ( " << coralTime( condSince )
00703                                        .total_nanoseconds() << " ) -> "
00704               << condUntil << " ( " << coralTime( condUntil )
00705                                        .total_nanoseconds() << " ) "
00706               << std::endl;
00707     if ( condSince <= snapshotTime ) condSince = snapshotTime;
00708     std::cout << "corrected since: "
00709               << condSince << " ( " << coralTime( condSince )
00710                                        .total_nanoseconds() << " ) "
00711               << std::endl;
00712     if ( condSince >= condUntil    ) break;
00713     std::cout << "missing... " << missingChannels << std::endl;
00714     checkForPeriod( condSince, condUntil, missingChannels, false );
00715     condUntil = condSince;
00716     condSince = condUntil - dTime;
00717   }
00718 
00719   if ( dumpAtStart ) dumpSnapshot( coralTime( procSince ) );
00720 
00721   copyHVData();
00722 
00723   if ( dumpAtEnd   ) dumpSnapshot( coralTime( lastFound ) );
00724 
00725   return;
00726 }
00727 
00728 
00729 int DTHVStatusHandler::recoverSnapshot() {
00730   int missingChannels = 0;
00731   std::map<int,int>::const_iterator layIter = layerMap.begin();
00732   std::map<int,int>::const_iterator layIend = layerMap.end();
00733   std::cout << "retrieve snapshot table..." << std::endl;
00734   coral::ITable& hvssTable =
00735          buff_session.nominalSchema().tableHandle( "HVSNAPSHOT" );
00736   std::auto_ptr<coral::IQuery> hvssQuery( hvssTable.newQuery() );
00737   hvssQuery->addToOutputList( "TIME" );
00738   hvssQuery->addToOutputList( "WHEEL" );
00739   hvssQuery->addToOutputList( "STATION" );
00740   hvssQuery->addToOutputList( "SECTOR" );
00741   hvssQuery->addToOutputList( "SUPERLAYER" );
00742   hvssQuery->addToOutputList( "LAYER" );
00743   hvssQuery->addToOutputList( "CHAN" );
00744   hvssQuery->addToOutputList( "TYPE" );
00745   hvssQuery->addToOutputList( "VALUE" );
00746   coral::ICursor& hvssCursor = hvssQuery->execute();
00747   while ( hvssCursor.next() ) {
00748     coral::TimeStamp time =
00749            hvssCursor.currentRow()["TIME"].data<coral::TimeStamp>();
00750     int     whe = hvssCursor.currentRow()["WHEEL"     ].data<int>();
00751     int     sta = hvssCursor.currentRow()["STATION"   ].data<int>();
00752     int     sec = hvssCursor.currentRow()["SECTOR"    ].data<int>();
00753     int     qua = hvssCursor.currentRow()["SUPERLAYER"].data<int>();
00754     int     lay = hvssCursor.currentRow()["LAYER"     ].data<int>();
00755     int     l_p = hvssCursor.currentRow()["CHAN"      ].data<int>();
00756     int     mty = hvssCursor.currentRow()["TYPE"      ].data<int>();
00757     float value = hvssCursor.currentRow()["VALUE"     ].data<float>();
00758     if ( mty > 2 ) continue;
00759     DTWireId wireId( whe, sta, sec, qua, lay, 10 + l_p );
00760     layIter = layerMap.find( wireId.rawId() );
00761     if ( layIter == layIend ) {
00762       continue;
00763     }
00764     int dpId = ( layIter->second * 10 ) + mty;
00765     snapshotValues.insert( std::pair<int,timedMeasurement>( 
00766                                    dpId, timedMeasurement( 
00767                                    time.total_nanoseconds(), value ) ) );
00768     missingChannels++;
00769   }
00770   return missingChannels;
00771 }
00772 
00773 
00774 cond::Time_t DTHVStatusHandler::recoverLastTime() {
00775   long long int lastTime = 0LL;
00776   long long int chanTime = 0LL;
00777   std::map<int,timedMeasurement>::iterator mapIter = snapshotValues.begin();
00778   std::map<int,timedMeasurement>::iterator mapIend = snapshotValues.end();
00779   while ( mapIter != mapIend ) {
00780     const std::pair<int,timedMeasurement>& entry = *mapIter++;
00781     chanTime = entry.second.first;
00782     if ( lastTime < chanTime ) lastTime = chanTime;
00783   }
00784   return condTime( lastTime );
00785 /*
00786   coral::ITable& infoTable =
00787          buff_session.nominalSchema().tableHandle( "LOG" );
00788   std::auto_ptr<coral::IQuery> infoQuery( infoTable.newQuery() );
00789   infoQuery->addToOutputList( "SNAPSHOT" );
00790   coral::ICursor& infoCursor = infoQuery->execute();
00791   coral::TimeStamp time;
00792   while ( infoCursor.next() ) {
00793     time = infoCursor.currentRow()["SNAPSHOT"].data<coral::TimeStamp>();
00794   }
00795   return condTime( time );
00796 */
00797 }
00798 
00799 
00800 void DTHVStatusHandler::dumpSnapshot( const coral::TimeStamp& time ) {
00801 
00802   std::cout << "dump snapshot to buffer db..." << std::endl;
00803   std::string emptyCondition( "" );
00804   coral::AttributeList emptyBindVariableList;
00805   std::map<int,int>::const_iterator mapIter = aliasMap.begin();
00806   std::map<int,int>::const_iterator mapIend = aliasMap.end();
00807   coral::ITable& hvssTable =
00808          buff_session.nominalSchema().tableHandle( "HVSNAPSHOT" );
00809   coral::ITableDataEditor& hvssEditor( hvssTable.dataEditor() );
00810   long nRows = hvssEditor.deleteRows( emptyCondition, emptyBindVariableList );
00811   std::cout << nRows << " rows deleted" << std::endl;
00812 
00813   coral::AttributeList newMeas;
00814   newMeas.extend( "TIME",       typeid(coral::TimeStamp) );
00815   newMeas.extend( "WHEEL",      typeid(int) );
00816   newMeas.extend( "STATION",    typeid(int) );
00817   newMeas.extend( "SECTOR",     typeid(int) );
00818   newMeas.extend( "SUPERLAYER", typeid(int) );
00819   newMeas.extend( "LAYER",      typeid(int) );
00820   newMeas.extend( "CHAN",       typeid(int) );
00821   newMeas.extend( "TYPE",       typeid(int) );
00822   newMeas.extend( "VALUE",      typeid(float) );
00823 
00824   nRows = 0;
00825   std::map<int,timedMeasurement>::const_iterator ssvIter =
00826                                   snapshotValues.begin();
00827   std::map<int,timedMeasurement>::const_iterator ssvIend =
00828                                   snapshotValues.end();
00829   while ( ssvIter != ssvIend ) {
00830     const std::pair<int,timedMeasurement>& entry = *ssvIter++;
00831     int dpty = entry.first;
00832     int dpId = dpty / 10;
00833     int type = dpty % 10;
00834     mapIter = aliasMap.find( dpId );
00835     if ( mapIter == mapIend ) continue;
00836     DTWireId chlId( mapIter->second );
00837     const timedMeasurement& tMeas = entry.second;
00838     long long int newTime = tMeas.first;
00839     newMeas["TIME"      ].data<coral::TimeStamp>() =
00840                                coral::TimeStamp( newTime );
00841     newMeas["WHEEL"     ].data<int>() = chlId.wheel     ();
00842     newMeas["STATION"   ].data<int>() = chlId.station   ();
00843     newMeas["SECTOR"    ].data<int>() = chlId.sector    ();
00844     newMeas["SUPERLAYER"].data<int>() = chlId.superLayer();
00845     newMeas["LAYER"     ].data<int>() = chlId.layer     ();
00846     newMeas["CHAN"      ].data<int>() = chlId.wire      () - 10;
00847     newMeas["TYPE"      ].data<int>() = type;
00848     newMeas["VALUE"     ].data<float>() = tMeas.second;
00849     hvssEditor.insertRow( newMeas );
00850     nRows++;
00851   }
00852   std::cout << nRows << " rows updated" << std::endl;
00853 
00854   std::cout << "create logging info..." << std::endl;
00855   if ( buff_session.nominalSchema().existsTable( "LOG" ) )
00856        buff_session.nominalSchema().  dropTable( "LOG" );
00857   coral::TableDescription infoDesc;
00858   infoDesc.setName( "LOG" );
00859   infoDesc.insertColumn( "EXECTIME",
00860                          coral::AttributeSpecification::typeNameForId( 
00861                          typeid(coral::TimeStamp) ) );
00862   infoDesc.insertColumn( "SNAPSHOT",
00863                          coral::AttributeSpecification::typeNameForId( 
00864                          typeid(coral::TimeStamp) ) );
00865   buff_session.nominalSchema().createTable( infoDesc );
00866   coral::AttributeList newInfo;
00867   newInfo.extend( "EXECTIME", typeid(coral::TimeStamp) );
00868   newInfo.extend( "SNAPSHOT", typeid(coral::TimeStamp) );
00869   newInfo["EXECTIME"].data<coral::TimeStamp>() = coral::TimeStamp::now();
00870   newInfo["SNAPSHOT"].data<coral::TimeStamp>() = time;
00871   coral::ITable& infoTable = 
00872     buff_session.nominalSchema().tableHandle( "LOG" );
00873   infoTable.dataEditor().insertRow( newInfo );
00874 
00875   return;
00876 
00877 }
00878 
00879 
00880 int DTHVStatusHandler::checkForPeriod( cond::Time_t condSince,
00881                                        cond::Time_t condUntil,
00882                                        int& missingChannels,
00883                                        bool copyOffline ) {
00884 
00885   std::map<int,timedMeasurement>::iterator mapIter = snapshotValues.begin();
00886   std::map<int,timedMeasurement>::iterator mapIend = snapshotValues.end();
00887 
00888   std::map<long long int,channelValue> periodBuffer;
00889 
00890   coral::ITable& fwccTable =
00891     omds_session.nominalSchema().tableHandle( "FWCAENCHANNEL" );
00892   std::auto_ptr<coral::IQuery> fwccQuery( fwccTable.newQuery() );
00893   fwccQuery->addToOutputList( "DPID"          );
00894   fwccQuery->addToOutputList( "CHANGE_DATE"   );
00895   fwccQuery->addToOutputList( "ACTUAL_VMON"   );
00896   fwccQuery->addToOutputList( "ACTUAL_IMON"   );
00897   fwccQuery->addToOutputList( "ACTUAL_ISON"   );
00898   fwccQuery->addToOutputList( "ACTUAL_STATUS" );
00899   fwccQuery->addToOutputList( "ACTUAL_OVC"    );
00900   coral::AttributeList timeBindVariableList;
00901   timeBindVariableList.extend( "since", typeid(coral::TimeStamp) );
00902   timeBindVariableList.extend( "until", typeid(coral::TimeStamp) );
00903   coral::TimeStamp coralSince = coralTime( condSince );
00904   coral::TimeStamp coralUntil = coralTime( condUntil );
00905   std::cout << "look for data since "            
00906             << coralSince.year(  ) << " "
00907             << coralSince.month( ) << " "
00908             << coralSince.day(   ) << " "
00909             << coralSince.hour(  ) << ":"
00910             << coralSince.minute() << ":"
00911             << coralSince.second() << " until "
00912             << coralUntil.year(  ) << " "
00913             << coralUntil.month( ) << " "
00914             << coralUntil.day(   ) << " "
00915             << coralUntil.hour(  ) << ":"
00916             << coralUntil.minute() << ":"
00917             << coralUntil.second() << std::endl;
00918   timeBindVariableList["since"].data<coral::TimeStamp>() =
00919                                      coralTime( condSince );
00920   timeBindVariableList["until"].data<coral::TimeStamp>() =
00921                                      coralTime( condUntil );
00922   fwccQuery->setCondition( "CHANGE_DATE>:since and CHANGE_DATE<:until",
00923                            timeBindVariableList );
00924   fwccQuery->addToOrderList( "CHANGE_DATE" );
00925   coral::ICursor& fwccCursor = fwccQuery->execute();
00926   int nrows = 0;
00927   while ( fwccCursor.next() ) {
00928     nrows++;
00929     const coral::Attribute& dp     = fwccCursor.currentRow()["DPID"         ];
00930     const coral::Attribute& vmon   = fwccCursor.currentRow()["ACTUAL_VMON"  ];
00931     const coral::Attribute& imon   = fwccCursor.currentRow()["ACTUAL_IMON"  ];
00932     coral::TimeStamp changeTime =
00933            fwccCursor.currentRow()["CHANGE_DATE"].data<coral::TimeStamp>();
00934     long long int cTimeValue = changeTime.total_nanoseconds();
00935     if ( !copyOffline ) cTimeValue = -cTimeValue;
00936     if ( dp.isNull() ) {
00937       std::cout << "------- " << nrows << std::endl;
00938       continue;
00939     }
00940     int dpId = 10 * static_cast<int>( 0.01 +
00941            fwccCursor.currentRow()["DPID"].data<float>() );
00942     if ( !( vmon.isNull() ) ) {
00943       while ( periodBuffer.find( cTimeValue ) !=
00944               periodBuffer.end() ) cTimeValue++;
00945       int chan = dpId + 1;
00946       periodBuffer.insert( std::pair<long long int,channelValue> (
00947                                      cTimeValue, channelValue( chan,
00948                                                  vmon.data<float>() ) ) );
00949     }
00950     if ( !( imon.isNull() ) ) {
00951       while ( periodBuffer.find( cTimeValue ) !=
00952               periodBuffer.end() ) cTimeValue++;
00953       int chan = dpId + 2;
00954       periodBuffer.insert( std::pair<long long int,channelValue> (
00955                                      cTimeValue, channelValue( chan,
00956                                                  imon.data<float>() ) ) );
00957     }
00958   }
00959 
00960   long long int dTime = minTime;
00961   dTime <<= 32;
00962   std::cout << "data found in period: " << periodBuffer.size() << std::endl;
00963   std::map<long long int,channelValue>::const_iterator bufIter =
00964                                                        periodBuffer.begin();
00965   std::map<long long int,channelValue>::const_iterator bufIend =
00966                                                        periodBuffer.end();
00967 
00968   bool changedStatus = false;
00969   while ( bufIter != bufIend ) {
00970     const std::pair<long long int,channelValue>& entry = *bufIter++;
00971     long long int mTime = entry.first;
00972     if ( !copyOffline ) mTime = -mTime;
00973     channelValue cValue = entry.second;
00974     int   chan = cValue.first;
00975     float cont = cValue.second;
00976     mapIter = snapshotValues.find( chan );
00977     if ( ( mapIter != mapIend ) &&
00978          ( mapIter->second.first < mTime ) ) {
00979       nextFound = condTime( mTime );
00980       if ( changedStatus ) {
00981         if ( nextFound > timeLimit ) {
00982           DTHVStatus* hvStatus = offlineList();
00983           std::cout << "new payload "
00984                     << hvStatus->end() - hvStatus->begin() << std::endl;
00985           tmpContainer.push_back( std::make_pair( hvStatus, lastFound ) );
00986           changedStatus = false;
00987           if ( !( --maxPayload ) ) {
00988             procUntil = lastFound;
00989             std::cout << "max payload number reached" << std::endl;
00990             break;
00991           }
00992         }
00993       }
00994       if ( copyOffline && !changedStatus &&
00995            checkStatusChange( chan, mapIter->second.second, cont ) ) {
00996         timeLimit = nextFound + dTime;
00997         changedStatus = true;
00998       }
00999       mapIter->second = timedMeasurement( lastStamp = mTime, cont );
01000       lastFound = nextFound;
01001       missingChannels--;
01002     }
01003   }
01004 
01005   std::cout << nrows << std::endl;
01006   return nrows;
01007 
01008 }
01009 
01010 
01011 void DTHVStatusHandler::copyHVData() {
01012   long long int dTime = fwdTime;
01013   dTime <<= 32;
01014 
01015   cond::Time_t condSince = procSince;
01016   cond::Time_t condUntil = condSince + dTime;
01017   if ( condUntil > procUntil ) condUntil = procUntil;
01018 
01019   int dum = 0;
01020   lastStatus = 0;
01021   while ( condSince < condUntil ) {
01022     checkForPeriod( condSince, condUntil, dum, true );
01023     condSince = condUntil;
01024     condUntil = condSince + dTime;
01025     if ( condUntil > procUntil ) condUntil = procUntil;
01026   }
01027   std::cout << "call filterData " << std::endl;
01028   filterData();
01029   std::cout << "filterData return "
01030             << switchOff  << " "
01031             << lastFound  << " "
01032             << maxPayload << " "
01033             << m_to_transfer.size() << std::endl;
01034   if ( switchOff || ( ( lastFound != 0 ) && ( maxPayload > 0 ) ) ) {
01035     DTHVStatus* hvStatus = offlineList();
01036     m_to_transfer.push_back( std::make_pair( hvStatus, lastFound ) );
01037   }
01038 
01039   return;
01040 }
01041 
01042 
01043 DTHVStatus* DTHVStatusHandler::offlineList() {
01044   DTHVStatus* hv = new DTHVStatus( dataTag );
01045   int type;
01046   float valueA = 0.0;
01047   float valueL = 0.0;
01048   float valueR = 0.0;
01049   float valueS = 0.0;
01050   float valueC = 0.0;
01051   std::map<int,int>::const_iterator layerIter = layerMap.begin();
01052   std::map<int,int>::const_iterator layerIend = layerMap.end();
01053   while ( layerIter != layerIend ) {
01054     const std::pair<int,int>& chanEntry = *layerIter++;
01055     int rawId = chanEntry.first;
01056     DTWireId chlId( rawId );
01057     int whe = chlId.wheel     ();
01058     int sta = chlId.station   ();
01059     int sec = chlId.sector    ();
01060     int qua = chlId.superLayer();
01061     int lay = chlId.layer     ();
01062     int l_p = chlId.wire();
01063     if ( l_p != 10 ) continue;
01064     for ( type = 1; type <= 2; type++ ) {
01065       getLayerValues( rawId, type, valueL, valueR, valueS, valueC );
01066       for ( l_p = 0; l_p <= 1; l_p++ ) {
01067         int rPart = layerId( rawId, l_p ).rawId();
01068         switch ( l_p ) {
01069         case 0:
01070           valueA = valueL;
01071           break;
01072         case 1:
01073           valueA = valueR;
01074           break;
01075         default:
01076           break;
01077         }
01078 //  std::cout << "layer values: " << type << " " << valueA << " "
01079 //                                               << valueS << " "
01080 //                                               << valueC << std::endl;
01081         DTHVAbstractCheck::flag flag = hvChecker->checkCurrentStatus(
01082                                                   rPart, type,
01083                                                   valueA, valueC, valueS,
01084                                                   snapshotValues,
01085                                                   aliasMap, layerMap );
01086         if ( !flag.a && !flag.c && !flag.s ) continue;
01087         setChannelFlag( hv, whe, sta, sec, qua, lay, l_p, flag );
01088         std::map< int,std::vector<int>* >::const_iterator m_iter =
01089                                            channelSplit.find( rPart );
01090         std::map< int,std::vector<int>* >::const_iterator m_iend =
01091                                            channelSplit.end();
01092         if ( m_iter != m_iend ) {
01093           std::vector<int>* cList = m_iter->second;
01094           std::vector<int>::const_iterator l_iter = cList->begin();
01095           std::vector<int>::const_iterator l_iend = cList->end();
01096           while ( l_iter != l_iend ) {
01097             DTWireId chlId( *l_iter++ );
01098             int wh2 = chlId.wheel     ();
01099             int st2 = chlId.station   ();
01100             int se2 = chlId.sector    ();
01101             int qu2 = chlId.superLayer();
01102             int la2 = chlId.layer     ();
01103             int lp2 = chlId.wire() - 10;
01104 //          std::cout << "duplicate "
01105 //                      << whe << " " << sta << " " << sec << " "
01106 //                      << qua << " " << lay << " " << l_p << " ---> "
01107 //                      << wh2 << " " << st2 << " " << se2 << " "
01108 //                      << qu2 << " " << la2 << " " << lp2 << std::endl;
01109             setChannelFlag( hv, wh2, st2, se2, qu2, la2, lp2, flag );
01110           }
01111         }
01112       }
01113     }
01114   }
01115   return hv;
01116 }
01117 
01118 
01119 void DTHVStatusHandler::getLayerValues( int rawId, int type,
01120                                         float& valueL, float& valueR,
01121                                         float& valueS, float& valueC ) {
01122   valueL =
01123   valueR =
01124   valueS =
01125   valueC = 0.0;
01126   DTWireId chlId( rawId );
01127   std::map<int,timedMeasurement>::const_iterator snapIter =
01128                                                  snapshotValues.begin();
01129   std::map<int,timedMeasurement>::const_iterator snapIend =
01130                                                  snapshotValues.end();
01131   int rawL = layerId( rawId, 0 ).rawId();
01132   int rawR = layerId( rawId, 1 ).rawId();
01133   int rawS = layerId( rawId, 2 ).rawId();
01134   int rawC = layerId( rawId, 3 ).rawId();
01135   std::map<int,int>::const_iterator layerIter;
01136   std::map<int,int>::const_iterator layerIend = layerMap.end();
01137   if ( ( layerIter = layerMap.find( rawL ) ) != layerIend ) {
01138     const std::pair<int,int>& layerEntry = *layerIter;
01139     int dpId = layerEntry.second;
01140     snapIter = snapshotValues.find( ( dpId * 10 ) + type );
01141     if ( snapIter != snapIend ) {
01142       const std::pair<int,timedMeasurement>& snapEntry = *snapIter;
01143       valueL = snapEntry.second.second;
01144     }
01145     else std::cout << "snapR not found" << std::endl;
01146   }
01147   else std::cout << "rawR not found" << std::endl;
01148   if ( ( layerIter = layerMap.find( rawR ) ) != layerIend ) {
01149     const std::pair<int,int>& layerEntry = *layerIter;
01150     int dpId = layerEntry.second;
01151     snapIter = snapshotValues.find( ( dpId * 10 ) + type );
01152     if ( snapIter != snapIend ) {
01153       const std::pair<int,timedMeasurement>& snapEntry = *snapIter;
01154       valueR = snapEntry.second.second;
01155     }
01156     else std::cout << "snapL not found" << std::endl;
01157   }
01158   else std::cout << "rawL not found" << std::endl;
01159   if ( ( layerIter = layerMap.find( rawS ) ) != layerIend ) {
01160     const std::pair<int,int>& layerEntry = *layerIter;
01161     int dpId = layerEntry.second;
01162     snapIter = snapshotValues.find( ( dpId * 10 ) + type );
01163     if ( snapIter != snapIend ) {
01164       const std::pair<int,timedMeasurement>& snapEntry = *snapIter;
01165       valueS = snapEntry.second.second;
01166     }
01167     else std::cout << "snapS not found" << std::endl;
01168   }
01169   else std::cout << "rawS not found" << std::endl;
01170   if ( ( layerIter = layerMap.find( rawC ) ) != layerIend ) {
01171     const std::pair<int,int>& layerEntry = *layerIter;
01172     int dpId = layerEntry.second;
01173     snapIter = snapshotValues.find( ( dpId * 10 ) + type );
01174     if ( snapIter != snapIend ) {
01175       const std::pair<int,timedMeasurement>& snapEntry = *snapIter;
01176       valueC = snapEntry.second.second;
01177     }
01178     else std::cout << "snapC not found" << std::endl;
01179   }
01180   else std::cout << "rawC not found" << std::endl;
01181 //  std::cout << "layer values... " << type << " " << valueL << " "
01182 //                                                 << valueR << " "
01183 //                                                 << valueS << " "
01184 //                                                 << valueC << std::endl;
01185   return;
01186 }
01187 
01188 
01189 void DTHVStatusHandler::setChannelFlag( DTHVStatus* hv,
01190                                         int whe, int sta, int sec,
01191                                         int qua, int lay, int l_p,
01192                                         const DTHVAbstractCheck::flag& flag ) {
01193   int fCell = 0;
01194   int lCell = 99;
01195   int flagA = 0;
01196   int flagC = 0;
01197   int flagS = 0;
01198   int searchStatus = hv->get( whe, sta, sec, qua, lay, l_p,
01199                               fCell, lCell, flagA, flagC, flagS );
01200   if ( searchStatus ) {
01201     DTWireId wireId( whe, sta, sec, qua, lay, 10 + l_p );
01202     std::map<int,int>::const_iterator splitIter =
01203                                       laySplit.find( wireId.rawId() );
01204     std::map<int,int>::const_iterator splitIend =
01205                                       laySplit.end();
01206     if ( splitIter != splitIend ) {
01207       int code = splitIter->second;
01208       fCell = code / 10000;
01209       lCell = code % 10000;
01210     }
01211   }
01212   flagA |= flag.a;
01213   flagC |= flag.c;
01214   flagS |= flag.s;
01215   hv->set( whe, sta, sec, qua, lay, l_p,
01216            fCell, lCell, flagA, flagC, flagS );
01217   return;
01218 }
01219 
01220 
01221 int DTHVStatusHandler::checkStatusChange( int chan,
01222                                           float oldValue, float newValue ) {
01223   int dpId = chan / 10;
01224   int type = chan % 10;
01225   std::map<int,int>::const_iterator aliasIter = aliasMap.find( dpId );
01226   std::map<int,int>::const_iterator aliasIend = aliasMap.end();
01227   if ( aliasIter == aliasIend ) return false;
01228   int rawId = aliasIter->second;
01229   DTWireId chlId( rawId );
01230   int l_p = chlId.wire();
01231   float valueL = 0.0;
01232   float valueR = 0.0;
01233   float valueS = 0.0;
01234   float valueC = 0.0;
01235   getLayerValues( rawId, type, valueL, valueR, valueS, valueC );
01236 //  std::cout << "layer values: " << type << " " << valueL << " "
01237 //                                               << valueR << " "
01238 //                                               << valueS << " "
01239 //                                               << valueC << std::endl;
01240   DTHVAbstractCheck::flag
01241       oldStatusL = hvChecker->checkCurrentStatus( layerId( rawId, 0 ).rawId(),
01242                                                   type,
01243                                                   valueL, valueC, valueS,
01244                                                   snapshotValues,
01245                                                   aliasMap, layerMap );
01246   DTHVAbstractCheck::flag
01247       oldStatusR = hvChecker->checkCurrentStatus( layerId( rawId, 1 ).rawId(),
01248                                                   type,
01249                                                   valueR, valueC, valueS,
01250                                                   snapshotValues,
01251                                                   aliasMap, layerMap );
01252   switch ( l_p ) {
01253   case 10:
01254     if ( valueL != oldValue ) std::cout << "*** INCONSISTENT DATA!!!!! "
01255                                         << type << " " << l_p << " "
01256                                         << oldValue << " " << valueL << " "
01257                                         << std::endl;
01258     valueL = newValue;
01259     break;
01260   case 11:
01261     if ( valueR != oldValue ) std::cout << "*** INCONSISTENT DATA!!!!! "
01262                                         << type << " " << l_p << " "
01263                                         << oldValue << " " << valueR << " "
01264                                         << std::endl;
01265     valueR = newValue;
01266     break;
01267   case 12:
01268     if ( valueS != oldValue ) std::cout << "*** INCONSISTENT DATA!!!!! "
01269                                         << type << " " << l_p << " "
01270                                         << oldValue << " " << valueS << " "
01271                                         << std::endl;
01272     valueS = newValue;
01273     break;
01274   case 13:
01275     if ( valueC != oldValue ) std::cout << "*** INCONSISTENT DATA!!!!! "
01276                                         << type << " " << l_p << " "
01277                                         << oldValue << " " << valueC << " "
01278                                         << std::endl;
01279     valueC = newValue;
01280     break;
01281   default:
01282     break;
01283   }
01284   DTHVAbstractCheck::flag
01285       newStatusL = hvChecker->checkCurrentStatus( layerId( rawId, 0 ).rawId(),
01286                                                   type,
01287                                                   valueL, valueC, valueS,
01288                                                   snapshotValues,
01289                                                   aliasMap, layerMap );
01290   DTHVAbstractCheck::flag
01291       newStatusR = hvChecker->checkCurrentStatus( layerId( rawId, 1 ).rawId(),
01292                                                   type,
01293                                                   valueR, valueC, valueS,
01294                                                   snapshotValues,
01295                                                   aliasMap, layerMap );
01296 
01297   if ( DTHVAbstractCheck::compare( newStatusL, oldStatusL ) &&
01298        DTHVAbstractCheck::compare( newStatusR, oldStatusR ) ) return 0;
01299   std::cout << "changed status: " << chan << " from "
01300             << oldValue << " to " << newValue << std::endl;
01301   return 1;
01302 }
01303 
01304 
01305 void DTHVStatusHandler::filterData() {
01306 
01307   int maxTime = 100;
01308   int maxTtot = 600;
01309   int minDiff = 88;
01310 
01311   int iTime = 0;
01312   int pTime = 0;
01313   int nTime = 0;
01314   int iSize;
01315   int pSize;
01316   int nSize;
01317 
01318   std::vector< std::pair<DTHVStatus*, cond::Time_t> >::const_iterator iter =
01319                                                        tmpContainer.begin();
01320   std::vector< std::pair<DTHVStatus*, cond::Time_t> >::const_iterator iend =
01321                                                        tmpContainer.end();
01322   std::vector< std::pair<DTHVStatus*, cond::Time_t> >::const_iterator prev;
01323   std::vector< std::pair<DTHVStatus*, cond::Time_t> >::const_iterator next;
01324 
01325   while ( iter != iend ) {
01326     switchOff = false;
01327     next = iter;
01328     prev = next++;
01329     if ( next == iend ) next = prev;
01330     const DTHVStatus* iPtr = iter->first;
01331     const DTHVStatus* pPtr = prev->first;
01332     const DTHVStatus* nPtr = next->first;
01333     iSize = std::distance( iPtr->begin(), iPtr->end() );
01334     pSize = std::distance( pPtr->begin(), pPtr->end() );
01335     nSize = std::distance( nPtr->begin(), nPtr->end() );
01336     int dtot = nSize - pSize;
01337     prev = next;
01338     while ( ++next != iend ) {
01339       pPtr = prev->first;
01340       nPtr = next->first;
01341       pSize = std::distance( pPtr->begin(), pPtr->end() );
01342       nSize = std::distance( nPtr->begin(), nPtr->end() );
01343       int diff = nSize - pSize;
01344       iTime = static_cast<int>( ( iter->second >> 32 ) & 0xffffffff );
01345       pTime = static_cast<int>( ( prev->second >> 32 ) & 0xffffffff );
01346       nTime = static_cast<int>( ( next->second >> 32 ) & 0xffffffff );
01347       if ( ( nTime - pTime ) > maxTime ) break;
01348       if ( ( nTime - iTime ) > maxTtot ) break;
01349       if ( ( dtot * diff ) < 0 ) break;
01350       prev = next;
01351     }
01352     pPtr = prev->first;
01353     iSize = std::distance( iPtr->begin(), iPtr->end() );
01354     pSize = std::distance( pPtr->begin(), pPtr->end() );
01355     dtot = pSize - iSize;
01356     int dist = pTime - iTime;
01357     if ( ( dtot < -minDiff ) &&
01358          ( dist <  maxTtot ) ) {
01359       std::cout << "  ******** SWITCH ON "
01360                 << std::distance( iter, prev ) << " "
01361                 << iTime << " " << pTime << " "
01362                 << iSize << " " << pSize << std::endl;
01363       m_to_transfer.push_back( std::make_pair( prev->first, prev->second ) );
01364       while ( iter != prev ) delete ( iter++->first );
01365     }
01366     if ( ( dtot >  minDiff ) &&
01367          ( dist <  maxTtot ) ) {
01368       std::cout << "  ******** SWITCH OFF "
01369                 << std::distance( iter, prev ) << " "
01370                 << iTime << " " << pTime << " "
01371                 << iSize << " " << pSize << std::endl;
01372       m_to_transfer.push_back( std::make_pair( prev->first, iter->second ) );
01373       switchOff = true;
01374       while ( iter != prev ) delete ( iter++->first );
01375     }
01376     if ( ( ( dtot >= -minDiff ) && ( dtot <= minDiff ) ) ||
01377          ( dist >= maxTtot ) ) {
01378       while ( iter != next ) {
01379         const std::pair<DTHVStatus*, cond::Time_t>& entry = *iter++;
01380         m_to_transfer.push_back( std::make_pair( entry.first, entry.second ) );
01381       }
01382     }
01383     iter = next;
01384   }
01385 
01386 }
01387 
01388 
01389 DTWireId DTHVStatusHandler::layerId( int rawId, int l_p ) {
01390   DTWireId chlId( rawId );
01391   int whe = chlId.wheel     ();
01392   int sta = chlId.station   ();
01393   int sec = chlId.sector    ();
01394   int qua = chlId.superLayer();
01395   int lay = chlId.layer     ();
01396   DTWireId chl( whe, sta, sec, qua, lay, 10 + l_p );
01397   return chl;
01398 }
01399 
01400 
01401 coral::TimeStamp DTHVStatusHandler::coralTime( const  cond::Time_t&    time ) {
01402   long long int iTime = ( ( ( ( time >> 32 ) & 0xFFFFFFFF ) * 1000000000 ) +
01403                           ( (   time         & 0xFFFFFFFF ) * 1000       ) );
01404   coral::TimeStamp cTime( iTime );
01405   return cTime;
01406 }
01407 
01408 
01409 cond::Time_t     DTHVStatusHandler::condTime(  const coral::TimeStamp& time ) {
01410   cond::Time_t cTime = ( ( time.total_nanoseconds() / 1000000000 )  << 32 ) + 
01411                        ( ( time.total_nanoseconds() % 1000000000 ) / 1000 );
01412   return cTime;
01413 }
01414 
01415 
01416 cond::Time_t     DTHVStatusHandler::condTime(  long long int           time ) {
01417   cond::Time_t cTime = ( ( time                     / 1000000000 )  << 32 ) + 
01418                        ( ( time                     % 1000000000 ) / 1000 );
01419   return cTime;
01420 }
01421 
01422