/* * SensorBase.h * * Created on: 09.08.2018 * Author: Micha Mueller */ #ifndef SRC_SENSORBASE_H_ #define SRC_SENSORBASE_H_ #include #include #include typedef struct { uint64_t value; uint64_t timestamp; } reading_t; class SensorBase { public: static const size_t QUEUE_MAXLIMIT=1024; SensorBase(const std::string& name) : _name(name), _mqtt(""), _cacheIndex(0), _cache(nullptr), _readingQueue(nullptr) { _latestValue.timestamp = 0; _latestValue.value = 0; } SensorBase(const SensorBase& other) : _name(other._name), _mqtt(other._mqtt), _cacheIndex(0), _cache(nullptr), _latestValue(other._latestValue), _readingQueue(nullptr) {} virtual ~SensorBase() {} SensorBase& operator=(const SensorBase& other) { _name = other._name; _mqtt = other._mqtt; _cacheIndex = 0; _cache.reset(nullptr); _latestValue.timestamp = other._latestValue.timestamp; _latestValue.value = other._latestValue.value; _readingQueue.reset(nullptr); return *this; } const std::string& getName() const { return _name; } const std::string& getMqtt() const { return _mqtt; } const reading_t * const getCache() const { return _cache.get(); } const reading_t getLatestValue() const { return _latestValue; } /*TODO return reference*/ 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.reset(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.reset(new boost::lockfree::spsc_queue(QUEUE_MAXLIMIT)); } } virtual void storeReading(reading_t reading, unsigned int cacheSize) { _readingQueue->push(reading); _cache[_cacheIndex] = reading; _cacheIndex = (_cacheIndex + 1) % cacheSize; _latestValue.value = reading.value; _latestValue.timestamp = reading.timestamp; } protected: std::string _name; std::string _mqtt; unsigned int _cacheIndex; std::unique_ptr _cache; reading_t _latestValue; std::unique_ptr> _readingQueue; }; #endif /* SRC_SENSORBASE_H_ */