redfly-led.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/bin/python3
  2. import socket
  3. import sys
  4. import time
  5. import math
  6. # Create a TCP/IP socket
  7. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  8. # Connect the socket to the port where the server is listening
  9. server_address = ('0.0.0.0', 2020)
  10. print('binding {} port {}'.format(*server_address))
  11. sock.bind(server_address)
  12. N_ROWS = 5
  13. N_COLS = 10
  14. oldTime = time.time()
  15. oldPing = time.time()
  16. def getBytes():
  17. pixels = [0] * (N_ROWS * N_COLS)
  18. for row in range(N_ROWS):
  19. for col in range(N_COLS):
  20. pixels[row*N_COLS + col] = int(math.sin(row + col + time.time()*15) * 8 + 8)
  21. pixels[49] = int(pixels[49]/2)
  22. return bytes([0x41] + pixels)
  23. client_address = None
  24. try:
  25. while True:
  26. if not client_address:
  27. data, addr = sock.recvfrom(16)
  28. print('received {} from {}'.format(data, addr))
  29. client_address = addr
  30. else:
  31. sock.sendto(getBytes(), client_address)
  32. if time.time() - oldPing > 30:
  33. data, addr = sock.recvfrom(16)
  34. print('received {} from {}'.format(data, addr))
  35. client_address = addr
  36. oldPing = time.time()
  37. oldTime = time.time()
  38. time.sleep(1/40)
  39. finally:
  40. print('closing socket')
  41. sock.close()