Mercurial > ~darius > hgwebdir.cgi > beermon
annotate beermon.py @ 4:32a56dd33e42
- Reduce hystersis down to 0.5C
- Properly track stale data (hopefully anyway :)
- Check if the monitor thread has died (ie unexpected exception)
- Re-work some variable names to be clearer (& add comments)
author | darius |
---|---|
date | Fri, 28 Sep 2007 13:05:11 +0000 |
parents | 1af7c85d5a0e |
children | 8d471840b153 |
rev | line source |
---|---|
0 | 1 #!/usr/bin/env python |
2 | |
1 | 3 ############################################################################ |
4 # Monitor & control fermenter temperature | |
5 # v1.0 | |
6 # | |
4 | 7 # $Id: beermon.py,v 1.5 2007/09/28 13:05:11 darius Exp $ |
1 | 8 # |
9 # Depends on: Python 2.3 (I think) | |
10 # | |
11 ############################################################################ | |
12 # | |
13 # Copyright (C) 2007 Daniel O'Connor. All rights reserved. | |
14 # | |
15 # Redistribution and use in source and binary forms, with or without | |
16 # modification, are permitted provided that the following conditions | |
17 # are met: | |
18 # 1. Redistributions of source code must retain the above copyright | |
19 # notice, this list of conditions and the following disclaimer. | |
20 # 2. Redistributions in binary form must reproduce the above copyright | |
21 # notice, this list of conditions and the following disclaimer in the | |
22 # documentation and/or other materials provided with the distribution. | |
23 # | |
24 # THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND | |
25 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
26 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
27 # ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE | |
28 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
29 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS | |
30 # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) | |
31 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | |
32 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY | |
33 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF | |
34 # SUCH DAMAGE. | |
35 # | |
36 ############################################################################ | |
37 | |
38 | |
2
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
39 import pexpect, re, threading, time, logging, sys, traceback |
0 | 40 from logging.handlers import RotatingFileHandler |
41 | |
42 class ROMReadError(Exception): | |
43 pass | |
44 | |
4 | 45 class ThreadDied(Exception): |
46 pass | |
47 | |
0 | 48 class Control(): |
49 targetTemp = 18 | |
4 | 50 hysteresis = 0.5 |
0 | 51 pollInterval = 30 |
4 | 52 staleDataTime = 30 |
0 | 53 |
1 | 54 def __init__(self, m, _log): |
0 | 55 self.m = m |
56 global log | |
1 | 57 log = _log |
2
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
58 self.cv = threading.Condition() |
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
59 self.cv.acquire() |
1 | 60 |
0 | 61 def doit(self): |
62 log.debug("target temperature - %3.2f" % (self.targetTemp)) | |
63 log.debug("fermenterId - %s" % (self.m.fermenterId)) | |
64 log.debug("fridgeId - %s" % (self.m.fridgeId)) | |
65 log.debug("ambientId - %s" % (self.m.ambientId)) | |
66 log.debug("minCoolOnTime - %d, minCoolOffTime - %d" % (self.m.minCoolOnTime, self.m.minCoolOffTime)) | |
67 log.debug("minHeatOnTime - %d, minHeatOffTime - %d" % (self.m.minHeatOnTime, self.m.minHeatOffTime)) | |
68 log.debug("pollInterval - %d" % (self.pollInterval)) | |
69 | |
70 log.debug("=== Starting ===") | |
71 log.debug("Fermenter Fridge Ambient State New State") | |
72 while True: | |
4 | 73 # Check if our monitor thread has died |
74 if (not self.m.isAlive()): | |
75 raise ThreadDied, "Monitor thread has died" | |
76 | |
77 # Check for stale data | |
78 if (self.m.lastUpdate[self.m.fermenterId] + self.staleDataTime < time.time()): | |
79 log.debug("Stale data") | |
2
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
80 self.cv.wait(self.pollInterval) |
0 | 81 self.m.setState('idle') |
82 continue | |
83 | |
4 | 84 # Work out what state we should go into |
0 | 85 nextState = "-" |
86 diff = self.m.temps[self.m.fermenterId] - self.targetTemp | |
87 if (self.m.currState == 'idle'): | |
88 # If we're idle then only heat or cool if the temperate difference is out of the | |
4 | 89 # hysteresis band |
0 | 90 if (abs(diff) > self.hysteresis): |
91 if (diff < 0 and self.m.minHeatOffTime + self.m.lastHeatOff < time.time()): | |
92 nextState = 'heat' | |
93 elif (diff > 0 and self.m.minHeatOffTime + self.m.lastHeatOff < time.time()): | |
94 nextState = 'cool' | |
95 elif (self.m.currState == 'cool'): | |
96 # Go idle as soon as we can, there will be overshoot anyway | |
97 if (diff < 0 and self.m.minCoolOnTime + self.m.lastCoolOn < time.time()): | |
98 nextState = 'idle' | |
99 elif (self.m.currState == 'heat'): | |
4 | 100 # Ditto |
0 | 101 if (diff > 0 and self.m.minHeatOnTime + self.m.lastHeatOn < time.time()): |
102 nextState = 'idle' | |
103 else: | |
4 | 104 # Not possible.. |
0 | 105 raise KeyError |
106 | |
107 log.debug("%3.2f %3.2f %3.2f %s %s" % | |
108 (self.m.temps[self.m.fermenterId], | |
109 self.m.temps[self.m.fridgeId], self.m.temps[self.m.ambientId], | |
110 self.m.currState, nextState)) | |
4 | 111 |
0 | 112 if (nextState != "-"): |
113 self.m.setState(nextState) | |
4 | 114 |
2
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
115 self.cv.wait(self.pollInterval) |
0 | 116 |
117 | |
118 class MonitorDev(threading.Thread): | |
119 # Match a ROM ID (eg 00:11:22:33:44:55:66:77) | |
120 romre = re.compile('([0-9a-f]{2}:){7}[0-9a-f]{2}') | |
121 # Match the prompt | |
122 promptre = re.compile('> ') | |
123 | |
124 coolRelay = 7 | |
125 heatRelay = 6 | |
126 | |
127 fermenterId = '10:eb:48:21:01:08:00:df' | |
128 fridgeId = '10:a6:2a:c4:00:08:00:11' | |
129 ambientId = '10:97:1b:fe:00:08:00:d1' | |
130 | |
131 # minimum time the cooler must spend on/off | |
132 minCoolOnTime = 10 * 60 | |
133 minCoolOffTime = 10 * 60 | |
134 | |
135 # minimum time the heater must spend on/off | |
136 minHeatOnTime = 60 | |
137 minHeatOffTime = 60 | |
138 | |
4 | 139 # Dictionary of sensor IDs & temperatures |
0 | 140 temps = {} |
4 | 141 # Dictionary of sensor IDs & epoch times |
142 lastUpdate = {} | |
0 | 143 |
4 | 144 # List of all device IDs |
145 devs = [] | |
146 # List of temperature sensor IDs | |
147 tempdevs = [] | |
148 | |
0 | 149 # Lock to gate access to the comms |
150 commsLock = None | |
151 | |
152 currState = 'idle' | |
153 | |
154 lastHeatOn = 0 | |
155 lastHeatOff = 0 | |
156 lastCoolOn = 0 | |
157 lastCoolOff = 0 | |
158 | |
159 def __init__(self): | |
160 threading.Thread.__init__(self) | |
161 self.commsLock = threading.Lock() | |
162 self.p = pexpect.spawn('/usr/bin/ssh', ['-xt', '-enone', '-i', '/home/darius/.ssh/id_wrt', 'root@wrt', '(echo logged in; microcom -D/dev/cua/1)']) | |
163 assert(self.p.expect('logged in') == 0) | |
164 self.p.timeout = 3 | |
165 self.setspeed() | |
166 self.devs = self.find1wire() | |
4 | 167 self.tempdevs = filter(self.istemp, self.devs) |
0 | 168 |
169 self.start() | |
170 | |
171 def setspeed(self): | |
172 self.commsLock.acquire() | |
173 self.p.send('~') | |
174 assert(self.p.expect('t - set terminal') == 0) | |
175 self.p.send('t') | |
176 assert(self.p.expect('p - set speed') == 0) | |
177 self.p.send('p') | |
178 assert(self.p.expect('f - 38400') == 0) | |
179 self.p.send('f') | |
180 assert(self.p.expect('done!') == 0) | |
181 self.commsLock.release() | |
182 | |
183 def find1wire(self): | |
184 self.commsLock.acquire() | |
185 self.p.sendline('') | |
186 assert(self.p.expect('> ') == 0) | |
187 self.p.sendline('sr') | |
188 # Echo | |
189 assert(self.p.expect('sr') == 0) | |
190 | |
191 # Send a new line which will give us a command prompt to stop on | |
192 # later. We could use read() but that would make the code a lot | |
193 # uglier | |
194 self.p.sendline('') | |
195 | |
196 devlist = [] | |
197 | |
198 # Loop until we get the command prompt (> ) collecting ROM IDs | |
199 while True: | |
200 idx = self.p.expect([self.romre, self.promptre]) | |
201 if (idx == 0): | |
202 # Matched a ROM | |
203 #print "Found ROM " + self.p.match.group() | |
204 devlist.append(self.p.match.group(0)) | |
205 elif (idx == 1): | |
206 # Matched prompt, exit | |
207 break | |
208 else: | |
209 # Unpossible! | |
210 self.commsLock.release() | |
211 raise SystemError() | |
212 | |
213 self.commsLock.release() | |
214 | |
215 return(devlist) | |
216 | |
217 def istemp(self, id): | |
218 [family, a, b, c, d, e, f, g] = id.split(':') | |
219 if (family == '10'): | |
220 return True | |
221 else: | |
222 return False | |
223 | |
224 def updateTemps(self): | |
4 | 225 for i in self.tempdevs: |
226 try: | |
227 self.temps[i] = float(self.readTemp(i)) | |
228 self.lastUpdate[i] = time.time() | |
229 except ROMReadError: | |
230 # Ignore this - just results in no update reflected by lastUpdate | |
231 pass | |
232 | |
0 | 233 return(self.temps) |
234 | |
235 def readTemp(self, id): | |
236 self.commsLock.acquire() | |
237 cmd = 'te ' + id | |
238 self.p.sendline(cmd) | |
239 # Echo | |
240 assert(self.p.expect(cmd) == 0) | |
241 # Eat EOL left from expect | |
242 self.p.readline() | |
243 | |
244 line = self.p.readline().strip() | |
245 self.commsLock.release() | |
246 # 'CRC mismatch' can mean that we picked the wrong ROM.. | |
247 if (re.match('CRC mismatch', line) != None): | |
248 raise ROMReadError | |
249 | |
250 return(line) | |
251 | |
252 def setState(self, state): | |
253 if (state == 'cool'): | |
254 relay = 1 << self.coolRelay | |
255 elif (state == 'heat'): | |
256 relay = 1 << self.heatRelay | |
257 elif (state == 'idle'): | |
258 relay = 0 | |
259 else: | |
260 raise(ValueError) | |
261 | |
262 if (state == self.currState): | |
263 return | |
264 | |
265 # Keep track of when we last turned off or on | |
266 if (state == 'cool'): | |
267 if (self.currState == 'heat'): | |
268 self.lastHeatOff = time.time() | |
269 self.lastCoolOn = time.time() | |
270 elif (state == 'heat'): | |
271 if (self.currState == 'cool'): | |
272 self.lastCoolOff = time.time() | |
273 self.lastHeatOn = time.time() | |
274 else: | |
275 if (self.currState == 'cool'): | |
276 self.lastCoolOff = time.time() | |
277 if (self.currState == 'heat'): | |
278 self.lastHeatOff = time.time() | |
279 | |
280 self.currState = state | |
281 | |
282 self.commsLock.acquire() | |
283 # Need the extra spaces cause the parser in the micro is busted | |
284 cmd = 'out c %02x' % relay | |
285 self.p.sendline(cmd) | |
286 # Echo | |
287 assert(self.p.expect(cmd) == 0) | |
288 self.commsLock.release() | |
289 | |
290 def polltemps(self, temps): | |
291 while True: | |
292 for d in temps: | |
293 #print d | |
294 t = gettemp(p, d) | |
295 print "%s -> %s" % (d, t) | |
296 print | |
297 | |
298 def run(self): | |
299 while True: | |
300 self.updateTemps() | |
301 | |
1 | 302 def initLog(): |
303 # Init our logging | |
304 log = logging.getLogger("monitor") | |
305 | |
306 # Default to warts and all logging | |
307 log.setLevel(logging.DEBUG) | |
308 | |
309 # Log to this file | |
310 logfile = logging.handlers.RotatingFileHandler(filename = "/tmp/beermon.log", | |
311 maxBytes = 1000000, backupCount = 3) | |
312 | |
313 # And stderr | |
314 logstderr = logging.StreamHandler() | |
315 | |
316 # Format it nicely | |
317 formatter = logging.Formatter(fmt = "%(asctime)s: %(message)s", datefmt = "%Y/%m/%d %H:%M:%S") | |
318 | |
319 # Glue it all together | |
320 logfile.setFormatter(formatter) | |
321 logstderr.setFormatter(formatter) | |
322 log.addHandler(logfile) | |
323 log.addHandler(logstderr) | |
324 return(log) | |
325 | |
0 | 326 def main(): |
2
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
327 import beermon |
1 | 328 |
2
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
329 global log |
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
330 log = initLog() |
1 | 331 |
332 log.debug("=== Initing ===") | |
4 | 333 log.debug("$Id: beermon.py,v 1.5 2007/09/28 13:05:11 darius Exp $") |
0 | 334 |
2
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
335 m = None |
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
336 exitCode = 0 |
0 | 337 try: |
2
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
338 m = beermon.MonitorDev() |
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
339 |
1 | 340 c = beermon.Control(m, log) |
0 | 341 # Wait for the first temperature readings to come through, saves |
342 # getting an 'invalid data' message | |
343 time.sleep(3) | |
344 c.doit() | |
345 log.debug("doit exited") | |
346 | |
347 except KeyboardInterrupt: | |
348 log.debug("Exiting due to keyboard interrupt") | |
1 | 349 |
2
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
350 except Exception, e: |
3 | 351 log.debug("Something went wrong, details below:") |
2
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
352 log.debug(e) |
3 | 353 log.debug(reduce(lambda x, y: x + y, traceback.format_exception( |
354 sys.exc_type, sys.exc_value, sys.exc_traceback))) | |
2
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
355 exitCode = 1 |
0 | 356 |
357 finally: | |
358 # Make sure we try and turn it off if something goes wrong | |
2
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
359 if (m != None): |
17bc5535bbb7
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
1
diff
changeset
|
360 m.setState('idle') |
0 | 361 |
1 | 362 sys.exit(exitCode) |
0 | 363 |
364 if __name__ == "__main__": | |
365 main() |