Mercurial > ~darius > hgwebdir.cgi > beermon
annotate MonitorDev.py @ 16:67a4dc218bbf
- Add commented out entries for ZigBee experiment.
- Send a return and sync up before sending out commands.
author | darius |
---|---|
date | Tue, 29 Jan 2008 11:39:22 +0000 |
parents | 8ada8d5cca15 |
children |
rev | line source |
---|---|
6 | 1 #!/usr/bin/env python |
2 | |
3 ############################################################################ | |
4 # Monitoring/control interface to hardware for beermon | |
5 # | |
16 | 6 # $Id: MonitorDev.py,v 1.4 2008/01/29 11:39:22 darius Exp $ |
6 | 7 # |
8 # Depends on: Python 2.3 (I think) | |
9 # | |
10 ############################################################################ | |
11 # | |
12 # Copyright (C) 2007 Daniel O'Connor. All rights reserved. | |
13 # | |
14 # Redistribution and use in source and binary forms, with or without | |
15 # modification, are permitted provided that the following conditions | |
16 # are met: | |
17 # 1. Redistributions of source code must retain the above copyright | |
18 # notice, this list of conditions and the following disclaimer. | |
19 # 2. Redistributions in binary form must reproduce the above copyright | |
20 # notice, this list of conditions and the following disclaimer in the | |
21 # documentation and/or other materials provided with the distribution. | |
22 # | |
23 # THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND | |
24 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
25 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
26 # ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE | |
27 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
28 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS | |
29 # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) | |
30 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | |
31 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY | |
32 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF | |
33 # SUCH DAMAGE. | |
34 # | |
35 ############################################################################ | |
36 | |
37 import threading, re, time, pexpect | |
38 | |
14
8ada8d5cca15
Move OWReadError to MonitorDev since that's where it's raised.
darius
parents:
10
diff
changeset
|
39 class OWReadError(Exception): |
8ada8d5cca15
Move OWReadError to MonitorDev since that's where it's raised.
darius
parents:
10
diff
changeset
|
40 """Raised when we failed to read from a 1-wire device, could be a timeout |
8ada8d5cca15
Move OWReadError to MonitorDev since that's where it's raised.
darius
parents:
10
diff
changeset
|
41 or the device is non-existent, etc""" |
8ada8d5cca15
Move OWReadError to MonitorDev since that's where it's raised.
darius
parents:
10
diff
changeset
|
42 pass |
8ada8d5cca15
Move OWReadError to MonitorDev since that's where it's raised.
darius
parents:
10
diff
changeset
|
43 |
6 | 44 class MonitorDev(threading.Thread): |
45 """This class continually polls the hardware for temperature | |
46 readings and accepts state changes to heat & cool""" | |
47 | |
48 # Match a ROM ID (eg 00:11:22:33:44:55:66:77) | |
49 romre = re.compile('([0-9a-f]{2}:){7}[0-9a-f]{2}') | |
50 # Match the prompt | |
51 promptre = re.compile('> ') | |
52 | |
53 # Dictionary of sensor IDs & temperatures | |
54 temps = {} | |
55 # Dictionary of sensor IDs & epoch times | |
56 lastUpdate = {} | |
57 | |
58 # List of all device IDs | |
59 devs = [] | |
60 # List of temperature sensor IDs | |
61 tempdevs = [] | |
62 | |
63 # Lock to gate access to the comms | |
64 commsLock = None | |
65 | |
66 currState = 'idle' | |
67 | |
68 lastHeatOn = 0 | |
69 lastHeatOff = 0 | |
70 lastCoolOn = 0 | |
71 lastCoolOff = 0 | |
72 | |
73 def __init__(self, _log, conf): | |
10 | 74 """_log is a logging object, conf is a ConfigParser object""" |
6 | 75 global log |
76 log = _log | |
77 threading.Thread.__init__(self) | |
78 | |
79 # Collect parameters | |
80 self.coolRelay = conf.getint('hardware', 'coolRelay') | |
81 self.heatRelay = conf.getint('hardware', 'heatRelay') | |
82 self.fermenterId = conf.get('hardware', 'fermenterId') | |
83 self.fridgeId = conf.get('hardware', 'fridgeId') | |
84 self.ambientId = conf.get('hardware', 'ambientId') | |
85 self.minCoolOnTime = conf.getfloat('hardware', 'minCoolOnTime') | |
86 self.minCoolOffTime = conf.getfloat('hardware', 'minCoolOffTime') | |
87 self.minHeatOnTime = conf.getfloat('hardware', 'minHeatOnTime') | |
88 self.minHeatOffTime = conf.getfloat('hardware', 'minHeatOffTime') | |
89 self.minHeatOvershoot = conf.getfloat('hardware', 'minHeatOvershoot') | |
90 self.minCoolOvershoot = conf.getfloat('hardware', 'minCoolOvershoot') | |
91 | |
92 # Setup locking & spawn SSH | |
93 self.commsLock = threading.Lock() | |
16 | 94 #self.p = pexpect.spawn('/usr/bin/cu', ['-l', '/dev/cuaU1', '-s', '38400']) |
6 | 95 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)']) |
16 | 96 |
97 self.p.timeout = 30 | |
98 #assert(self.p.expect('Connected') == 0) | |
6 | 99 assert(self.p.expect('logged in') == 0) |
100 self.p.timeout = 3 | |
101 self.setspeed() | |
102 | |
103 # Search for 1-wire modules | |
104 self.devs = self.find1wire() | |
105 self.tempdevs = filter(self.istemp, self.devs) | |
106 | |
107 log.debug("fermenterId - %s" % (self.fermenterId)) | |
108 log.debug("fridgeId - %s" % (self.fridgeId)) | |
109 log.debug("ambientId - %s" % (self.ambientId)) | |
110 log.debug("minCoolOnTime - %d, minCoolOffTime - %d" % | |
111 (self.minCoolOnTime, self.minCoolOffTime)) | |
112 log.debug("minHeatOnTime - %d, minHeatOffTime - %d" % | |
113 (self.minHeatOnTime, self.minHeatOffTime)) | |
114 log.debug("minHeatOvershoot - %3.2f, minCoolOvershoot - %3.2f" % | |
115 (self.minHeatOvershoot, self.minCoolOvershoot)) | |
116 self.start() | |
16 | 117 |
6 | 118 def setspeed(self): |
10 | 119 """Set the speed microcom talks to the serial port to 38400""" |
6 | 120 self.commsLock.acquire() |
121 self.p.send('~') | |
122 assert(self.p.expect('t - set terminal') == 0) | |
123 self.p.send('t') | |
124 assert(self.p.expect('p - set speed') == 0) | |
125 self.p.send('p') | |
126 assert(self.p.expect('f - 38400') == 0) | |
127 self.p.send('f') | |
128 assert(self.p.expect('done!') == 0) | |
129 self.commsLock.release() | |
16 | 130 |
6 | 131 def find1wire(self): |
10 | 132 """Scan the bus for 1-wire devices""" |
6 | 133 self.commsLock.acquire() |
134 self.p.sendline('') | |
135 assert(self.p.expect('> ') == 0) | |
136 self.p.sendline('sr') | |
137 # Echo | |
138 assert(self.p.expect('sr') == 0) | |
139 | |
140 # Send a new line which will give us a command prompt to stop on | |
141 # later. We could use read() but that would make the code a lot | |
142 # uglier | |
143 self.p.sendline('') | |
144 | |
145 devlist = [] | |
146 | |
147 # Loop until we get the command prompt (> ) collecting ROM IDs | |
148 while True: | |
149 idx = self.p.expect([self.romre, self.promptre]) | |
150 if (idx == 0): | |
151 # Matched a ROM | |
16 | 152 #log.debug("Found ROM " + self.p.match.group()) |
6 | 153 devlist.append(self.p.match.group(0)) |
154 elif (idx == 1): | |
155 # Matched prompt, exit | |
156 break | |
157 else: | |
158 # Unpossible! | |
159 self.commsLock.release() | |
160 raise SystemError() | |
161 | |
162 self.commsLock.release() | |
163 | |
164 return(devlist) | |
165 | |
166 def istemp(self, id): | |
10 | 167 """Returns true if the 1-wire device is a temperature sensor""" |
6 | 168 [family, a, b, c, d, e, f, g] = id.split(':') |
169 if (family == '10'): | |
170 return True | |
171 else: | |
172 return False | |
173 | |
174 def updateTemps(self): | |
10 | 175 """Update our cached copy of temperatures""" |
6 | 176 for i in self.tempdevs: |
177 try: | |
178 self.temps[i] = float(self.readTemp(i)) | |
179 self.lastUpdate[i] = time.time() | |
180 except OWReadError: | |
181 # Ignore this - just results in no update reflected by lastUpdate | |
182 pass | |
16 | 183 |
6 | 184 return(self.temps) |
185 | |
186 def readTemp(self, id): | |
10 | 187 """Read the temperature of a sensor""" |
6 | 188 self.commsLock.acquire() |
189 cmd = 'te ' + id | |
190 self.p.sendline(cmd) | |
191 # Echo | |
192 assert(self.p.expect(cmd) == 0) | |
193 # Eat EOL left from expect | |
194 self.p.readline() | |
195 line = self.p.readline().strip() | |
196 self.commsLock.release() | |
197 # 'CRC mismatch' can mean that we picked the wrong ROM.. | |
198 if (re.match('CRC mismatch', line) != None): | |
199 raise OWReadError | |
200 return(line) | |
201 | |
202 def setState(self, state): | |
10 | 203 """Set the heat/cool state, track the on/off time""" |
6 | 204 if (state == 'cool'): |
205 relay = 1 << self.coolRelay | |
206 elif (state == 'heat'): | |
207 relay = 1 << self.heatRelay | |
208 elif (state == 'idle'): | |
209 relay = 0 | |
210 else: | |
211 raise(ValueError) | |
212 | |
213 if (state == self.currState): | |
214 return | |
215 | |
216 # Keep track of when we last turned off or on | |
217 if (state == 'cool'): | |
218 if (self.currState == 'heat'): | |
219 self.lastHeatOff = time.time() | |
220 self.lastCoolOn = time.time() | |
221 elif (state == 'heat'): | |
222 if (self.currState == 'cool'): | |
223 self.lastCoolOff = time.time() | |
224 self.lastHeatOn = time.time() | |
225 else: | |
226 if (self.currState == 'cool'): | |
227 self.lastCoolOff = time.time() | |
228 if (self.currState == 'heat'): | |
229 self.lastHeatOff = time.time() | |
230 | |
231 self.currState = state | |
232 | |
233 self.commsLock.acquire() | |
234 # Need the extra spaces cause the parser in the micro is busted | |
16 | 235 self.p.sendline('') |
236 assert(self.p.expect('> ') == 0) | |
6 | 237 cmd = 'out c %02x' % relay |
238 self.p.sendline(cmd) | |
16 | 239 # Echo |
6 | 240 assert(self.p.expect(cmd) == 0) |
241 self.commsLock.release() | |
242 | |
243 def run(self): | |
10 | 244 """Sit in a loop polling temperatures""" |
6 | 245 while True: |
246 self.updateTemps() | |
247 |