Mercurial > code > home > repos > homeauto
annotate service/sba/sba.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 | 867f59c83dba |
children | dc03f39f46d9 |
rev | line source |
---|---|
808 | 1 from __future__ import division |
2 import serial, time, jsonlib, sys, cgi, argparse | |
3 import cyclone.web | |
4 from twisted.python import log | |
5 from twisted.internet import reactor | |
6 | |
7 class Sba(object): | |
8 def __init__(self, port="/dev/ttyACM0"): | |
9 self.port = port | |
10 self.reset() | |
11 | |
12 def reset(self): | |
13 log.msg("reopening port") | |
14 self.s = serial.Serial(self.port, baudrate=115200) | |
15 log.msg(str(self.s.__dict__)) | |
16 self.sendControl() | |
17 | |
809
bebb8f7c5a3e
move a bunch of services into this tree, give them all web status pages
drewp <drewp@bigasterisk.com>
parents:
808
diff
changeset
|
18 def ping(self): |
bebb8f7c5a3e
move a bunch of services into this tree, give them all web status pages
drewp <drewp@bigasterisk.com>
parents:
808
diff
changeset
|
19 pass # waiting for spec |
bebb8f7c5a3e
move a bunch of services into this tree, give them all web status pages
drewp <drewp@bigasterisk.com>
parents:
808
diff
changeset
|
20 |
808 | 21 def sendControl(self): |
22 controlBits = [0, 1, | |
23 0, 0, 0, | |
24 1, 1, 1, 1, 1, 1, 1, # b correction | |
25 0, 0, 0, | |
26 1, 1, 1, 1, 1, 1, 1, # g correction | |
27 0, | |
28 0, 0, # clock mode 00=internal | |
29 1, 1, 1, 1, 1, 1, 1, # r correction | |
30 ] | |
31 | |
32 control = reduce(lambda a, b: a<<1 | b, | |
33 #controlBits | |
34 reversed(controlBits) | |
35 ) | |
36 self.send("C" + hex(control)[2:].zfill(8)) | |
37 self.send("E0") | |
38 | |
39 def send(self, cmd, getResponse=True): | |
40 """ | |
41 send a command using the protocol from http://engr.biz/prod/SB-A/ | |
42 | |
43 we will attach the carriage return, cmd is just a string like 'V' | |
44 | |
45 Returns the response line, like '+OK' | |
46 """ | |
47 try: | |
48 self.s.write(cmd + "\r") | |
49 except OSError: | |
50 self.reset() | |
51 | |
52 if getResponse: | |
53 return self.s.readline().strip() | |
54 | |
55 def rgbs(self, rgbs): | |
56 """ | |
57 send a set of full rgb packets. Values are 0..1023. | |
58 """ | |
59 t1 = time.time() | |
60 for (r,g,b) in rgbs: | |
61 packed = (b & 0x3ff) << 20 | (r & 0x3ff) << 10 | (g & 0x3ff) | |
62 self.send("D%08x" % packed, getResponse=False) | |
63 | |
64 self.send("L1", getResponse=False) | |
65 self.send("L0", getResponse=False) | |
66 sends = time.time() - t1 | |
67 # doing all the reads together triples the transmission rate | |
68 t2 = time.time() | |
69 [self.s.readline() for loop in range(2 + len(rgbs))] | |
70 reads = time.time() - t2 | |
71 | |
72 log.msg("%.1f ms for sends, %.1f ms for reads" % ( | |
73 1000 * sends, 1000 * reads)) | |
74 | |
75 class BriteChain(object): | |
76 def __init__(self, sba): | |
77 self.sba = sba | |
78 self.colors = [] | |
79 | |
80 def setColor(self, pos, color): | |
81 """color is (r,g,b) 10-bit int. The highest position you ever | |
82 set is how many channels we'll output""" | |
83 if len(self.colors) <= pos: | |
84 self.colors.extend([(0,0,0)]*(pos - len(self.colors) + 1)) | |
85 self.colors[pos] = color | |
86 self.refresh() | |
87 | |
88 def getColor(self, pos): | |
89 try: | |
90 return self.colors[pos] | |
91 except IndexError: | |
92 return (0,0,0) | |
93 | |
94 def refresh(self): | |
95 self.sba.rgbs(self.colors[::-1]) | |
96 | |
97 class IndexHandler(cyclone.web.RequestHandler): | |
98 def get(self): | |
809
bebb8f7c5a3e
move a bunch of services into this tree, give them all web status pages
drewp <drewp@bigasterisk.com>
parents:
808
diff
changeset
|
99 self.settings.chain.ping() |
808 | 100 self.set_header("Content-type", "text/html") |
101 self.write(open("sba.html").read()) | |
102 | |
103 class BriteHandler(cyclone.web.RequestHandler): | |
104 """ | |
105 /brite/0 is the first shiftbrite on the chain. Put a text/plain | |
106 color like #ffffff (8-bit) or a application/json value like | |
107 {"rgb10":[1023,1023,1023]} (for 10-bit). GET (with accept, to pick | |
108 your format) to learn the current color. | |
109 | |
110 /brite/1 affects the second shiftbrite on the chain, etc | |
111 """ | |
112 def put(self, pos): | |
113 d = self.request.body | |
114 ctype = self.request.headers.get("Content-Type") | |
115 if ';' in ctype: | |
116 ctype = ctype.split(';')[0].strip() | |
117 if ctype == 'text/plain': | |
118 color = decode8bitHexColor(d) | |
119 elif ctype == 'application/json': | |
120 color = jsonlib.read(d)['rgb10'] | |
121 elif ctype == 'application/x-www-form-urlencoded': | |
122 color = decode8bitHexColor(cgi.parse_qs(d)['color'][0]) | |
123 else: | |
124 self.response.set_status(415, "use text/plain, application/json, " | |
125 "or application/x-www-form-urlencoded") | |
126 return | |
127 | |
128 self.settings.chain.setColor(int(pos), color) | |
129 self.set_header("Content-Type", "text/plain") | |
130 self.write("set %s\n" % pos) | |
131 | |
132 def post(self, pos): | |
133 self.put(pos) | |
134 self.redirect("..") | |
135 | |
136 def get(self, pos): | |
137 # todo: content neg | |
138 color = self.settings.chain.getColor(int(pos)) | |
139 self.set_header("Content-Type", "text/plain") | |
140 self.write(encode8bitHexColor(color)) | |
141 | |
142 def decode8bitHexColor(s): | |
143 return [4 * int(s.lstrip('#')[i:i+2], 16) for i in [0, 2, 4]] | |
144 def encode8bitHexColor(color): | |
145 return "#%02X%02X%02X" % (color[0] // 4, color[1] // 4, color[2] // 4) | |
146 | |
147 class Application(cyclone.web.Application): | |
148 def __init__(self, chain): | |
149 handlers = [ | |
150 (r"/", IndexHandler), | |
151 (r"/brite/(\d+)", BriteHandler), | |
152 ] | |
153 | |
154 settings = { | |
155 "static_path": "./static", | |
156 "template_path": "./template", | |
157 "chain" : chain, | |
158 } | |
159 | |
160 cyclone.web.Application.__init__(self, handlers, **settings) | |
161 | |
162 def main(): | |
163 parser = argparse.ArgumentParser(description='drive sba lights') | |
164 parser.add_argument('-v', '--verbose', action="store_true", help='logging') | |
165 args = parser.parse_args() | |
166 | |
167 try: | |
168 sba = Sba() | |
169 except serial.SerialException: | |
170 sba = Sba("/dev/ttyACM1") | |
171 | |
172 chain = BriteChain(sba) | |
173 | |
174 if 0: # todo: stick test patterns like this on some other resource | |
175 while 1: | |
176 t1 = time.time() | |
177 steps = 0 | |
178 for x in range(0, 1024, 5): | |
179 steps += 1 | |
180 sba.rgbs([(x, x, x)] * 2) | |
181 print steps / (time.time() - t1) | |
182 | |
183 if args.verbose: | |
184 log.startLogging(sys.stdout) | |
185 reactor.listenTCP(9060, Application(chain)) | |
186 reactor.run() | |
187 | |
188 if __name__ == "__main__": | |
189 main() |