SensorGroupTemplate.h 2.48 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
/*
 * SensorGroupTemplate.h
 *
 *  Created on: 03.08.2018
 *      Author: Micha Mueller
 */

#ifndef SENSORGROUPTEMPLATE_H_
#define SENSORGROUPTEMPLATE_H_

11
#include "SensorGroupInterface.h"
12

13
14
15
16
#include "timestamp.h"

#include <vector>

17
18
19
20
21
22
23
24
25
template <typename S>
class SensorGroupTemplate : public SensorGroupInterface {
	//the template shall only be instantiated for classes which derive from SensorBase
	static_assert(std::is_base_of<SensorBase, S>::value, "S must derive from SensorBase!");

public:
	SensorGroupTemplate(const std::string groupName) :
		SensorGroupInterface(groupName) {}

26
27
28
	SensorGroupTemplate(const SensorGroupTemplate& other) :
		SensorGroupInterface(other) {
		for(auto s : other._sensors) {
29
			S* sensor = new S(*s);
30
31
32
33
34
			_sensors.push_back(sensor);
			_baseSensors.push_back(sensor);
		}
	}

35
36
37
38
39
40
	virtual ~SensorGroupTemplate() {
		for(auto s : _sensors) {
			delete s;
		}
	}

41
42
43
44
45
46
47
48
49
	SensorGroupTemplate& operator=(const SensorGroupTemplate& other) {
		SensorGroupInterface::operator=(other);
		for(auto s : _sensors) {
			delete s;
		}
		_sensors.clear();
		_baseSensors.clear();

		for(auto s : other._sensors) {
50
			S* sensor = new S(*s);
51
52
53
54
55
56
57
			_sensors.push_back(sensor);
			_baseSensors.push_back(sensor);
		}

		return *this;
	}

58
59
60
61
62
	virtual void pushBackSensor(SensorBase* s) override {
		if (S* dSensor = dynamic_cast<S*>(s)) {
			_sensors.push_back(dSensor);
			_baseSensors.push_back(s);
		} else {
63
			LOG(warning) << "Group " << _groupName << ": Type mismatch when storing sensor! Sensor omitted";
64
65
66
67
68
69
		}
	}

	virtual std::vector<SensorBase*>& getSensors() override	{ return _baseSensors; }

	virtual void init(boost::asio::io_service& io) {
70
		SensorGroupInterface::init(io);
71
72
73
74
75
76
77

		for(auto s : _sensors) {
			s->initSensor(_cacheSize);
		}
	}

protected:
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
	/** Calculate timestamp for the next reading
	 * @return 	Timestamp in the future to wait for
	 */
	uint64_t nextReadingTime() {
		uint64_t now = getTimestamp();
		uint64_t next;
		if (_sync) {
			uint64_t interval64 = static_cast<uint64_t>(_interval);
			uint64_t now_ms = now / 1000 / 1000;
			uint64_t waitToStart = interval64 - (now_ms%interval64); //synchronize all measurements with other sensors
			if(!waitToStart ){ // less than 1 ms seconds is too small, so we wait the entire interval for the next measurement
					return (now_ms + interval64)*1000*1000;
			}
			return (now_ms + waitToStart)*1000*1000;
		} else {
			return now + MS_TO_NS(_interval);
		}
	}

97
98
99
100
101
	std::vector<S*> _sensors;
	std::vector<SensorBase*> _baseSensors;
};

#endif /* SENSORGROUPTEMPLATE_H_ */