SensorBase.h 1.96 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
78
79
80
81
/*
 * SensorBase.h
 *
 *  Created on: 09.08.2018
 *      Author: Micha Mueller
 */

#ifndef SRC_SENSORBASE_H_
#define SRC_SENSORBASE_H_

#include <string>
#include <boost/lockfree/spsc_queue.hpp>

typedef struct {
	uint64_t value;
	uint64_t timestamp;
} reading_t;

class SensorBase {
public:
	SensorBase(const std::string& name) :
		_name(name),
		_mqtt("") {

		_latestValue.timestamp	= 0;
		_latestValue.value		= 0;

		_cache = NULL;
		_readingQueue = NULL;
	}

	virtual ~SensorBase() {
		if (_cache) {
			delete[] _cache;
		}
		if (_readingQueue) {
			delete _readingQueue;
		}
	}

	const std::string& 		getName() 			const	{ return _name; }
	const std::string&		getMqtt() 			const	{ return _mqtt; }
	const reading_t * const	getCache() 			const	{ return _cache; }
	const reading_t			getLatestValue()	const	{ return _latestValue; }

	void				setName(const std::string& name)	{ _name = name; }
	void				setMqtt(const std::string& mqtt)	{ _mqtt = mqtt; }

	const std::size_t	getSizeOfReadingQueue() const { return _readingQueue->read_available(); }
	std::size_t 		popReadingQueue(reading_t *reads, std::size_t max) const	{ return _readingQueue->pop(reads, max); }
	void				pushReadingQueue(reading_t *reads, std::size_t count) const	{ _readingQueue->push(reads, count); }

	void initSensor(unsigned cacheSize) {
		if(!_cache) {
			_cache = new reading_t[cacheSize];
			for(unsigned i = 0; i < cacheSize; i++) {
				_cache[i] = _latestValue;	//_latestValue should equal (0,0) at this point
			}
		}
		if(!_readingQueue) {
			_readingQueue = new boost::lockfree::spsc_queue<reading_t>(1024);
		}
	}

	virtual void storeReading(reading_t reading, unsigned cacheIndex) {
		_readingQueue->push(reading);
		_cache[cacheIndex] = reading;
		_latestValue.value = reading.value;
		_latestValue.timestamp = reading.timestamp;
	}

protected:

	std::string _name;
	std::string _mqtt;
	reading_t * _cache;
	reading_t _latestValue;
	boost::lockfree::spsc_queue<reading_t>* _readingQueue;
};

#endif /* SRC_SENSORBASE_H_ */