sensorcache.cpp 2.06 KB
Newer Older
1
2
3
4
5
6
7
8
/*
 * SensorCache.cpp
 *
 *  Created on: 3 Aug 2016
 *      Author: ottmi
 */

#include "sensorcache.h"
9
#include "messaging.h"
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

#include <exception>
#include <iostream>
namespace DCDB {

SensorCache::SensorCache() {
	// TODO Auto-generated constructor stub

}

SensorCache::~SensorCache() {
	// TODO Auto-generated destructor stub
}

void SensorCache::storeSensor(SensorId sid, uint64_t ts, uint64_t val) {
25
26
	cacheEntry_t e;

27
28
	/* Remove the reserved bytes to leverage the standard find function */
	sid.setRsvd(0);
29
30
31
32
33
34
35
36
37
38
39
40
	sensorCache_t::iterator it = sensorCache.find(sid);
	if (it != sensorCache.end()) {
		e = it->second;
		e.deltaT.push_back((ts - e.timestamp)/1000000);
		if (e.deltaT.size() > 5) {
			e.deltaT.pop_front();
		}
	}

	e.val = val;
	e.timestamp = ts;

41
42
43
44
45
46
47
48
49
	sensorCache[sid] = e;
}

uint64_t SensorCache::getSensor(SensorId sid) {
	/* Remove the reserved bytes to leverage the standard find function */
	sid.setRsvd(0);
	sensorCache_t::iterator it = sensorCache.find(sid);

	if (it == sensorCache.end()) {
50
51
52
53
54
55
56
57
58
59
60
61
62
		throw std::invalid_argument("Sid not found");
	}

	if (it->second.deltaT.size()) {
		uint64_t ts = Messaging::calculateTimestamp() / 1000000;
		uint64_t avg = 0;
		for (std::list<uint32_t>::iterator dt = it->second.deltaT.begin(); dt !=  it->second.deltaT.end(); dt++) {
			avg+= *dt;
		}
		avg/= it->second.deltaT.size();
		if ((ts - it->second.timestamp) > 5 * avg) {
			throw std::out_of_range("Sid outdated");
		}
63
64
	}

65
	return it->second.val;
66
67
68
69
70
71
72
}

void SensorCache::dump() {
	sensorCache_t::iterator it;

	std::cout << "SensorCache Dump:" << std::endl;
	for (it = sensorCache.begin(); it != sensorCache.end(); it++) {
73
74
75
76
77
78
79
80
81
82
83
		std::cout << "  id=" << it->first.toString() << " val=" << it->second.val << " ts=" << it->second.timestamp;
		if (it->second.deltaT.size()) {
			uint64_t avg = 0;
			std::cout <<  " deltaT=[";
			for (std::list<uint32_t>::iterator dt = it->second.deltaT.begin(); dt !=  it->second.deltaT.end(); dt++) {
				avg+= *dt;
				std::cout << " " << *dt;
			}
			std::cout << "] avg=" << avg/it->second.deltaT.size();
		}
		std::cout << std::endl;
84
85
86
87
	}
}

} /* namespace DCDB */