/
sensor_ds18b20.py
66 lines (54 loc) · 1.96 KB
/
sensor_ds18b20.py
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
#!/usr/bin/env python2.7
import gevent
import gevent.threadpool
import config
import re
from utils import L,W,E,EX
class DS18B20s(gevent.Greenlet):
THERM_RE = re.compile('.* YES\n.*t=(.*)\n', re.MULTILINE)
def __init__(self, server):
gevent.Greenlet.__init__(self)
self.server = server
self.readthread = gevent.threadpool.ThreadPool(1)
self.master_dir = config.SENSOR_BASE_DIR
def _run(self):
while True:
self.do()
gevent.sleep(config.SENSOR_SLEEP)
def read_wait(self, f):
# handles a blocking file read with a gevent threadpool. A
# real python thread performs the read while other gevent
# greenlets keep running.
# the ds18b20 takes ~750ms to read, which is noticable
# interactively.
return self.readthread.apply(lambda: f.read)
def do_sensor(self, s, contents = None):
""" contents can be set by the caller for testing """
try:
if contents is None:
fn = os.path.join(self.master_dir, s, 'w1_slave')
f = open(fn, 'r')
contents = self.read_wait(f)
match = self.THERM_RE.match(contents)
if match is None:
return None
temp = int(match.groups(1)[0])
return temp / 1000.0
except Exception, e:
EX("Problem reading sensor '%s': %s" % (s, str(e)))
return None
def do(self):
vals = {}
for n in self.sensor_names():
value = do_sensor(n)
if value is not None:
vals[n] = value
self.server.add_reading(vals)
def sensor_names(self):
""" Returns a sequence of sensorname """
slaves_path = os.path.join(self.master_dir, "w1_master_slaves")
return open(slaves_path, 'r').split()
def wort_name(self):
return config.WORT_NAME
def fridge_name(self):
return config.FRIDGE_NAME