SensorBase.h 2.51 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
/*
 * SensorBase.h
 *
 *  Created on: 09.08.2018
 *      Author: Micha Mueller
 */

#ifndef SRC_SENSORBASE_H_
#define SRC_SENSORBASE_H_

11
#include <memory>
12
13
14
15
16
17
18
19
20
21
#include <string>
#include <boost/lockfree/spsc_queue.hpp>

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

class SensorBase {
public:
lu43jih's avatar
lu43jih committed
22
23
	static const size_t QUEUE_MAXLIMIT=1024;

24
25
	SensorBase(const std::string& name) :
		_name(name),
26
27
28
		_mqtt(""),
		_cache(nullptr),
		_readingQueue(nullptr) {
29
30
31
32
33

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

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
	SensorBase(const SensorBase& other) :
		_name(other._name),
		_mqtt(other._mqtt),
		_cache(nullptr),
		_latestValue(other._latestValue),
		_readingQueue(nullptr) {}

	virtual ~SensorBase() {}

	SensorBase& operator=(const SensorBase& other) {
		_name = other._name;
		_mqtt = other._mqtt;
		_cache.reset(nullptr);
		_latestValue.timestamp	= other._latestValue.timestamp;
		_latestValue.value		= other._latestValue.value;
		_readingQueue.reset(nullptr);

		return *this;
52
53
54
55
	}

	const std::string& 		getName() 			const	{ return _name; }
	const std::string&		getMqtt() 			const	{ return _mqtt; }
56
	const reading_t * const	getCache() 			const	{ return _cache.get(); }
57
58
59
60
	const reading_t			getLatestValue()	const	{ return _latestValue; }

	void				setName(const std::string& name)	{ _name = name; }
	void				setMqtt(const std::string& mqtt)	{ _mqtt = mqtt; }
61
	void 				setLatestValue(const reading_t& latestValue) { _latestValue = latestValue; }
62
63
64
65
66
67
68

	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) {
69
			_cache.reset(new reading_t[cacheSize]);
70
71
72
73
74
			for(unsigned i = 0; i < cacheSize; i++) {
				_cache[i] = _latestValue;	//_latestValue should equal (0,0) at this point
			}
		}
		if(!_readingQueue) {
lu43jih's avatar
lu43jih committed
75
			_readingQueue.reset(new boost::lockfree::spsc_queue<reading_t>(QUEUE_MAXLIMIT));
76
77
78
79
80
81
82
83
84
85
		}
	}

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

86
87


88
89
90
91
protected:

	std::string _name;
	std::string _mqtt;
92
	std::unique_ptr<reading_t[]> _cache;
93
	reading_t _latestValue;
94
	std::unique_ptr<boost::lockfree::spsc_queue<reading_t>> _readingQueue;
95
96
97
};

#endif /* SRC_SENSORBASE_H_ */