Mercurial > code > home > repos > homeauto
comparison service/garageArduino/garageArduino.py @ 0:6fd208b97616
start
Ignore-this: e06ac598970a0d4750f588ab89f56996
author | Drew Perttula <drewp@bigasterisk.com> |
---|---|
date | Mon, 01 Aug 2011 03:30:30 -0700 |
parents | |
children | be855a111619 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:6fd208b97616 |
---|---|
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") | |
96 self.settings.poller.assertIsCurrent() | |
97 self.write(json.dumps({"irLevels" : [[t1, lev1], [t2,lev2], ]})) | |
98 | |
99 class HousePowerThreshold(PrettyErrorHandler, cyclone.web.RequestHandler): | |
100 """ | |
101 the level that's between between an IR pulse and the noise | |
102 """ | |
103 def get(self): | |
104 self.set_header("Content-Type", "application/javascript") | |
105 self.settings.poller.assertIsCurrent() | |
106 self.write(json.dumps({"threshold" : thr})) | |
107 | |
108 def put(self): | |
109 pass | |
110 | |
111 | |
112 class Application(cyclone.web.Application): | |
113 def __init__(self, ard, poller): | |
114 handlers = [ | |
115 (r"/", Index), | |
116 (r"/graph", GraphPage), | |
117 (r"/frontDoorMotion", FrontDoorMotion), | |
118 (r'/housePower', HousePower), | |
119 (r'/housepower/raw', HousePowerRaw), | |
120 (r'/housepower/threshold', HousePowerThreshold), | |
121 ] | |
122 settings = {"arduino" : ard, "poller" : poller} | |
123 cyclone.web.Application.__init__(self, handlers, **settings) | |
124 | |
125 | |
126 class Poller(object): | |
127 """ | |
128 times the blinks to estimate power usage. Captures the other | |
129 returned sensor values too in self.lastValues | |
130 """ | |
131 def __init__(self, ard, period): | |
132 self.ard = ard | |
133 self.period = period | |
134 self.carbon = CarbonClient(serverHost='bang') | |
135 self.lastBlinkTime = None | |
136 self.lastValues = None | |
137 self.lastPollTime = 0 | |
138 self.lastWatts = "(just restarted; wait no data yet)" | |
139 self.kwhPerBlink = 1.0 # unsure | |
140 self.lastMotion = False | |
141 | |
142 def assertIsCurrent(self): | |
143 """raise an error if the poll data is not fresh""" | |
144 dt = time.time() - self.lastPollTime | |
145 if dt > period * 2: | |
146 raise ValueError("last poll time was too old: %.1f sec ago" % dt) | |
147 | |
148 def poll(self): | |
149 now = time.time() | |
150 try: | |
151 try: | |
152 newData = ard.poll() | |
153 except ValueError, e: | |
154 print e | |
155 else: | |
156 self.lastPollTime = now | |
157 self.lastValues = newData # for other data besides the blinks | |
158 self.processBlinks(now, newData['newBlinks']) | |
159 self.processMotion(newData['motion']) | |
160 | |
161 except (IOError, OSError): | |
162 os.abort() | |
163 except Exception, e: | |
164 print "poll error", e | |
165 traceback.print_exc() | |
166 | |
167 def processBlinks(self, now, b): | |
168 if b > 0: | |
169 if b > 1: | |
170 # todo: if it's like 1,1,2,2,2,2,1,1 then we | |
171 # need to subdivide those inner sample periods | |
172 # since there might really be two blinks. But | |
173 # if it's like 0,0,0,2,0,0, that should be | |
174 # treated like b=1 since it's probably noise | |
175 pass | |
176 | |
177 if self.lastBlinkTime is not None: | |
178 dt = now - self.lastBlinkTime | |
179 dth = dt / 3600. | |
180 watts = self.kwhPerBlink / dth | |
181 | |
182 if watts > 10000: | |
183 # this pulse (or the previous one) is | |
184 # likely noise. Too late for the previous | |
185 # one, but we're going to skip this one | |
186 return | |
187 else: | |
188 self.lastWatts = watts | |
189 | |
190 # todo: remove this; a separate logger shall do it | |
191 self.carbon.send('system.house.powerMeter_w', watts, now) | |
192 | |
193 self.lastBlinkTime = now | |
194 | |
195 def processMotion(self, state): | |
196 if state == self.lastMotion: | |
197 return | |
198 self.lastMotion = state | |
199 msg = json.dumps(dict(board='garage', | |
200 name="frontDoorMotion", state=state)) | |
201 getPage('http://bang.bigasterisk.com:9069/inputChange', | |
202 method="POST", | |
203 postdata=msg, | |
204 headers={'Content-Type' : 'application/json'} | |
205 ).addErrback(self.reportError, msg) | |
206 | |
207 def reportError(self, msg, *args): | |
208 print "post error", msg, args | |
209 | |
210 if __name__ == '__main__': | |
211 | |
212 config = { # to be read from a file | |
213 'arduinoPort': '/dev/ttyACM0', | |
214 'servePort' : 9050, | |
215 'pollFrequency' : 5, | |
216 'boardName' : 'garage', # gets sent with updates | |
217 } | |
218 | |
219 #log.startLogging(sys.stdout) | |
220 | |
221 ard = ArduinoGarage() | |
222 | |
223 period = 1/config['pollFrequency'] | |
224 p = Poller(ard, period) | |
225 task.LoopingCall(p.poll).start(period) | |
226 reactor.listenTCP(config['servePort'], Application(ard, p)) | |
227 reactor.run() |