|
| 1 | +import numpy as np |
| 2 | +import socket |
| 3 | + |
| 4 | +class WledRealtimeClient: |
| 5 | + def __init__(self, wled_controller_ip, num_pixels, udp_port=21324, max_pixels_per_packet=126): |
| 6 | + self.wled_controller_ip = wled_controller_ip |
| 7 | + self.num_pixels = num_pixels |
| 8 | + self.udp_port = udp_port |
| 9 | + self.max_pixels_per_packet = max_pixels_per_packet |
| 10 | + self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 11 | + self._prev_pixels = np.full((3, self.num_pixels), 253, dtype=np.uint8) |
| 12 | + self.pixels = np.full((3, self.num_pixels), 1, dtype=np.uint8) |
| 13 | + |
| 14 | + def update(self): |
| 15 | + # Truncate values and cast to integer |
| 16 | + self.pixels = np.clip(self.pixels, 0, 255).astype(np.uint8) |
| 17 | + p = np.copy(self.pixels) |
| 18 | + |
| 19 | + idx = np.where(~np.all(p == self._prev_pixels, axis=0))[0] |
| 20 | + num_pixels = len(idx) |
| 21 | + n_packets = (num_pixels + self.max_pixels_per_packet - 1) // self.max_pixels_per_packet |
| 22 | + idx_split = np.array_split(idx, n_packets) |
| 23 | + |
| 24 | + header = bytes([1, 2]) # WARLS protocol header |
| 25 | + for packet_indices in idx_split: |
| 26 | + data = bytearray(header) |
| 27 | + for i in packet_indices: |
| 28 | + data.extend([i, *p[:, i]]) # Index and RGB values |
| 29 | + self._sock.sendto(bytes(data), (self.wled_controller_ip, self.udp_port)) |
| 30 | + |
| 31 | + self._prev_pixels = np.copy(p) |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | +################################## LED blink test ################################## |
| 36 | +if __name__ == "__main__": |
| 37 | + WLED_CONTROLLER_IP = "192.168.1.153" |
| 38 | + NUM_PIXELS = 255 # Amount of LEDs on your strip |
| 39 | + import time |
| 40 | + wled = WledRealtimeClient(WLED_CONTROLLER_IP, NUM_PIXELS) |
| 41 | + print('Starting LED blink test') |
| 42 | + while True: |
| 43 | + for i in range(NUM_PIXELS): |
| 44 | + wled.pixels[1, i] = 255 if wled.pixels[1, i] == 0 else 0 |
| 45 | + wled.update() |
| 46 | + time.sleep(.01) |
0 commit comments