SysfsSensor.cpp 2.17 KB
Newer Older
1
2
3
4
/*
 * SYSFSSensor.cpp
 *
 *  Created on: 18.11.2017
5
 *      Author: Michael Ott (original), Micha Mueller
6
7
 */

8
#include "SysfsSensor.h"
9
10
11
12
13
#include "timestamp.h"
#include <functional>

using namespace std;

14
15
SysfsSensor::SysfsSensor(const std::string& name) :
	Sensor(name) {
16
17
18
19
20
21
22
	_path = "";
	_file = NULL;
	_filter = false;
	//_regx = "";
	_substitution = "";
}

23
SysfsSensor::~SysfsSensor() {
24
	// TODO Auto-generated destructor stub
25
26
}

27
void SysfsSensor::read() {
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
	reading_t reading;
	char buf[1024];

	reading.timestamp = getTimestamp();

	fseek(_file, 0, SEEK_SET);
	size_t nelem = fread(buf, 1, 1024, _file);
	if (nelem) {
		buf[nelem-1] = 0;

		try {
			//filter the payload if necessary
			if(_filter) {
				//substitution must have sed format
				//if no substitution is defined the whole regex-match is copied as is.
				//parts which do not match are not copied --> filter
				reading.value = stoll(regex_replace(buf, _regx, _substitution, regex_constants::format_sed | regex_constants::format_no_copy));
			} else {
				reading.value = stoll(buf);
			}
		} catch (const std::exception& e) {
#ifdef DEBUG
Micha Mueller's avatar
Micha Mueller committed
50
			LOG(warning) << "SysfsSensor " << _name << " could not read value!";
51
52
53
54
55
#endif
			return;
		}

#ifdef DEBUG
Micha Mueller's avatar
Micha Mueller committed
56
		LOG(debug) << _name << ": \"" << reading.value << "\"";
57
58
59
60
61
#endif
	}
	_readingQueue->push(reading);
}

62
void SysfsSensor::readAsync() {
63
64
	uint64_t now = getTimestamp();
	read();
65
	if (_timer != NULL && _keepRunning) {
66
67
		uint64_t next = now + MS_TO_NS(_interval);
		_timer->expires_at(timestamp2ptime(next));
68
		_timer->async_wait(std::bind(&SysfsSensor::readAsync, this));
69
70
71
	}
}

72
void SysfsSensor::startPolling() {
73
74
75
	if(_file == NULL) {
		_file = fopen(_path.c_str(), "r");
		if (_file == NULL) {
76
			LOG(error) << "Error starting sensor \"" << _name << "\": " << strerror(errno);
77
78
79
			return;
		}
	}
80
81

	_keepRunning = 1;
82
	_timer->async_wait(std::bind(&SysfsSensor::readAsync, this));
83
84
85
86
87
88
89
90
91
92
93
94
95
96
	LOG(info) << "Sensor " << _name << " started.";
}

void SysfsSensor::stopPolling() {
	_keepRunning = 0;
	//cancel any outstanding readAsync()
	_timer->cancel();
	//wait until read() finished before closing _file
	_timer->wait();
	if (_file != NULL) {
		fclose(_file);
		_file = NULL;
	}
	LOG(info) << "Sensor " << _name << " stopped.";
97
}