-
Notifications
You must be signed in to change notification settings - Fork 6
/
counter.cpp
69 lines (56 loc) · 1.26 KB
/
counter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Handles accumulation of measurement values.
*/
#include "counter.h"
typedef struct {
double integrated;
uint32_t last_time;
float last_value;
} TIntegrator;
static TIntegrator charge;
static TIntegrator energy;
/* performs basic trapezoid integration */
static void integrate(TIntegrator *state, uint32_t timestamp, float value)
{
float average = (value + state->last_value) / 2;
float sum = average * (timestamp - state->last_time) * 1E-6;
state->integrated += sum;
state->last_time = timestamp;
state->last_value = value;
}
/**
* Initialises the counter system.
*/
void CounterInit(void)
{
charge.integrated = 0;
charge.last_time = 0;
charge.last_value = 0;
energy.integrated = 0;
energy.last_time = 0;
energy.last_value = 0;
}
void CounterChargeReset(void)
{
charge.integrated = 0;
}
void CounterChargeUpdate(uint32_t timestamp, float current)
{
integrate(&charge, timestamp, current);
}
double CounterChargeGet(void)
{
return charge.integrated;
}
void CounterEnergyReset(void)
{
energy.integrated = 0;
}
void CounterEnergyUpdate(uint32_t timestamp, float power)
{
integrate(&energy, timestamp, power);
}
double CounterEnergyGet(void)
{
return energy.integrated;
}