Skip to content

Instantly share code, notes, and snippets.

@sorz
Created December 22, 2015 09:06
Show Gist options
  • Save sorz/516f6fb8b81fcb99225a to your computer and use it in GitHub Desktop.
Save sorz/516f6fb8b81fcb99225a to your computer and use it in GitHub Desktop.
#!/usr/bin/bash
DIR=/path/to/www/public
DATA=/path/to/pms5003.rrd
TIME=$1
time=$(date '+%H\:%M\:%S')
rrdtool graph $DIR/pm-$TIME.svg \
--imgformat SVG \
--start end-$TIME \
--title "Particle Pollution Statistics - $TIME (µg/m³)" \
DEF:pm10=$DATA:pm10:AVERAGE \
DEF:pm25=$DATA:pm25:AVERAGE \
DEF:pm100=$DATA:pm100:AVERAGE \
LINE1:pm10#0084a4:"PM₁.₀" \
LINE1:pm25#d85427:"PM₂.₅" \
LINE1:pm100#676767:"PM₁₀" \
VDEF:avg25=pm25,AVERAGE \
VDEF:max25=pm25,MAXIMUM \
VDEF:min25=pm25,MINIMUM \
VDEF:now25=pm25,LAST \
COMMENT:" (updated on $time)" \
GPRINT:avg25:"avg\: %2.0lf µg/m³" \
GPRINT:max25:"max\: %2.0lf µg/m³" \
GPRINT:min25:"min\: %2.0lf µg/m³" \
GPRINT:now25:"cur\: %2.0lf µg/m³"
#!/usr/bin/env python3
from subprocess import call
from struct import unpack
from serial import Serial
RRDTOOL = '/usr/bin/rrdtool'
RRDCACHE = '/tmp/rrdcached.sock'
DB_PATH = '/path/to/pms5003.rrd'
FORMAT = 'N:%d:%d:%d'
def read_once(ser):
if ser.read() != b'\x42' or ser.read() != b'\x4d':
return
if ser.read(2) != b'\x00\x1c':
return
raw = ser.read(2 * 13 + 2)
values = unpack('>HHHHHHHHHHHH', raw[:-4])
checksum, = unpack('>H', raw[-2:])
if checksum != sum(b'\x42\x4d\x1c' + raw[:-2]):
return
return values
def feed_to_rrdtool(values):
args = FORMAT % values
#code = call([RRDTOOL, 'update', '-d', RRDCACHE, DB_PATH, args])
code = call([RRDTOOL, 'update', DB_PATH, args])
if code != 0:
print('rrdtool update failed')
def main():
ser = Serial('/dev/ttyUSB0', 9600)
while True:
values = read_once(ser)
if values is None:
continue
pms = values[:3]
#print(pms)
feed_to_rrdtool(pms)
if __name__ == '__main__':
main()
#!/bin/bash
rrdtool create pms5003.rrd \
--step 1 \
DS:pm10:GAUGE:10:0:1000 \
DS:pm25:GAUGE:10:0:1000 \
DS:pm100:GAUGE:10:0:1000 \
RRA:AVERAGE:0.1:10:17280 \
RRA:AVERAGE:0.5:60:43200 \
RRA:AVERAGE:0.5:300:105120
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment