-
Notifications
You must be signed in to change notification settings - Fork 0
/
WaterMeter.cpp
76 lines (62 loc) · 1.92 KB
/
WaterMeter.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
69
70
71
72
73
74
75
#define LIBCALL_ENABLEINTERRUPT
#include <EnableInterrupt.h>
#define LIBCALL_DEEP_SLEEP_SCHEDULER
#include <DeepSleepScheduler.h> // https://github.com/PRosenb/DeepSleepScheduler
#include "WaterMeter.h"
volatile unsigned int WaterMeter::samplesInInterval;
volatile unsigned long WaterMeter::totalPulseCount;
volatile unsigned long WaterMeter::lastPulseCount;
volatile unsigned int WaterMeter::lastPulseCountOverThreshold;
volatile Runnable *WaterMeter::listener;
WaterMeter::WaterMeter(const unsigned long invervalMs) {
pinMode(WATER_METER_PIN, INPUT_PULLUP);
MsTimer2::set(invervalMs, WaterMeter::isrTimer);
totalPulseCount = 0;
lastPulseCountOverThreshold = 0;
started = false;
}
WaterMeter::~WaterMeter() {
}
void WaterMeter::start() {
if (!started) {
started = true;
scheduler.acquireNoSleepLock();
enableInterrupt(WATER_METER_PIN, WaterMeter::isrWaterMeterPulses, FALLING);
if (thresholdSupervisionDelay == 0) {
lastPulseCount = totalPulseCount;
MsTimer2::start();
} else {
scheduler.scheduleDelayed(this, thresholdSupervisionDelay);
}
}
}
void WaterMeter::stop() {
if (started) {
started = false;
MsTimer2::stop();
disableInterrupt(WATER_METER_PIN);
scheduler.releaseNoSleepLock();
scheduler.removeCallbacks(this);
}
}
void WaterMeter::run() {
if (started) {
lastPulseCount = totalPulseCount;
MsTimer2::start();
}
}
void WaterMeter::setThresholdListener(const unsigned int samplesInInterval, Runnable *listener) {
WaterMeter::samplesInInterval = samplesInInterval;
WaterMeter::listener = listener;
}
void WaterMeter::isrWaterMeterPulses() {
totalPulseCount++;
}
void WaterMeter::isrTimer() {
unsigned int pulsesCount = totalPulseCount - lastPulseCount;
lastPulseCount = totalPulseCount;
if (listener != NULL && pulsesCount >= samplesInInterval) {
lastPulseCountOverThreshold = pulsesCount;
scheduler.schedule((Runnable*) listener);
}
}