439
|
1 #!/usr/bin/env python2.7 |
|
2 |
443
|
3 import gevent |
447
|
4 import gevent.threadpool |
443
|
5 import config |
|
6 import re |
|
7 from utils import L,W,E,EX |
|
8 |
|
9 class DS18B20s(gevent.Greenlet): |
|
10 |
|
11 THERM_RE = re.compile('.* YES\n.*t=(.*)\n', re.MULTILINE) |
439
|
12 |
443
|
13 def __init__(self, server): |
|
14 gevent.Greenlet.__init__(self) |
|
15 self.server = server |
447
|
16 self.readthread = gevent.threadpool.ThreadPool(1) |
|
17 self.master_dir = config.SENSOR_BASE_DIR |
443
|
18 |
|
19 def _run(self): |
|
20 while True: |
|
21 self.do() |
|
22 gevent.sleep(config.SENSOR_SLEEP) |
|
23 |
447
|
24 def read_wait(self, f): |
|
25 # handles a blocking file read with a gevent threadpool. A |
|
26 # real python thread performs the read while other gevent |
|
27 # greenlets keep running. |
|
28 # the ds18b20 takes ~750ms to read, which is noticable |
|
29 # interactively. |
|
30 return self.readthread.apply(lambda: f.read) |
439
|
31 |
447
|
32 def do_sensor(self, s, contents = None): |
|
33 """ contents can be set by the caller for testing """ |
443
|
34 try: |
|
35 if contents is None: |
447
|
36 fn = os.path.join(self.master_dir, s, 'w1_slave') |
443
|
37 f = open(fn, 'r') |
447
|
38 contents = self.read_wait(f) |
443
|
39 match = self.THERM_RE.match(contents) |
|
40 if match is None: |
|
41 return None |
|
42 temp = int(match.groups(1)[0]) |
|
43 return temp / 1000.0 |
|
44 except Exception, e: |
|
45 EX("Problem reading sensor '%s': %s" % (s, str(e))) |
|
46 return None |
439
|
47 |
443
|
48 def do(self): |
|
49 vals = {} |
|
50 for n in self.sensor_names(): |
|
51 value = do_sensor(n) |
|
52 if value is not None: |
|
53 vals[n] = value |
|
54 |
|
55 self.server.add_reading(vals) |
|
56 |
|
57 def sensor_names(self): |
|
58 """ Returns a sequence of sensorname """ |
447
|
59 slaves_path = os.path.join(self.master_dir, "w1_master_slaves") |
|
60 return open(slaves_path, 'r').split() |
439
|
61 |
|
62 def wort_name(self): |
443
|
63 return config.WORT_NAME |
439
|
64 |
|
65 def fridge_name(self): |
443
|
66 return config.FRIDGE_NAME |