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