Mercurial > code > home > repos > homeauto
annotate service/garageArduino/garageArduino.py @ 810:44e1ca03ddf1
move garage door opener from parport to arduino
Ignore-this: c7d21f40841af0e64b26dd4991e441ae
darcs-hash:20110815044657-312f9-4533ff085af323016f0c7a51629b250231ef2dc6.gz
author | drewp <drewp@bigasterisk.com> |
---|---|
date | Sun, 14 Aug 2011 21:46:57 -0700 |
parents | bebb8f7c5a3e |
children | 33e6678d76ab |
rev | line source |
---|---|
805 | 1 #!bin/python |
2 """ | |
3 talks to frontdoordriver.pde on an arduino | |
4 """ | |
5 | |
6 from __future__ import division | |
7 | |
810
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
8 import cyclone.web, json, traceback, os, sys, time, logging |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
9 from twisted.internet import reactor, task, defer |
805 | 10 from twisted.web.client import getPage |
11 sys.path.append("/my/proj/house/frontdoor") | |
12 from loggingserial import LoggingSerial | |
810
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
13 sys.path.append("/my/proj/homeauto/lib") |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
14 from cycloneerr import PrettyErrorHandler |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
15 from logsetup import log |
805 | 16 sys.path.append("../../../room") |
17 from carbondata import CarbonClient | |
18 sys.path.append("/my/site/magma") | |
19 from stategraph import StateGraph | |
20 from rdflib import Namespace, RDF, Literal | |
810
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
21 |
805 | 22 |
23 ROOM = Namespace("http://projects.bigasterisk.com/room/") | |
24 DEV = Namespace("http://projects.bigasterisk.com/device/") | |
25 | |
26 class ArduinoGarage(object): | |
27 def __init__(self, port='/dev/ttyACM0'): | |
28 self.ser = LoggingSerial(port=port, baudrate=115200, timeout=1) | |
29 self.ser.flush() | |
30 | |
31 def ping(self): | |
32 self.ser.write("\x60\x00\x00") | |
33 msg = self.ser.readJson() | |
34 assert msg == {"ok":True}, msg | |
35 | |
36 def poll(self): | |
37 self.ser.write("\x60\x01\x00") | |
38 ret = self.ser.readJson() | |
39 return ret | |
40 | |
41 def lastLevel(self): | |
42 self.ser.write("\x60\x02\x00") | |
43 return self.ser.readJson()['z'] | |
44 | |
45 def setThreshold(self, t): | |
46 """set 10-bit threshold""" | |
47 self.ser.write("\x60\x03"+chr(max(1 << 2, t) >> 2)) | |
48 return self.ser.readJson()['threshold'] | |
49 | |
810
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
50 def setGarage(self, level): |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
51 """set garage door opener pin""" |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
52 self.ser.write("\x60\x04"+chr(int(bool(level)))) |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
53 return self.ser.readJson()['garage'] |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
54 |
805 | 55 |
56 class Index(PrettyErrorHandler, cyclone.web.RequestHandler): | |
57 def get(self): | |
58 """ | |
59 this is an acceptable status check since it makes a round-trip | |
60 to the arduino before returning success | |
61 """ | |
62 self.settings.arduino.ping() | |
63 | |
64 self.set_header("Content-Type", "application/xhtml+xml") | |
65 self.write(open("index.html").read()) | |
66 | |
67 class GraphPage(PrettyErrorHandler, cyclone.web.RequestHandler): | |
68 def get(self): | |
69 self.set_header("Content-Type", "application/x-trig") | |
70 g = StateGraph(ROOM['garageArduino']) | |
71 self.settings.poller.assertIsCurrent() | |
72 g.add((DEV['frontDoorMotion'], ROOM['state'], | |
73 ROOM['motion'] if self.settings.poller.lastValues['motion'] else | |
74 ROOM['noMotion'])) | |
75 g.add((ROOM['house'], ROOM['usingPower'], | |
76 Literal(self.settings.poller.lastWatts, datatype=ROOM["#watts"]))) | |
77 self.write(g.asTrig()) | |
78 | |
79 class FrontDoorMotion(PrettyErrorHandler, cyclone.web.RequestHandler): | |
80 def get(self): | |
81 self.set_header("Content-Type", "application/javascript") | |
82 self.settings.poller.assertIsCurrent() | |
83 self.write(json.dumps({"frontDoorMotion" : | |
84 self.settings.poller.lastValues['motion']})) | |
85 | |
86 class HousePower(PrettyErrorHandler, cyclone.web.RequestHandler): | |
87 def get(self): | |
88 self.set_header("Content-Type", "application/javascript") | |
89 self.settings.poller.assertIsCurrent() | |
90 w = self.settings.poller | |
91 self.write(json.dumps({ | |
92 "currentWatts" : round(w.lastWatts, 2) if isinstance(w.lastWatts, float) else w.lastWatts, | |
93 "lastPulseAgo" : "%.1f sec ago" % (time.time() - w.lastBlinkTime) if w.lastBlinkTime is not None else "unknown", | |
94 "kwhPerBlink" : w.kwhPerBlink})) | |
95 | |
96 class HousePowerRaw(PrettyErrorHandler, cyclone.web.RequestHandler): | |
97 """ | |
98 raw data from the analog sensor, for plotting or picking a noise threshold | |
99 """ | |
100 def get(self): | |
101 self.set_header("Content-Type", "application/javascript") | |
809
bebb8f7c5a3e
move a bunch of services into this tree, give them all web status pages
drewp <drewp@bigasterisk.com>
parents:
805
diff
changeset
|
102 pts = [] |
bebb8f7c5a3e
move a bunch of services into this tree, give them all web status pages
drewp <drewp@bigasterisk.com>
parents:
805
diff
changeset
|
103 for i in range(60): |
bebb8f7c5a3e
move a bunch of services into this tree, give them all web status pages
drewp <drewp@bigasterisk.com>
parents:
805
diff
changeset
|
104 level = self.settings.arduino.lastLevel() |
bebb8f7c5a3e
move a bunch of services into this tree, give them all web status pages
drewp <drewp@bigasterisk.com>
parents:
805
diff
changeset
|
105 pts.append((round(time.time(), 3), level)) |
bebb8f7c5a3e
move a bunch of services into this tree, give them all web status pages
drewp <drewp@bigasterisk.com>
parents:
805
diff
changeset
|
106 |
bebb8f7c5a3e
move a bunch of services into this tree, give them all web status pages
drewp <drewp@bigasterisk.com>
parents:
805
diff
changeset
|
107 self.write(json.dumps({"irLevels" : pts})) |
805 | 108 |
109 class HousePowerThreshold(PrettyErrorHandler, cyclone.web.RequestHandler): | |
110 """ | |
111 the level that's between between an IR pulse and the noise | |
112 """ | |
113 def get(self): | |
114 self.set_header("Content-Type", "application/javascript") | |
115 self.settings.poller.assertIsCurrent() | |
116 self.write(json.dumps({"threshold" : thr})) | |
117 | |
118 def put(self): | |
119 pass | |
120 | |
810
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
121 class GarageDoorOpen(PrettyErrorHandler, cyclone.web.RequestHandler): |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
122 def post(self): |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
123 self.set_header("Content-Type", "text/plain") |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
124 self.settings.arduino.setGarage(True) |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
125 self.write("pin high, waiting..\n") |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
126 self.flush() |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
127 d = defer.Deferred() |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
128 def finish(): |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
129 self.settings.arduino.setGarage(False) |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
130 self.write("pin low. Done") |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
131 d.callback(None) |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
132 reactor.callLater(1.5, finish) # this time depends on the LP circuit |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
133 return d |
805 | 134 |
135 class Application(cyclone.web.Application): | |
136 def __init__(self, ard, poller): | |
137 handlers = [ | |
138 (r"/", Index), | |
139 (r"/graph", GraphPage), | |
140 (r"/frontDoorMotion", FrontDoorMotion), | |
141 (r'/housePower', HousePower), | |
809
bebb8f7c5a3e
move a bunch of services into this tree, give them all web status pages
drewp <drewp@bigasterisk.com>
parents:
805
diff
changeset
|
142 (r'/housePower/raw', HousePowerRaw), |
bebb8f7c5a3e
move a bunch of services into this tree, give them all web status pages
drewp <drewp@bigasterisk.com>
parents:
805
diff
changeset
|
143 (r'/housePower/threshold', HousePowerThreshold), |
810
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
144 (r'/garageDoorOpen', GarageDoorOpen), |
805 | 145 ] |
146 settings = {"arduino" : ard, "poller" : poller} | |
147 cyclone.web.Application.__init__(self, handlers, **settings) | |
148 | |
149 | |
150 class Poller(object): | |
151 """ | |
152 times the blinks to estimate power usage. Captures the other | |
153 returned sensor values too in self.lastValues | |
154 """ | |
155 def __init__(self, ard, period): | |
156 self.ard = ard | |
157 self.period = period | |
158 self.carbon = CarbonClient(serverHost='bang') | |
159 self.lastBlinkTime = None | |
160 self.lastValues = None | |
161 self.lastPollTime = 0 | |
162 self.lastWatts = "(just restarted; wait no data yet)" | |
163 self.kwhPerBlink = 1.0 # unsure | |
164 self.lastMotion = False | |
165 | |
166 def assertIsCurrent(self): | |
167 """raise an error if the poll data is not fresh""" | |
168 dt = time.time() - self.lastPollTime | |
169 if dt > period * 2: | |
170 raise ValueError("last poll time was too old: %.1f sec ago" % dt) | |
171 | |
172 def poll(self): | |
173 now = time.time() | |
174 try: | |
175 try: | |
176 newData = ard.poll() | |
177 except ValueError, e: | |
178 print e | |
179 else: | |
180 self.lastPollTime = now | |
181 self.lastValues = newData # for other data besides the blinks | |
182 self.processBlinks(now, newData['newBlinks']) | |
183 self.processMotion(newData['motion']) | |
184 | |
185 except (IOError, OSError): | |
186 os.abort() | |
187 except Exception, e: | |
188 print "poll error", e | |
189 traceback.print_exc() | |
190 | |
191 def processBlinks(self, now, b): | |
192 if b > 0: | |
193 if b > 1: | |
194 # todo: if it's like 1,1,2,2,2,2,1,1 then we | |
195 # need to subdivide those inner sample periods | |
196 # since there might really be two blinks. But | |
197 # if it's like 0,0,0,2,0,0, that should be | |
198 # treated like b=1 since it's probably noise | |
199 pass | |
200 | |
201 if self.lastBlinkTime is not None: | |
202 dt = now - self.lastBlinkTime | |
203 dth = dt / 3600. | |
204 watts = self.kwhPerBlink / dth | |
205 | |
206 if watts > 10000: | |
207 # this pulse (or the previous one) is | |
208 # likely noise. Too late for the previous | |
209 # one, but we're going to skip this one | |
210 return | |
211 else: | |
212 self.lastWatts = watts | |
213 | |
214 # todo: remove this; a separate logger shall do it | |
215 self.carbon.send('system.house.powerMeter_w', watts, now) | |
216 | |
217 self.lastBlinkTime = now | |
218 | |
219 def processMotion(self, state): | |
220 if state == self.lastMotion: | |
221 return | |
222 self.lastMotion = state | |
223 msg = json.dumps(dict(board='garage', | |
224 name="frontDoorMotion", state=state)) | |
225 getPage('http://bang.bigasterisk.com:9069/inputChange', | |
226 method="POST", | |
227 postdata=msg, | |
228 headers={'Content-Type' : 'application/json'} | |
229 ).addErrback(self.reportError, msg) | |
230 | |
231 def reportError(self, msg, *args): | |
232 print "post error", msg, args | |
233 | |
234 if __name__ == '__main__': | |
235 | |
236 config = { # to be read from a file | |
237 'arduinoPort': '/dev/ttyACM0', | |
238 'servePort' : 9050, | |
239 'pollFrequency' : 5, | |
240 'boardName' : 'garage', # gets sent with updates | |
241 } | |
242 | |
810
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
243 #from twisted.python import log as twlog |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
244 #twlog.startLogging(sys.stdout) |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
245 |
44e1ca03ddf1
move garage door opener from parport to arduino
drewp <drewp@bigasterisk.com>
parents:
809
diff
changeset
|
246 log.setLevel(logging.DEBUG) |
805 | 247 |
248 ard = ArduinoGarage() | |
249 | |
250 period = 1/config['pollFrequency'] | |
251 p = Poller(ard, period) | |
252 task.LoopingCall(p.poll).start(period) | |
253 reactor.listenTCP(config['servePort'], Application(ard, p)) | |
254 reactor.run() |