-
Notifications
You must be signed in to change notification settings - Fork 0
/
unicorn-opc.py
executable file
·48 lines (37 loc) · 1.24 KB
/
unicorn-opc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python
import struct
from SocketServer import ThreadingTCPServer, StreamRequestHandler
from threading import Thread
import unicornhat as unicorn
width = height = 8
def init():
global width, height
unicorn.set_layout(unicorn.AUTO)
unicorn.rotation(0)
unicorn.brightness(0.5)
width, height=unicorn.get_shape()
MSG_HEADER = struct.Struct('>BBH')
class Handler(StreamRequestHandler):
def handle(self):
sock = self.request
f = sock.makefile('rb')
while True:
hdr = f.read(MSG_HEADER.size)
if not hdr:
break
channel, command, length = MSG_HEADER.unpack(hdr)
data = f.read(length)
if command == 0:
for off in range(0, len(data), 3):
y, x = divmod(off // 3, 64)
if y > height or x > width:
continue
color = tuple(ord(c) for c in data[off:off + 3])
unicorn.set_pixel(y, 8 - x, color)
unicorn.show()
elif command == 2:
print("Unsupported command %d" % command)
init()
s = ThreadingTCPServer(('0.0.0.0', 7891), Handler)
s.daemon_threads = True
s.serve_forever()