PDUSingleSensor.cpp 1.93 KB
Newer Older
1
/*
2
 * PDUSingleSensor.cpp
3
4
5
6
7
 *
 *  Created on: 24.02.2018
 *      Author: Micha Mueller
 */

8
9
#include "PDUSingleSensor.h"

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

13
14
PDUSingleSensor::PDUSingleSensor(const std::string& name) :
	SensorBase(name), PDUSensorBase(name), SingleSensor(name) {}
15

16
PDUSingleSensor::~PDUSingleSensor() {}
17

18
void PDUSingleSensor::init(boost::asio::io_service& io) {
19
20
21
22
	if(_pdu) {
		_pdu->initializeStrand(io);
	} else {
		LOG(error) << "No PDUUnit set for sensor " << _name << "! Cannot initialize sensor.";
23
	}
24
	SingleSensor::init(io);
25
26
}

27
void PDUSingleSensor::start() {
28
29
30
31
32
33
	if (_keepRunning) {
		//we have been started already
		LOG(info) << "Sensor " << _name << " already running.";
		return;
	}

34
	if (_pdu) {
35
		_keepRunning = 1;
36
		_pendingTasks++;
37
		_timer->async_wait(_pdu->getStrand()->wrap(std::bind(&PDUSingleSensor::readAsync, this)));
38
		LOG(info) << "Sensor " << _name << " started.";
39
	} else {
Micha Mueller's avatar
Micha Mueller committed
40
		LOG(error) << "No PDUUnit set for sensor " << _name << "! Cannot start polling.";
41
	}
42
43
}

44
void PDUSingleSensor::stop() {
45
46
47
48
49
	_keepRunning = 0;
	//cancel any outstanding readAsync()
	_timer->cancel();
	LOG(info) << "Sensor " << _name << " stopped.";
}
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

void PDUSingleSensor::read() {
	reading_t reading;
	reading.timestamp = getTimestamp();

	try {
		reading.value = _pdu->readValue(_xmlPath);
		storeReading(reading, _cacheIndex);
		_cacheIndex = (_cacheIndex + 1) % _cacheSize;
#ifdef DEBUG
		LOG(debug) << _pdu->getHost() << "::" << _name << ": \"" << reading.value << "\"";
#endif
	} catch (const std::exception& e) {
		LOG(error) << _pdu->getHost() << "::" << _name << " could not read value: " << e.what();
	}
}

void PDUSingleSensor::readAsync() {
	uint64_t now = getTimestamp();
	read();
	if (_timer != NULL && _keepRunning) {
		uint64_t next = now + MS_TO_NS(_interval);
		_timer->expires_at(timestamp2ptime(next));
		_pendingTasks++;
		_timer->async_wait(_pdu->getStrand()->wrap(std::bind(&PDUSingleSensor::readAsync, this)));
	}
	_pendingTasks--;
}