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