Advertisement
DeaD_EyE

wled.py

Mar 2nd, 2024
1,361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. import atexit
  2.  
  3. from struct import Struct
  4. from socket import socket, AF_INET, SOCK_DGRAM
  5. from itertools import chain
  6.  
  7.  
  8. WLED_ADDR = ("192.168.0.215", 21324)
  9. sock = socket(AF_INET, SOCK_DGRAM)
  10.  
  11. atexit.register(sock.close)
  12.  
  13.  
  14. def set_leds(colors, addr=WLED_ADDR):
  15.     if len(colors) > 490:
  16.         raise ValueError("Too many LEDs")
  17.  
  18.     leds = chain.from_iterable(colors)
  19.     data_len = len(colors) * 3
  20.     proto = 2
  21.     delay = 10
  22.  
  23.     # Protokoll 2 == RGB
  24.  
  25.     # Protokoll, Timeout, [Rn,Gn,Bn], ...
  26.     st = Struct(f"!BB{data_len}B")
  27.     sock.sendto(st.pack(proto, delay, *leds), WLED_ADDR)
  28.  
  29.  
  30. def set_level(value, /, min_value=0, max_value=140, leds=72):
  31.     relative = (value - min_value) / (max_value - min_value)
  32.  
  33.     on_count = round(relative * leds)
  34.     off_count = leds - on_count
  35.  
  36.     r = min(255, max(0, int(relative * 255)))
  37.     g = 0
  38.     b = 255 - r
  39.  
  40.     color = (r , g , b)
  41.     colors = [color] * on_count + [(0, 0, 0)] * off_count
  42.  
  43.     set_leds(colors)
  44.  
  45.  
  46. if __name__ == "__main__":
  47.     try:
  48.         while True:
  49.             set_level(float(input("Value: ")))
  50.     except KeyboardInterrupt:
  51.         pass
  52.     except ValueError:
  53.         pass
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement