PDUSensor.cpp 1.54 KB
Newer Older
1
2
3
4
5
6
7
8
9
/*
 * PDUSensor.cpp
 *
 *  Created on: 24.02.2018
 *      Author: Micha Mueller
 */

#include "PDUSensor.h"
#include "timestamp.h"
10
11
12
#include <string>

extern volatile int keepRunning;
13
14
15

PDUSensor::PDUSensor(const std::string& name) :
	Sensor(name) {
16
	_pdu = NULL;
17
18
19
20
21
22
23
}

PDUSensor::~PDUSensor() {
	// TODO Auto-generated destructor stub
}

void PDUSensor::read() {
24
25
26
	reading_t reading;
	reading.timestamp = getTimestamp();

27
28
29
30
31
	try {
		reading.value = _pdu->readValue(_xmlPath);
		_readingQueue->push(reading);
		_latestValue.value		= reading.value;
		_latestValue.timestamp	= reading.timestamp;
32
#ifdef DEBUG
Micha Mueller's avatar
Micha Mueller committed
33
		LOG(debug) << _pdu->getHost() << "::" << _name << ": \"" << reading.value << "\"";
34
#endif
35
	} catch (const std::exception& e) {
Micha Mueller's avatar
Micha Mueller committed
36
		LOG(error) << _pdu->getHost() << "::" << _name << " could not read value: " << e.what();
37
	}
38
39
40
41
42
43
44
45
}

void PDUSensor::readAsync() {
	uint64_t now = getTimestamp();
	read();
	if (_timer != NULL && keepRunning) {
		uint64_t next = now + MS_TO_NS(_interval);
		_timer->expires_at(timestamp2ptime(next));
46
		_timer->async_wait(_pdu->getStrand()->wrap(std::bind(&PDUSensor::readAsync, this)));
47
48
49
50
51
52
53
	}
}

void PDUSensor::startPolling(boost::asio::io_service& io) {
	if(!_readingQueue) {
		_readingQueue = new boost::lockfree::spsc_queue<reading_t>(1024);
	}
54
	if (_pdu) {
Micha Mueller's avatar
Micha Mueller committed
55
		_pdu->initializeStrand(io);
56
57
58
		_timer = new boost::asio::deadline_timer(io, boost::posix_time::seconds(0));
		_timer->async_wait(_pdu->getStrand()->wrap(std::bind(&PDUSensor::readAsync, this)));
	} else {
Micha Mueller's avatar
Micha Mueller committed
59
		LOG(error) << "No PDUUnit set for sensor " << _name << "! Cannot start polling.";
60
	}
61
62
}