comparison MonitorDev.py @ 8:483375ca5d10

Split into seperate files.
author darius
date Sat, 29 Sep 2007 14:39:59 +0000
parents
children 9d5b291cfd01
comparison
equal deleted inserted replaced
7:860936fab75f 8:483375ca5d10
1 #!/usr/bin/env python
2
3 ############################################################################
4 # Monitoring/control interface to hardware for beermon
5 #
6 # $Id: MonitorDev.py,v 1.1 2007/09/29 14:39:59 darius Exp $
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
39 class MonitorDev(threading.Thread):
40 """This class continually polls the hardware for temperature
41 readings and accepts state changes to heat & cool"""
42
43 # Match a ROM ID (eg 00:11:22:33:44:55:66:77)
44 romre = re.compile('([0-9a-f]{2}:){7}[0-9a-f]{2}')
45 # Match the prompt
46 promptre = re.compile('> ')
47
48 # Dictionary of sensor IDs & temperatures
49 temps = {}
50 # Dictionary of sensor IDs & epoch times
51 lastUpdate = {}
52
53 # List of all device IDs
54 devs = []
55 # List of temperature sensor IDs
56 tempdevs = []
57
58 # Lock to gate access to the comms
59 commsLock = None
60
61 currState = 'idle'
62
63 lastHeatOn = 0
64 lastHeatOff = 0
65 lastCoolOn = 0
66 lastCoolOff = 0
67
68 def __init__(self, _log, conf):
69 global log
70 log = _log
71 threading.Thread.__init__(self)
72
73 # Collect parameters
74 self.coolRelay = conf.getint('hardware', 'coolRelay')
75 self.heatRelay = conf.getint('hardware', 'heatRelay')
76 self.fermenterId = conf.get('hardware', 'fermenterId')
77 self.fridgeId = conf.get('hardware', 'fridgeId')
78 self.ambientId = conf.get('hardware', 'ambientId')
79 self.minCoolOnTime = conf.getfloat('hardware', 'minCoolOnTime')
80 self.minCoolOffTime = conf.getfloat('hardware', 'minCoolOffTime')
81 self.minHeatOnTime = conf.getfloat('hardware', 'minHeatOnTime')
82 self.minHeatOffTime = conf.getfloat('hardware', 'minHeatOffTime')
83 self.minHeatOvershoot = conf.getfloat('hardware', 'minHeatOvershoot')
84 self.minCoolOvershoot = conf.getfloat('hardware', 'minCoolOvershoot')
85
86 # Setup locking & spawn SSH
87 self.commsLock = threading.Lock()
88 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)'])
89 assert(self.p.expect('logged in') == 0)
90 self.p.timeout = 3
91 self.setspeed()
92
93 # Search for 1-wire modules
94 self.devs = self.find1wire()
95 self.tempdevs = filter(self.istemp, self.devs)
96
97 log.debug("fermenterId - %s" % (self.fermenterId))
98 log.debug("fridgeId - %s" % (self.fridgeId))
99 log.debug("ambientId - %s" % (self.ambientId))
100 log.debug("minCoolOnTime - %d, minCoolOffTime - %d" %
101 (self.minCoolOnTime, self.minCoolOffTime))
102 log.debug("minHeatOnTime - %d, minHeatOffTime - %d" %
103 (self.minHeatOnTime, self.minHeatOffTime))
104 log.debug("minHeatOvershoot - %3.2f, minCoolOvershoot - %3.2f" %
105 (self.minHeatOvershoot, self.minCoolOvershoot))
106 self.start()
107
108 def setspeed(self):
109 self.commsLock.acquire()
110 self.p.send('~')
111 assert(self.p.expect('t - set terminal') == 0)
112 self.p.send('t')
113 assert(self.p.expect('p - set speed') == 0)
114 self.p.send('p')
115 assert(self.p.expect('f - 38400') == 0)
116 self.p.send('f')
117 assert(self.p.expect('done!') == 0)
118 self.commsLock.release()
119
120 def find1wire(self):
121 self.commsLock.acquire()
122 self.p.sendline('')
123 assert(self.p.expect('> ') == 0)
124 self.p.sendline('sr')
125 # Echo
126 assert(self.p.expect('sr') == 0)
127
128 # Send a new line which will give us a command prompt to stop on
129 # later. We could use read() but that would make the code a lot
130 # uglier
131 self.p.sendline('')
132
133 devlist = []
134
135 # Loop until we get the command prompt (> ) collecting ROM IDs
136 while True:
137 idx = self.p.expect([self.romre, self.promptre])
138 if (idx == 0):
139 # Matched a ROM
140 #print "Found ROM " + self.p.match.group()
141 devlist.append(self.p.match.group(0))
142 elif (idx == 1):
143 # Matched prompt, exit
144 break
145 else:
146 # Unpossible!
147 self.commsLock.release()
148 raise SystemError()
149
150 self.commsLock.release()
151
152 return(devlist)
153
154 def istemp(self, id):
155 [family, a, b, c, d, e, f, g] = id.split(':')
156 if (family == '10'):
157 return True
158 else:
159 return False
160
161 def updateTemps(self):
162 for i in self.tempdevs:
163 try:
164 self.temps[i] = float(self.readTemp(i))
165 self.lastUpdate[i] = time.time()
166 except OWReadError:
167 # Ignore this - just results in no update reflected by lastUpdate
168 pass
169
170 return(self.temps)
171
172 def readTemp(self, id):
173 self.commsLock.acquire()
174 cmd = 'te ' + id
175 self.p.sendline(cmd)
176 # Echo
177 assert(self.p.expect(cmd) == 0)
178 # Eat EOL left from expect
179 self.p.readline()
180
181 line = self.p.readline().strip()
182 self.commsLock.release()
183 # 'CRC mismatch' can mean that we picked the wrong ROM..
184 if (re.match('CRC mismatch', line) != None):
185 raise OWReadError
186
187 return(line)
188
189 def setState(self, state):
190 if (state == 'cool'):
191 relay = 1 << self.coolRelay
192 elif (state == 'heat'):
193 relay = 1 << self.heatRelay
194 elif (state == 'idle'):
195 relay = 0
196 else:
197 raise(ValueError)
198
199 if (state == self.currState):
200 return
201
202 # Keep track of when we last turned off or on
203 if (state == 'cool'):
204 if (self.currState == 'heat'):
205 self.lastHeatOff = time.time()
206 self.lastCoolOn = time.time()
207 elif (state == 'heat'):
208 if (self.currState == 'cool'):
209 self.lastCoolOff = time.time()
210 self.lastHeatOn = time.time()
211 else:
212 if (self.currState == 'cool'):
213 self.lastCoolOff = time.time()
214 if (self.currState == 'heat'):
215 self.lastHeatOff = time.time()
216
217 self.currState = state
218
219 self.commsLock.acquire()
220 # Need the extra spaces cause the parser in the micro is busted
221 cmd = 'out c %02x' % relay
222 self.p.sendline(cmd)
223 # Echo
224 assert(self.p.expect(cmd) == 0)
225 self.commsLock.release()
226
227 def polltemps(self, temps):
228 while True:
229 for d in temps:
230 #print d
231 t = gettemp(p, d)
232 print "%s -> %s" % (d, t)
233 print
234
235 def run(self):
236 while True:
237 self.updateTemps()
238