Skip to content

Commit c79afb4

Browse files
committed
Raingauge example
1 parent dbe24a8 commit c79afb4

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

examples/raingauge.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Calculating interval deltas for a rain gauge (and other counters)
2+
3+
This script calculates deltas on each value from my rain gauge. The gauge behaves in the following way:
4+
- if it rained a certain amount (0.45mm), a counter is increased and the total value is sent via mqtt
5+
- the total value is also published every 30 seconds
6+
- if the device is restarted, the total value starts at zero
7+
- the topic where the total value is published is /sensor/SENSORID/rain
8+
9+
This script calculates the delta between two total value changes and handles some special situations:
10+
- a zero delta is ignored (so no unnecessary updates if it's not raining)
11+
- a delta is ignored when its negative (that happens when the device is restarted)
12+
- a delta is ignored when the previous value is more than 10 minutes old (happens when the script did not run for a while, so the rain cannot be assigned to the correct timestamp)
13+
- a delta is ignored when it's >10mm (that should not happen because a delta should be sent every 0.45mm or at least every 30 seconds - it's just a sanity check)
14+
15+
The result is published via /sensor/SENSORID/rainDelta and can directly be stored to a time series database and then aggregated.
16+
17+
This script can easily be used/modified to do the same calculations for any kind of counter that runs over or is reset from time to time.
18+
19+
The script:
20+
21+
```javascript
22+
subscribe('sensor/+/rain', function (topic,val,obj,prev,msg) {
23+
var sensorId=topic.split("/")[1]
24+
var lastValueTopic='sensor/'+sensorId+'/rainLastValue';
25+
var oldValue=getValue(lastValueTopic)
26+
if (oldValue!==undefined) {
27+
var delta=Math.round((val-oldValue.v)*1000)/1000;
28+
29+
if (now()-oldValue.t>1800000) {
30+
log.info("sensor ",sensorId,", delta ",delta,"- delta older than 30 minutes ignored");
31+
} else if (delta<0) {
32+
log.info("sensor ",sensorId,", delta ",delta,"- negative delta ignored");
33+
} else if (delta>10) {
34+
log.info("sensor ",sensorId,", delta ",delta,"- very large delta ignored");
35+
} else if (delta==0) {
36+
log.debug("sensor ",sensorId,", delta ",delta,"- zero delta ignored");
37+
} else {
38+
log.debug("sensor ",sensorId,", delta ",delta);
39+
publish('sensor/'+sensorId+'/rainDelta',delta);
40+
}
41+
}
42+
publish(lastValueTopic,{v:val,t:now()},{retain:true});
43+
});
44+
```

0 commit comments

Comments
 (0)