MetaDataRetrieverDIPBridge.cc 22.3 KB
Newer Older
1
2
#include <iomanip>
#include <sstream>
3
#include <bitset>
4
5
6
7
8
9

#include "evb/readoutunit/MetaDataRetrieverDIPBridge.h"
#include "log4cplus/loggingmacros.h"

#include "b2in/nub/Method.h"
#include "xcept/tools.h"
10
#include "xcept/Exception.h"
11
#include "toolbox/mem/AutoReference.h"
12
13
14
15
16
17

#include "toolbox/task/Timer.h"

#include "toolbox/task/TimerFactory.h"
#include "toolbox/TimeInterval.h"

18
19
20
21
#include "xdata/Table.h"
#include "xdata/exdr/Serializer.h"
#include "xdata/exdr/FixedSizeInputStreamBuffer.h"
#include "xdata/Integer32.h"
22
#include "xdata/Integer64.h"
23
24
25
26
27
28
#include "xdata/Float.h"



evb::readoutunit::MetaDataRetrieverDIPBridge::MetaDataRetrieverDIPBridge(
  xdaq::Application* owner,
29
  toolbox::task::TimerListener* timerListener,
30
  const std::string& eventBusName,
31
  xdata::UnsignedInteger32& dipBridgeTimeout,
32
33
34
35
36
  log4cplus::Logger& logger
):
  eventing::api::Member(owner),
  logger_(logger)
{
37
  timerListener_= timerListener;
38
  eventingBusName_=eventBusName.c_str();
39
  dipBridgeRegisterTimeout_ = dipBridgeTimeout;
40
41
42
  // Attention: DCS HV values have to come first and in the order of the HV bits
  // defined in DataFormats::OnlineMetaData::DCSRecord::Partition in CMSSW
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_ECAL/CMS_ECAL_BP/state",unavailable) );
43
  dipTopicsMap_["dip/CMS/DCS/CMS_ECAL/CMS_ECAL_BP/state"]= 0;
44
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_ECAL/CMS_ECAL_BM/state",unavailable) );
45
  dipTopicsMap_["dip/CMS/DCS/CMS_ECAL/CMS_ECAL_BM/state"]= 1;
46
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_ECAL/CMS_ECAL_EP/state",unavailable) );
47
  dipTopicsMap_["dip/CMS/DCS/CMS_ECAL/CMS_ECAL_EP/state"]= 2;
48
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_ECAL/CMS_ECAL_EM/state",unavailable) );
49
  dipTopicsMap_["dip/CMS/DCS/CMS_ECAL/CMS_ECAL_EM/state"]= 3;
50
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_HCAL/CMS_HCAL_HEHBa/state",unavailable) );
51
  dipTopicsMap_["dip/CMS/DCS/CMS_HCAL/CMS_HCAL_HEHBa/state"]= 4;
52
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_HCAL/CMS_HCAL_HEHBb/state",unavailable) );
53
  dipTopicsMap_["dip/CMS/DCS/CMS_HCAL/CMS_HCAL_HEHBb/state"]= 5;
54
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_HCAL/CMS_HCAL_HEHBc/state",unavailable) );
55
  dipTopicsMap_["dip/CMS/DCS/CMS_HCAL/CMS_HCAL_HEHBc/state"]= 6;
56
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_HCAL/CMS_HCAL_HF/state",unavailable) );
57
  dipTopicsMap_["dip/CMS/DCS/CMS_HCAL/CMS_HCAL_HF/state"]= 7;
58
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_HCAL/CMS_HCAL_HO/state",unavailable) );
59
  dipTopicsMap_["dip/CMS/DCS/CMS_HCAL/CMS_HCAL_HO/state"]= 8;
60
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_RPC/state",unavailable) );
61
  dipTopicsMap_["dip/CMS/DCS/CMS_RPC/state"]= 9;
62
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_DT/CMS_DT_DT0/state",unavailable) );
63
  dipTopicsMap_["dip/CMS/DCS/CMS_DT/CMS_DT_DT0/state"]= 10;
64
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_DT/CMS_DT_DTP/state",unavailable) );
65
  dipTopicsMap_["dip/CMS/DCS/CMS_DT/CMS_DT_DTP/state"]= 11;
66
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_DT/CMS_DT_DTM/state",unavailable) );
67
  dipTopicsMap_["dip/CMS/DCS/CMS_DT/CMS_DT_DTM/state"]= 12;
68
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_CSC/CMS_CSCP/state",unavailable) );
69
  dipTopicsMap_["dip/CMS/DCS/CMS_CSC/CMS_CSCP/state"]= 13;
70
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_CSC/CMS_CSCM/state",unavailable) );
71
  dipTopicsMap_["dip/CMS/DCS/CMS_CSC/CMS_CSCM/state"]= 14;
72
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_HCAL/CMS_HCAL_CASTOR/state",unavailable) );
73
  dipTopicsMap_["dip/CMS/DCS/CMS_HCAL/CMS_HCAL_CASTOR/state"]= 15;
74
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_HCAL/CMS_HCAL_ZDC/state",unavailable) );
75
  dipTopicsMap_["dip/CMS/DCS/CMS_HCAL/CMS_HCAL_ZDC/state"]= 16;
76
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_TRACKER/CMS_TRACKER_TIB_TID/state",unavailable) );
77
  dipTopicsMap_["dip/CMS/DCS/CMS_TRACKER/CMS_TRACKER_TIB_TID/state"]= 17;
78
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_TRACKER/CMS_TRACKER_TOB/state",unavailable) );
79
  dipTopicsMap_["dip/CMS/DCS/CMS_TRACKER/CMS_TRACKER_TOB/state"]= 18;
80
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_TRACKER/CMS_TRACKER_TECP/state",unavailable) );
81
  dipTopicsMap_["dip/CMS/DCS/CMS_TRACKER/CMS_TRACKER_TECP/state"]= 19;
82
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_TRACKER/CMS_TRACKER_TECM/state",unavailable) );
83
  dipTopicsMap_["dip/CMS/DCS/CMS_TRACKER/CMS_TRACKER_TECM/state"]= 20;
84
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_PIXEL/CMS_PIXEL_BPIX/state",unavailable) );
85
  dipTopicsMap_["dip/CMS/DCS/CMS_PIXEL/CMS_PIXEL_BPIX/state"]= 21;
86
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_PIXEL/CMS_PIXEL_FPIX/state",unavailable) );
87
  dipTopicsMap_["dip/CMS/DCS/CMS_PIXEL/CMS_PIXEL_FPIX/state"]= 22;
88
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_ECAL/CMS_ECAL_ESP/state",unavailable) );
89
  dipTopicsMap_["dip/CMS/DCS/CMS_ECAL/CMS_ECAL_ESP/state"]= 23;
90
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_ECAL/CMS_ECAL_ESM/state",unavailable) );
91
  dipTopicsMap_["dip/CMS/DCS/CMS_ECAL/CMS_ECAL_ESM/state"]= 24;
92
93
94
95
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_GEM/CMS_GEM_EP/state",unavailable) );
  dipTopicsMap_["dip/CMS/DCS/CMS_GEM/CMS_GEM_EP/state"]= 25;
  dipTopics_.push_back( DipTopic("dip/CMS/DCS/CMS_GEM/CMS_GEM_EM/state",unavailable) );
  dipTopicsMap_["dip/CMS/DCS/CMS_GEM/CMS_GEM_EM/state"]= 26;
96
  dipTopics_.push_back( DipTopic("dip/CMS/MCS/Current",unavailable) );
97
  dipTopicsMap_["dip/CMS/MCS/Current"]= 27;
98
  dipTopics_.push_back( DipTopic("dip/CMS/BRIL/Luminosity",unavailable) );
99
  dipTopicsMap_["dip/CMS/BRIL/Luminosity"]= 28;
100
  dipTopics_.push_back( DipTopic("dip/CMS/Tracker/BeamSpot",unavailable) );
101
  dipTopicsMap_["dip/CMS/Tracker/BeamSpot"]= 29;
102
  dipTopics_.push_back( DipTopic("dip/CMS/CTPPS/detectorFSM",unavailable) );
103
  dipTopicsMap_["dip/CMS/CTPPS/detectorFSM"]= 30;
104
105

 b2in::nub::deferredbind(this->getOwnerApplication(),this, &evb::readoutunit::MetaDataRetrieverDIPBridge::handleMessage);
106
 dipBridgeSubscriptions_ = false;
107
108
109
110
111
112
113
114
115
116
117
118
119
120

}


evb::readoutunit::MetaDataRetrieverDIPBridge::~MetaDataRetrieverDIPBridge()
{

	for (auto& topic : dipTopics_)
  {

	try
	{
		if ( maskedDipTopics_.find(topic.first) != std::string::npos )
		  topic.second = masked;
121
122
		else if ( topic.second != okay ) {
		    xdata::Properties plist;
123
		    plist.setProperty("urn:dip:action", "unregister");
124
125
		    plist.setProperty("urn:dip:topicname", topic.first.c_str());
		    this->getEventingBus(eventingBusName_).publish("urn:dip:metacontrol", 0, plist);
126
		    LOG4CPLUS_INFO(logger_,toolbox::toString("urn:dip:action=unregister, urn:dip:topicname=%s",topic.first.c_str()));
127
		}
128
129
130
131
132
133
134
135
136
	 } catch(eventing::api::exception::Exception& e)
		{
			std::string msg("Failed to unsubscribe to eventing bus "+eventingBusName_);
			LOG4CPLUS_ERROR(logger_,msg+stdformat_exception_history(e));
		}
  }

}

137
void evb::readoutunit::MetaDataRetrieverDIPBridge::timerToRegisterToDipBridge() {
138

139
140
     std::string appUUID= this->getOwnerApplication()->getApplicationDescriptor()->getUUID().toString();
     std::string timerName_= "timer_" + appUUID + toolbox::toString(".%d", rand());
141
142
143
144
145
146
147
148
149
150
151
152
153
154
     try {
		 toolbox::task::Timer * timer_ = toolbox::task::getTimerFactory()->createTimer(timerName_);

		 // current time, scheduled start time, and xmas-ready time
		 double now = toolbox::TimeVal::gettimeofday();
		 double startTimeSecs_ = now + dipBridgeRegisterTimeout_;

		 // schedule start of monitoring
		 toolbox::TimeVal startTime(startTimeSecs_);
		 timer_->schedule(timerListener_, startTime, 0, "");
     } catch (toolbox::task::exception::Exception &e) {
    	 std::string msg("Failed to create the timer with name=" + timerName_ + " ");
    	 LOG4CPLUS_ERROR(logger_, msg + stdformat_exception_history(e));
     }
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170

}


void evb::readoutunit::MetaDataRetrieverDIPBridge::registerToDipBridge(
		const std::string &maskedDipTopics) {
	for (auto &topic : dipTopics_) {
			try {
				if (maskedDipTopics.find(topic.first) != std::string::npos)
					topic.second = masked;
				else if (topic.second != okay) {
					xdata::Properties plist;
					plist.setProperty("urn:dip:action", "register");
					plist.setProperty("urn:dip:topicname", topic.first.c_str());
					this->getEventingBus(eventingBusName_).publish(
							"urn:dip:metacontrol", 0, plist);
171
					LOG4CPLUS_INFO(logger_,
172
173
174
175
176
177
178
179
							toolbox::toString(
									"urn:dip:action=register, urn:dip:topicname=%s",
									topic.first.c_str()));
				}
			} catch (eventing::api::exception::Exception &e) {
				std::string msg(
						"Failed to subscribe to eventing bus " + eventingBusName_);
				LOG4CPLUS_ERROR(logger_, msg + stdformat_exception_history(e));
180
			}
181
		}
182
}
183

184
185
186
187
188
189
190
191
192
193
194
195
void evb::readoutunit::MetaDataRetrieverDIPBridge::subscribeToDip(
		const std::string &maskedDipTopics) {
	maskedDipTopics_ = maskedDipTopics;
	if (!dipBridgeSubscriptions_) {
		for (auto &topic : dipTopics_) {

			try {
				if (maskedDipTopics.find(topic.first) != std::string::npos)
					topic.second = masked;
				else if (topic.second != okay) {
					this->getEventingBus(eventingBusName_).subscribe(
							topic.first.c_str());
196
					LOG4CPLUS_INFO(logger_,
197
198
199
200
201
202
203
204
205
206
207
208
209
210
							toolbox::toString("subsribe, topicname=%s",
									topic.first.c_str()));
				}
			} catch (eventing::api::exception::Exception &e) {
				std::string msg(
						"Failed to subscribe to eventing bus "
								+ eventingBusName_);
				LOG4CPLUS_ERROR(logger_, msg + stdformat_exception_history(e));
			}
		}
		dipBridgeSubscriptions_ = true;
	}
	// Call the timer to register to DIPBridge
	this->timerToRegisterToDipBridge();
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
}

void evb::readoutunit::MetaDataRetrieverDIPBridge::handleMessage(toolbox::mem::Reference * ref, xdata::Properties & plist)
{
	toolbox::mem::AutoReference refguard(ref); //guarantee ref is released when refguard is out of scope
	std::string action = plist.getProperty("urn:b2in-eventing:action");
	if ( action == "notify" && ref!=0 )
	{
		const std::string topicName = plist.getProperty("urn:b2in-eventing:topic");
		//parse table message
		xdata::Table table;
		xdata::exdr::FixedSizeInputStreamBuffer inBuffer(static_cast<char*>(ref->getDataLocation()),ref->getDataSize());
		xdata::exdr::Serializer serializer;
		try
		{
			serializer.import(&table, &inBuffer);
		}
		catch (xdata::exception::Exception& e)
		{
			LOG4CPLUS_ERROR(logger_,"Failed to deserialize incoming table "+stdformat_exception_history(e));
			ref->release();
		}

234
		try {
235
		xdata::Serializable* p;
236
237
		p = table.getValueAt(0, "DipTimestamp");
		xdata::Integer64 timeStampNanos = dynamic_cast<xdata::Integer64*>(p)->value_;
238
		uint64_t dipTime = static_cast<uint64_t>(timeStampNanos);
239
240
241
242
243
244
245

		std::map<std::string,int> ::iterator it;
		it = dipTopicsMap_.find(topicName);

		if(it != dipTopicsMap_.end()) {
			dipTopics_[it->second].second = okay;
		}
246
		std::stringstream msg;
247
248
249
250
		if ( topicName == "dip/CMS/BRIL/Luminosity" )
		  {
		      std::lock_guard<std::mutex> guard(luminosityMutex_);

251
		      lastLuminosity_.timeStamp = dipTime;
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267

		      //lastLuminosity_.lumiSection = dipData.extractInt("LumiSection");
		      p = table.getValueAt(0, "LumiSection");
		      lastLuminosity_.lumiSection = dynamic_cast<xdata::Integer32*>(p)->value_;

		      //lastLuminosity_.lumiNibble = dipData.extractInt("LumiNibble");
		      p = table.getValueAt(0, "LumiNibble");
		      lastLuminosity_.lumiNibble = dynamic_cast<xdata::Integer32*>(p)->value_;

		     //lastLuminosity_.instLumi = dipData.extractFloat("InstLumi");
		      p = table.getValueAt(0, "InstLumi");
		      lastLuminosity_.instLumi = dynamic_cast<xdata::Float*>(p)->value_;

		      //lastLuminosity_.avgPileUp = dipData.extractFloat("AvgPileUp");
		      p = table.getValueAt(0, "AvgPileUp");
		      lastLuminosity_.avgPileUp = dynamic_cast<xdata::Float*>(p)->value_;
268

269
		      /*msg << "Got a 'dip/CMS/BRIL/Luminosity' notification: diptime=" << dipTime <<
270
271
272
		    		  " lumiSection=" << lastLuminosity_.lumiSection << " LumiNibble=" <<
					  lastLuminosity_.lumiNibble << " InstLumi=" << lastLuminosity_.instLumi <<
					  " AvgPileUp=" << lastLuminosity_.avgPileUp;
273
		      LOG4CPLUS_INFO(logger_,msg.str());*/
274
275
276
277
278
		  }
		  else if ( topicName == "dip/CMS/Tracker/BeamSpot" )
		  {
		      std::lock_guard<std::mutex> guard(beamSpotMutex_);

279
280
		      lastBeamSpot_.timeStamp = dipTime;

281
		      //msg << "Got a 'dip/CMS/Tracker/BeamSpot': diptime=" <<  dipTime;
282
283
284
285
286
287
288
289
290
291
292
293
294

		      //lastBeamSpot_.x = dipData.extractFloat("x");
		      p = table.getValueAt(0, "x");
		      lastBeamSpot_.x = dynamic_cast<xdata::Float*>(p)->value_;

		     // lastBeamSpot_.y = dipData.extractFloat("y");
		      p = table.getValueAt(0, "y");
		      lastBeamSpot_.y = dynamic_cast<xdata::Float*>(p)->value_;

		      //lastBeamSpot_.z = dipData.extractFloat("z");
		      p = table.getValueAt(0, "z");
		      lastBeamSpot_.z = dynamic_cast<xdata::Float*>(p)->value_;

295
		      //msg << ", x=" << lastBeamSpot_.x << ", y=" << lastBeamSpot_.y <<", z=" << lastBeamSpot_.z;
296

297
298
299
300
301
302
303
304
305
306
307
308
		      //lastBeamSpot_.widthX = dipData.extractFloat("width_x");
		      p = table.getValueAt(0, "width_x");
		      lastBeamSpot_.widthX = dynamic_cast<xdata::Float*>(p)->value_;

		      //lastBeamSpot_.widthY = dipData.extractFloat("width_y");
		      p = table.getValueAt(0, "width_y");
		      lastBeamSpot_.widthY = dynamic_cast<xdata::Float*>(p)->value_;

		      //lastBeamSpot_.sigmaZ = dipData.extractFloat("sigma_z");
		      p = table.getValueAt(0, "sigma_z");
		      lastBeamSpot_.sigmaZ = dynamic_cast<xdata::Float*>(p)->value_;

309
		      //msg << ", width_x=" << lastBeamSpot_.widthX << ", width_y=" << lastBeamSpot_.widthY << ", sigma_z=" << lastBeamSpot_.sigmaZ;
310
311
312
313
314
315
316
317
318
319
320
321
322

		      //lastBeamSpot_.errX = dipData.extractFloat("err_x");
		      p = table.getValueAt(0, "err_x");
		      lastBeamSpot_.errX = dynamic_cast<xdata::Float*>(p)->value_;

		      //lastBeamSpot_.errY = dipData.extractFloat("err_y");
		      p = table.getValueAt(0, "err_y");
		      lastBeamSpot_.errY = dynamic_cast<xdata::Float*>(p)->value_;

		      //lastBeamSpot_.errZ = dipData.extractFloat("err_z");
		      p = table.getValueAt(0, "err_z");
		      lastBeamSpot_.errZ = dynamic_cast<xdata::Float*>(p)->value_;

323
		      //msg << ", err_x=" << lastBeamSpot_.errX << ", err_y=" << lastBeamSpot_.errY << ", err_z=" << lastBeamSpot_.errZ;
324

325
326
327
328
329
330
331
332
333
334
335
336
		      //lastBeamSpot_.errWidthX = dipData.extractFloat("err_width_x");
		      p = table.getValueAt(0, "err_width_x");
		      lastBeamSpot_.errWidthX = dynamic_cast<xdata::Float*>(p)->value_;

		      //lastBeamSpot_.errWidthY = dipData.extractFloat("err_width_y");
		      p = table.getValueAt(0, "err_width_y");
		      lastBeamSpot_.errWidthY = dynamic_cast<xdata::Float*>(p)->value_;

		      //lastBeamSpot_.errSigmaZ = dipData.extractFloat("err_sigma_z");
		      p = table.getValueAt(0, "err_sigma_z");
		      lastBeamSpot_.errSigmaZ = dynamic_cast<xdata::Float*>(p)->value_;

337
		      //msg << ", err_width_x="<< lastBeamSpot_.errWidthX << ", err_width_y="<< lastBeamSpot_.errWidthY << ", err_sigma_z="<< lastBeamSpot_.errSigmaZ;
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354

		      //lastBeamSpot_.dxdz = dipData.extractFloat("dxdz");
		      p = table.getValueAt(0, "dxdz");
		      lastBeamSpot_.dxdz = dynamic_cast<xdata::Float*>(p)->value_;

		      //lastBeamSpot_.dydz = dipData.extractFloat("dydz");
		      p = table.getValueAt(0, "dydz");
		      lastBeamSpot_.dydz = dynamic_cast<xdata::Float*>(p)->value_;

		      //lastBeamSpot_.errDxdz = dipData.extractFloat("err_dxdz");
		      p = table.getValueAt(0, "err_dxdz");
		      lastBeamSpot_.errDxdz = dynamic_cast<xdata::Float*>(p)->value_;

		      //lastBeamSpot_.errDydz = dipData.extractFloat("err_dydz");
		      p = table.getValueAt(0, "err_dydz");
		      lastBeamSpot_.errDydz = dynamic_cast<xdata::Float*>(p)->value_;

355
356
		      //msg << ", dxdz=" << lastBeamSpot_.dxdz << ", dydz=" << lastBeamSpot_.dydz << ", err_dxdz="<< lastBeamSpot_.errDxdz << ", err_dydz="<< lastBeamSpot_.errDydz;
		      //LOG4CPLUS_INFO(logger_,msg.str());
357
358
359
360
		  }
		  else if ( topicName == "dip/CMS/CTPPS/detectorFSM" )
		  {
		      std::lock_guard<std::mutex> guard(ctppsMutex_);
361
		      lastCTPPS_.timeStamp = dipTime;
362
363
364
365
		      lastCTPPS_.status = 0;

		      for (uint8_t i = 0; i < MetaData::CTPPS::rpCount; ++i)
		      {
366
			    // TODO check if it works
367
368
369
		    	p = table.getValueAt(0, MetaData::CTPPS::ctppsRP[i]);
		    	uint64_t status = static_cast<uint64_t>(dynamic_cast<xdata::Integer32*>(p)->value_);
		        lastCTPPS_.status |= (status & 0x3) << (i*2);
370
		      }
371
		      /* msg << "Got a 'dip/CMS/CTPPS/detectorFSM' notification: diptime=" << dipTime <<
372
		    		  " status=" << lastCTPPS_.status;
373
		      LOG4CPLUS_INFO(logger_, msg.str());*/
374

375
376
377
378
		  }
		  else if ( topicName == "dip/CMS/MCS/Current" )
		  {
		      std::lock_guard<std::mutex> guard(dcsMutex_);
379
		      lastDCS_.timeStamp = std::max(lastDCS_.timeStamp,dipTime);
380
381
382

		      p = table.getValueAt(0, "__DIP_DEFAULT__");
		      lastDCS_.magnetCurrent = dynamic_cast<xdata::Float*>(p)->value_;
383
		      /* msg << "Got a 'dip/CMS/MCS/Current' notification: diptime=" << dipTime <<
384
		    		  " magnetCurrent=" << lastDCS_.magnetCurrent;
385
		      LOG4CPLUS_INFO(logger_, msg.str()); */
386
387
388
389
390
391
392
393
394
		  }
		  else
		  {
		    const uint16_t pos = std::find_if(dipTopics_.begin(), dipTopics_.end(), isTopic(topicName)) - dipTopics_.begin();
		      std::lock_guard<std::mutex> guard(dcsMutex_);

		      p = table.getValueAt(0, "__DIP_DEFAULT__");
		      const std::string state = dynamic_cast<xdata::String*>(p)->value_;

395
		      lastDCS_.highVoltageValid |= (1 << pos);
396

397
		      if ( state == "ON" || state == "READY" )
398
399
400
401
		        lastDCS_.highVoltageReady |= (1 << pos);
		      else
		        lastDCS_.highVoltageReady &= ~(1 << pos);

402
		      std::bitset<32> bitValue(lastDCS_.highVoltageReady);
403
		      lastDCS_.timeStamp = std::max(lastDCS_.timeStamp,dipTime);
404
405
406
		      msg << "Got a '" << topicName << "' notification: diptime=" << dipTime << " state="  <<
		    		  state << " status=" << bitValue;
		      LOG4CPLUS_INFO(logger_, msg.str());
407

408
		  }
409
410
411
412
		} catch (std::bad_cast& e)
		{
			LOG4CPLUS_ERROR(logger_,toolbox::toString("Failed to dynamic cast dip value and got this error: %s", e.what()));
		}
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
	}
}


bool evb::readoutunit::MetaDataRetrieverDIPBridge::fillLuminosity(MetaData::Luminosity& luminosity)
{
  std::lock_guard<std::mutex> guard(luminosityMutex_);

  if ( lastLuminosity_.timeStamp > 0 && lastLuminosity_ != luminosity )
  {
    luminosity = lastLuminosity_;
    return true;
  }

  return false;
}


bool evb::readoutunit::MetaDataRetrieverDIPBridge::fillBeamSpot(MetaData::BeamSpot& beamSpot)
{
  std::lock_guard<std::mutex> guard(beamSpotMutex_);

  if ( lastBeamSpot_.timeStamp > 0 && lastBeamSpot_ != beamSpot )
  {
    beamSpot = lastBeamSpot_;
    return true;
  }

  return false;
}


bool evb::readoutunit::MetaDataRetrieverDIPBridge::fillCTPPS(MetaData::CTPPS& CTPPS)
{
  std::lock_guard<std::mutex> guard(ctppsMutex_);

  if ( lastCTPPS_.timeStamp > 0 && lastCTPPS_ != CTPPS )
  {
    CTPPS = lastCTPPS_;
    return true;
  }

  return false;
}


bool evb::readoutunit::MetaDataRetrieverDIPBridge::fillDCS(MetaData::DCS& dcs)
{
  std::lock_guard<std::mutex> guard(dcsMutex_);

  if ( lastDCS_.timeStamp > 0 && lastDCS_ != dcs )
  {
    dcs = lastDCS_;
    return true;
  }

  return false;
}


bool evb::readoutunit::MetaDataRetrieverDIPBridge::fillData(unsigned char* payload)
{
  MetaData::Data* data = (MetaData::Data*)payload;
  data->version = MetaData::version;

  return (
    fillLuminosity(data->luminosity) ||
    fillBeamSpot(data->beamSpot) ||
    fillCTPPS(data->ctpps) ||
    fillDCS(data->dcs)
  );
}


bool evb::readoutunit::MetaDataRetrieverDIPBridge::missingSubscriptions() const
{
  for (auto const& topic : dipTopics_)
  {
    if (topic.second == unavailable) return true;
  }
  return false;
}


void evb::readoutunit::MetaDataRetrieverDIPBridge::addListOfSubscriptions(std::ostringstream& msg, const bool missingOnly)
{
  for (auto const& topic : dipTopics_)
  {
    if ( missingOnly )
    {
      if ( topic.second == unavailable )
        msg << " " << topic.first;
    }
    else
    {
      msg << " " << topic.first;
    }
  }
}


cgicc::td evb::readoutunit::MetaDataRetrieverDIPBridge::getDipStatus(const std::string& urn) const
{
  using namespace cgicc;

  td status;
  status.set("colspan","6").set("style","text-align:center");
  status.add(a(std::string("soft FED ") + (missingSubscriptions()?"missing DIP subscriptions":"subscribed to DIP"))
             .set("href","/"+urn+"/dipStatus").set("target","_blank"));

  return status;
}


cgicc::table evb::readoutunit::MetaDataRetrieverDIPBridge::dipStatusTable() const
{
  using namespace cgicc;

  table table;
  table.set("class","xdaq-table-vertical");

  table.add(tr()
            .add(th("DIP topic"))
            .add(th("value")));

  for (uint16_t pos = 0; pos < dipTopics_.size(); ++pos)
  {
    const std::string topic = dipTopics_[pos].first;

    switch ( dipTopics_[pos].second )
    {
      case okay :
      {
        tr row;
        row.add(td(topic));

        if ( topic == "dip/CMS/BRIL/Luminosity" )
        {
          std::lock_guard<std::mutex> guard(luminosityMutex_);
          std::ostringstream valueStr;
          valueStr << lastLuminosity_;
          row.add(td(pre(valueStr.str())));
        }
        else if ( topic == "dip/CMS/Tracker/BeamSpot" )
        {
          std::lock_guard<std::mutex> guard(dcsMutex_);
          std::ostringstream valueStr;
          valueStr << lastBeamSpot_;
          row.add(td(pre(valueStr.str())));
        }
        else if ( topic == "dip/CMS/CTPPS/detectorFSM" )
        {
          std::lock_guard<std::mutex> guard(ctppsMutex_);
          std::ostringstream valueStr;
          valueStr << lastCTPPS_;
          row.add(td(pre(valueStr.str())));
        }
        else if ( topic == "dip/CMS/MCS/Current" )
        {
          std::lock_guard<std::mutex> guard(dcsMutex_);
          std::ostringstream valueStr;
          valueStr << std::fixed << std::setprecision(3) << lastDCS_.magnetCurrent << " A";
          row.add(td(valueStr.str()));
        }
        else
        {
          std::lock_guard<std::mutex> guard(dcsMutex_);
          if ( lastDCS_.highVoltageReady & (1 << pos) )
            row.add(td("READY"));
          else
            row.add(td("OFF"));
        }

        table.add(row);
        break;
      }
      case unavailable:
      {
        table.add(tr().set("style","background-color: #ff9380")
                  .add(td(topic))
                  .add(td("unavailable")));
        break;
      }
      case masked:
      {
        table.add(tr().set("style","color: #c1c1c1")
                  .add(td(topic))
                  .add(td("masked")));
        break;
      }
    }
  }

  return table;
}


/// emacs configuration
/// Local Variables: -
/// mode: c++ -
/// c-basic-offset: 2 -
/// indent-tabs-mode: nil -
/// End: -