#include "SensorHistory.h" #include //static const char *TAG = "SensorHistory"; SensorHistory::SensorHistory(const int size) { _size = size; _values = (float*) malloc(_size * sizeof(float)); clear(); } SensorHistory::~SensorHistory() { if (_values != NULL) free(_values); } void SensorHistory::clear(void) { _index = 0; _cnt = 0; for (int i = 0; i < _size; i++) { _values[i] = 0.0; // keeps addValue simpler } } void SensorHistory::addValue(const float value) { if (_values == NULL) return; _values[_index] = value; _index = (_index+1) % _size; if (_cnt < _size) _cnt++; } float SensorHistory::getAverage(void) const { if (_cnt == 0) return NAN; float sum = 0; for (int i = 0; i < _cnt; i++) { sum += _values[i]; } return sum / _cnt; } float SensorHistory::getMin(void) const { if (_cnt == 0) return NAN; float min = _values[0]; for (int i = 0; i < _cnt; i++) { if (_values[i] < min) min = _values[i]; } return min; } float SensorHistory::getMax(void) const { if (_cnt == 0) return NAN; float max = _values[0]; for (int i = 0; i < _cnt; i++) { if (_values[i] > max) max = _values[i]; } return max; } float SensorHistory::getElement(int index) const { if (_cnt == 0) return NAN; index = (_index-1 - index) % _size; if (index < 0) index = _size+index; if (index >= _cnt) return NAN; return _values[index]; } float SensorHistory::getFirst(void) const { if (_cnt < _size) return _values[0]; return getElement(-1); }