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