75 lines
1.9 KiB
Python
75 lines
1.9 KiB
Python
|
#!/usr/bin/env python
|
||
|
|
||
|
import struct
|
||
|
import socket
|
||
|
import time
|
||
|
|
||
|
from random import random
|
||
|
|
||
|
class WS2801Command:
|
||
|
# command definitions
|
||
|
SET_COLOR = 0
|
||
|
FADE_COLOR = 1
|
||
|
ADD_COLOR = 2
|
||
|
SET_FADESTEP = 3
|
||
|
|
||
|
def __init__(self, action = SET_COLOR, module = 0, d0 = 0, d1 = 0, d2 = 0):
|
||
|
self.action = action
|
||
|
self.module = module
|
||
|
self.d0 = d0
|
||
|
self.d1 = d1
|
||
|
self.d2 = d2
|
||
|
|
||
|
def serialize(self):
|
||
|
meta = (self.action << 6) | self.module
|
||
|
|
||
|
return struct.pack("BBBB", meta, self.d0, self.d1, self.d2)
|
||
|
|
||
|
class WS2801:
|
||
|
def __init__(self, host, port):
|
||
|
self.__commands = []
|
||
|
|
||
|
# create the UDP socket
|
||
|
family, socktype, proto, canonname, sockaddr = socket.getaddrinfo(host, port, 0, socket.SOCK_DGRAM)[0]
|
||
|
|
||
|
self.__socket = socket.socket(family, socktype, proto)
|
||
|
self.__socket.connect(sockaddr)
|
||
|
|
||
|
def commit(self):
|
||
|
# send the data
|
||
|
packet = ''
|
||
|
for command in self.__commands:
|
||
|
packet = packet + command.serialize()
|
||
|
|
||
|
if packet:
|
||
|
self.__socket.send(packet)
|
||
|
|
||
|
self.__commands = []
|
||
|
|
||
|
def set_fadestep(self, fadestep):
|
||
|
# add a "set fadestep" command
|
||
|
self.__commands.append(WS2801Command(WS2801Command.SET_FADESTEP, d0 = fadestep))
|
||
|
|
||
|
def set_color(self, module, r, g, b):
|
||
|
# add a "set color" command
|
||
|
self.__commands.append(WS2801Command(WS2801Command.SET_COLOR, module, r, g, b))
|
||
|
|
||
|
def fade_color(self, module, r, g, b):
|
||
|
# add a "fade to color" command
|
||
|
self.__commands.append(WS2801Command(WS2801Command.FADE_COLOR, module, r, g, b))
|
||
|
|
||
|
def add_color(self, module, r, g, b):
|
||
|
# add a "add to color" command
|
||
|
self.__commands.append(WS2801Command(WS2801Command.ADD_COLOR, module, r, g, b))
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
w = WS2801("192.168.2.222", 2703)
|
||
|
w.set_fadestep(1);
|
||
|
|
||
|
while True:
|
||
|
w.set_color(10, 255, 255, 255)
|
||
|
for i in range(20):
|
||
|
w.fade_color(i, 0, 0, 0)
|
||
|
w.commit()
|
||
|
time.sleep(0.2)
|