Mercurial > ~darius > hgwebdir.cgi > beermon.old
annotate beermon.py @ 4:618372f83862
Wait on a condition var instead of using time.sleep() - this works
better with signals in a multithreaded environment (ie the signal will
interrupt the wait)
A few other misc tidy ups.
author | darius |
---|---|
date | Mon, 24 Sep 2007 13:31:15 +0000 |
parents | f197f6716cd6 |
children | dba51b33fd9e |
rev | line source |
---|---|
1 | 1 #!/usr/bin/env python |
2 | |
3 | 3 ############################################################################ |
4 # Monitor & control fermenter temperature | |
5 # v1.0 | |
6 # | |
4
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
7 # $Id: beermon.py,v 1.3 2007/09/24 13:31:15 darius Exp $ |
3 | 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 | |
4
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
39 import pexpect, re, threading, time, logging, sys, traceback |
1 | 40 from logging.handlers import RotatingFileHandler |
41 | |
42 class ROMReadError(Exception): | |
43 pass | |
44 | |
45 class Control(): | |
46 targetTemp = 18 | |
3 | 47 hysteresis = 1 |
1 | 48 pollInterval = 30 |
49 | |
3 | 50 def __init__(self, m, _log): |
1 | 51 self.m = m |
52 global log | |
3 | 53 log = _log |
4
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
54 self.cv = threading.Condition() |
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
55 self.cv.acquire() |
3 | 56 |
1 | 57 def doit(self): |
58 log.debug("target temperature - %3.2f" % (self.targetTemp)) | |
59 log.debug("fermenterId - %s" % (self.m.fermenterId)) | |
60 log.debug("fridgeId - %s" % (self.m.fridgeId)) | |
61 log.debug("ambientId - %s" % (self.m.ambientId)) | |
62 log.debug("minCoolOnTime - %d, minCoolOffTime - %d" % (self.m.minCoolOnTime, self.m.minCoolOffTime)) | |
63 log.debug("minHeatOnTime - %d, minHeatOffTime - %d" % (self.m.minHeatOnTime, self.m.minHeatOffTime)) | |
64 log.debug("pollInterval - %d" % (self.pollInterval)) | |
65 | |
66 log.debug("=== Starting ===") | |
67 log.debug("Fermenter Fridge Ambient State New State") | |
68 while True: | |
69 if (self.m.lastUpdate == 0): | |
4
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
70 log.debug("Invalid data") |
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
71 self.cv.wait(self.pollInterval) |
1 | 72 self.m.setState('idle') |
73 continue | |
74 | |
75 nextState = "-" | |
76 | |
77 diff = self.m.temps[self.m.fermenterId] - self.targetTemp | |
78 if (self.m.currState == 'idle'): | |
79 # If we're idle then only heat or cool if the temperate difference is out of the | |
80 # hysteresis range | |
81 if (abs(diff) > self.hysteresis): | |
82 if (diff < 0 and self.m.minHeatOffTime + self.m.lastHeatOff < time.time()): | |
83 nextState = 'heat' | |
84 elif (diff > 0 and self.m.minHeatOffTime + self.m.lastHeatOff < time.time()): | |
85 nextState = 'cool' | |
86 elif (self.m.currState == 'cool'): | |
87 # Go idle as soon as we can, there will be overshoot anyway | |
88 if (diff < 0 and self.m.minCoolOnTime + self.m.lastCoolOn < time.time()): | |
89 nextState = 'idle' | |
90 elif (self.m.currState == 'heat'): | |
91 if (diff > 0 and self.m.minHeatOnTime + self.m.lastHeatOn < time.time()): | |
92 nextState = 'idle' | |
93 else: | |
94 raise KeyError | |
95 | |
96 log.debug("%3.2f %3.2f %3.2f %s %s" % | |
97 (self.m.temps[self.m.fermenterId], | |
98 self.m.temps[self.m.fridgeId], self.m.temps[self.m.ambientId], | |
99 self.m.currState, nextState)) | |
100 if (nextState != "-"): | |
101 self.m.setState(nextState) | |
102 | |
4
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
103 self.cv.wait(self.pollInterval) |
1 | 104 |
105 | |
106 class MonitorDev(threading.Thread): | |
107 # Match a ROM ID (eg 00:11:22:33:44:55:66:77) | |
108 romre = re.compile('([0-9a-f]{2}:){7}[0-9a-f]{2}') | |
109 # Match the prompt | |
110 promptre = re.compile('> ') | |
111 | |
112 coolRelay = 7 | |
113 heatRelay = 6 | |
114 | |
115 fermenterId = '10:eb:48:21:01:08:00:df' | |
116 fridgeId = '10:a6:2a:c4:00:08:00:11' | |
117 ambientId = '10:97:1b:fe:00:08:00:d1' | |
118 | |
119 # minimum time the cooler must spend on/off | |
120 minCoolOnTime = 10 * 60 | |
121 minCoolOffTime = 10 * 60 | |
122 | |
123 # minimum time the heater must spend on/off | |
124 minHeatOnTime = 60 | |
125 minHeatOffTime = 60 | |
126 | |
127 temps = {} | |
128 lastUpdate = 0 | |
129 | |
130 # Lock to gate access to the comms | |
131 commsLock = None | |
132 | |
133 currState = 'idle' | |
134 | |
135 lastHeatOn = 0 | |
136 lastHeatOff = 0 | |
137 lastCoolOn = 0 | |
138 lastCoolOff = 0 | |
139 | |
140 def __init__(self): | |
141 threading.Thread.__init__(self) | |
142 self.commsLock = threading.Lock() | |
143 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)']) | |
144 assert(self.p.expect('logged in') == 0) | |
145 self.p.timeout = 3 | |
146 self.setspeed() | |
147 self.devs = self.find1wire() | |
148 self.temps = filter(self.istemp, self.devs) | |
149 | |
150 self.start() | |
151 | |
152 def setspeed(self): | |
153 self.commsLock.acquire() | |
154 self.p.send('~') | |
155 assert(self.p.expect('t - set terminal') == 0) | |
156 self.p.send('t') | |
157 assert(self.p.expect('p - set speed') == 0) | |
158 self.p.send('p') | |
159 assert(self.p.expect('f - 38400') == 0) | |
160 self.p.send('f') | |
161 assert(self.p.expect('done!') == 0) | |
162 self.commsLock.release() | |
163 | |
164 def find1wire(self): | |
165 self.commsLock.acquire() | |
166 self.p.sendline('') | |
167 assert(self.p.expect('> ') == 0) | |
168 self.p.sendline('sr') | |
169 # Echo | |
170 assert(self.p.expect('sr') == 0) | |
171 | |
172 # Send a new line which will give us a command prompt to stop on | |
173 # later. We could use read() but that would make the code a lot | |
174 # uglier | |
175 self.p.sendline('') | |
176 | |
177 devlist = [] | |
178 | |
179 # Loop until we get the command prompt (> ) collecting ROM IDs | |
180 while True: | |
181 idx = self.p.expect([self.romre, self.promptre]) | |
182 if (idx == 0): | |
183 # Matched a ROM | |
184 #print "Found ROM " + self.p.match.group() | |
185 devlist.append(self.p.match.group(0)) | |
186 elif (idx == 1): | |
187 # Matched prompt, exit | |
188 break | |
189 else: | |
190 # Unpossible! | |
191 self.commsLock.release() | |
192 raise SystemError() | |
193 | |
194 self.commsLock.release() | |
195 | |
196 return(devlist) | |
197 | |
198 def istemp(self, id): | |
199 [family, a, b, c, d, e, f, g] = id.split(':') | |
200 if (family == '10'): | |
201 return True | |
202 else: | |
203 return False | |
204 | |
205 def updateTemps(self): | |
206 tmp = {} | |
207 for i in self.temps: | |
208 tmp[i] = float(self.readTemp(i)) | |
209 | |
210 self.temps = tmp | |
211 self.lastUpdate = time.time() | |
212 return(self.temps) | |
213 | |
214 def readTemp(self, id): | |
215 self.commsLock.acquire() | |
216 cmd = 'te ' + id | |
217 self.p.sendline(cmd) | |
218 # Echo | |
219 assert(self.p.expect(cmd) == 0) | |
220 # Eat EOL left from expect | |
221 self.p.readline() | |
222 | |
223 line = self.p.readline().strip() | |
224 self.commsLock.release() | |
225 # 'CRC mismatch' can mean that we picked the wrong ROM.. | |
226 if (re.match('CRC mismatch', line) != None): | |
227 raise ROMReadError | |
228 | |
229 return(line) | |
230 | |
231 def setState(self, state): | |
232 if (state == 'cool'): | |
233 relay = 1 << self.coolRelay | |
234 elif (state == 'heat'): | |
235 relay = 1 << self.heatRelay | |
236 elif (state == 'idle'): | |
237 relay = 0 | |
238 else: | |
239 raise(ValueError) | |
240 | |
241 if (state == self.currState): | |
242 return | |
243 | |
244 # Keep track of when we last turned off or on | |
245 if (state == 'cool'): | |
246 if (self.currState == 'heat'): | |
247 self.lastHeatOff = time.time() | |
248 self.lastCoolOn = time.time() | |
249 elif (state == 'heat'): | |
250 if (self.currState == 'cool'): | |
251 self.lastCoolOff = time.time() | |
252 self.lastHeatOn = time.time() | |
253 else: | |
254 if (self.currState == 'cool'): | |
255 self.lastCoolOff = time.time() | |
256 if (self.currState == 'heat'): | |
257 self.lastHeatOff = time.time() | |
258 | |
259 self.currState = state | |
260 | |
261 self.commsLock.acquire() | |
262 # Need the extra spaces cause the parser in the micro is busted | |
263 cmd = 'out c %02x' % relay | |
264 self.p.sendline(cmd) | |
265 # Echo | |
266 assert(self.p.expect(cmd) == 0) | |
267 self.commsLock.release() | |
268 | |
269 def polltemps(self, temps): | |
270 while True: | |
271 for d in temps: | |
272 #print d | |
273 t = gettemp(p, d) | |
274 print "%s -> %s" % (d, t) | |
275 print | |
276 | |
277 def run(self): | |
278 while True: | |
279 self.updateTemps() | |
280 | |
3 | 281 def initLog(): |
282 # Init our logging | |
283 log = logging.getLogger("monitor") | |
284 | |
285 # Default to warts and all logging | |
286 log.setLevel(logging.DEBUG) | |
287 | |
288 # Log to this file | |
289 logfile = logging.handlers.RotatingFileHandler(filename = "/tmp/beermon.log", | |
290 maxBytes = 1000000, backupCount = 3) | |
291 | |
292 # And stderr | |
293 logstderr = logging.StreamHandler() | |
294 | |
295 # Format it nicely | |
296 formatter = logging.Formatter(fmt = "%(asctime)s: %(message)s", datefmt = "%Y/%m/%d %H:%M:%S") | |
297 | |
298 # Glue it all together | |
299 logfile.setFormatter(formatter) | |
300 logstderr.setFormatter(formatter) | |
301 log.addHandler(logfile) | |
302 log.addHandler(logstderr) | |
303 return(log) | |
304 | |
1 | 305 def main(): |
4
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
306 import beermon |
3 | 307 |
4
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
308 global log |
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
309 log = initLog() |
3 | 310 |
311 log.debug("=== Initing ===") | |
4
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
312 log.debug("$Id: beermon.py,v 1.3 2007/09/24 13:31:15 darius Exp $") |
1 | 313 |
4
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
314 m = None |
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
315 exitCode = 0 |
1 | 316 try: |
4
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
317 m = beermon.MonitorDev() |
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
318 |
3 | 319 c = beermon.Control(m, log) |
1 | 320 # Wait for the first temperature readings to come through, saves |
321 # getting an 'invalid data' message | |
322 time.sleep(3) | |
323 c.doit() | |
324 log.debug("doit exited") | |
325 | |
326 except KeyboardInterrupt: | |
327 log.debug("Exiting due to keyboard interrupt") | |
3 | 328 |
4
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
329 except Exception, e: |
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
330 log.debug("Something went wrong, details below") |
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
331 log.debug(e) |
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
332 #log.debug(reduce(lambda x, y: x + y, traceback.format_exception( |
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
333 # sys.last_type, sys.last_value, sys.last_traceback))) |
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
334 exitCode = 1 |
1 | 335 |
336 finally: | |
337 # Make sure we try and turn it off if something goes wrong | |
4
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
338 if (m != None): |
618372f83862
Wait on a condition var instead of using time.sleep() - this works
darius
parents:
3
diff
changeset
|
339 m.setState('idle') |
1 | 340 |
3 | 341 sys.exit(exitCode) |
1 | 342 |
343 if __name__ == "__main__": | |
344 main() |