PDUSensor.cpp 1.72 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
#include <string>

12
13
PDUSensor::PDUSensor(const std::string& name) :
	Sensor(name) {
14
	_pdu = NULL;
15
16
17
18
19
20
21
}

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

void PDUSensor::read() {
22
23
24
	reading_t reading;
	reading.timestamp = getTimestamp();

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

void PDUSensor::readAsync() {
	uint64_t now = getTimestamp();
	read();
41
	if (_timer != NULL && _keepRunning) {
42
43
		uint64_t next = now + MS_TO_NS(_interval);
		_timer->expires_at(timestamp2ptime(next));
44
		_timer->async_wait(_pdu->getStrand()->wrap(std::bind(&PDUSensor::readAsync, this)));
45
46
47
	}
}

48
49
50
51
52
void PDUSensor::init(boost::asio::io_service& io) {
	if(_pdu) {
		_pdu->initializeStrand(io);
	} else {
		LOG(error) << "No PDUUnit set for sensor " << _name << "! Cannot initialize sensor.";
53
	}
54
55
56
57
	Sensor::init(io);
}

void PDUSensor::startPolling() {
58
	if (_pdu) {
59
		_keepRunning = 1;
60
		_timer->async_wait(_pdu->getStrand()->wrap(std::bind(&PDUSensor::readAsync, this)));
61
		LOG(info) << "Sensor " << _name << " started.";
62
	} else {
Micha Mueller's avatar
Micha Mueller committed
63
		LOG(error) << "No PDUUnit set for sensor " << _name << "! Cannot start polling.";
64
	}
65
66
}

67
68
69
70
71
72
void PDUSensor::stopPolling() {
	_keepRunning = 0;
	//cancel any outstanding readAsync()
	_timer->cancel();
	LOG(info) << "Sensor " << _name << " stopped.";
}