Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#!/usr/bin/env python
import socket
import json
import datetime
import sys
import MySQLdb
import os
# create database sensors:
#
# create table logs(
# date datetime,
# sensor char(10),
# reading char(12),
# value decimal(5,2),
# ip int unsigned
# )
#
# grant all privileges on table sensors.logs to '***'@'localhost' identified by '***';
# grant select on table sensors.logs to ''@'10.0.0.%';
lastreadings = {}
error = {'humidityDHT11': 4, 'temperatureDHT11':3, 'temperatureDS18B20':10}
while True:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("0.0.0.0",19252))
while True:
data, addr = sock.recvfrom(1024)
res = json.loads(data)
res['ip'] = addr
scale = float(res['scale'])
print ",".join([str(x) for x in datetime.datetime.now(), res['type'], float(res['temperature']) * scale, float(res['humidity']) * scale, addr[0]])
sys.stdout.flush()
db = MySQLdb.connect(host="localhost",
user="***",
passwd="***",
db="sensors")
cur = db.cursor()
vals = {'humidity': -1, 'temperature':-1}
store = True
types = ['humidity', 'temperature']
if res['type'] == 'DS18B20':
types = ['temperature']
for reading in types:
value = float(res[reading]) * scale
vals[reading] = value
if value > 0 and not (res['type'] == 'DS18B20' and value == 85 ):
key = res['type'] + reading + str(addr[0])
if key in lastreadings:
old_value = lastreadings[key]
error_bar = error[reading + res['type']]
if value > old_value +error_bar or value < old_value -error_bar:
store = False
print "Ignoring {} because too high/low from {} [{}]".format(value,old_value,key)
continue
cur.execute("insert into logs values (%s, %s, %s, %s, INET_ATON(%s), %s)",
(datetime.datetime.now(),
res['type'],
reading,value,
str(addr[0]),
int(res['success'])
))
lastreadings[key] = value
else:
store = False
db.commit()
if store:
rrdupdate = "rrdtool update {}-{}.rrd N:{}:{}".format(addr[0], res['type'],vals['humidity'], vals['temperature'])
#print rrdupdate
os.system(rrdupdate)
except KeyboardInterrupt:
raise
except:
print >> sys.stderr, "Error! Restarting" , sys.exc_info()
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment