led-color-flow.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env python
  2. import os
  3. import time
  4. import math
  5. from requests import post
  6. def get_env(name):
  7. value = os.getenv(name, None)
  8. if value is None:
  9. raise Exception('Missing {} from the environment'.format(name))
  10. return value
  11. def call(service_call, data):
  12. endpoint = get_env('HA_ENDPOINT')
  13. token = get_env('HA_TOKEN')
  14. url = '{}/api/services/light/{}'.format(endpoint, service_call)
  15. headers = {
  16. "Authorization": "Bearer {}".format(token),
  17. "content-type": "application/json",
  18. }
  19. response = post(url, headers=headers, json=data)
  20. print(response.text)
  21. def set_rgb(r, g, b):
  22. data = {
  23. 'entity_id': 'light.led_strip_light',
  24. 'rgb_color': [r, g, b],
  25. }
  26. call('turn_on', data)
  27. def turn_off():
  28. data = {
  29. 'entity_id': 'light.led_strip_light',
  30. }
  31. call('turn_off', data)
  32. if __name__ == '__main__':
  33. print('Press CTRL+C to interrupt...')
  34. try:
  35. while True:
  36. for i in range(1, 50):
  37. r = math.sin(0.3*i + 0) * 127 + 128
  38. g = math.sin(0.3*i + 2) * 127 + 128
  39. b = math.sin(0.3*i + 4) * 127 + 128
  40. set_rgb(r, g, b)
  41. time.sleep(0.5)
  42. except KeyboardInterrupt:
  43. pass
  44. finally:
  45. set_rgb(0, 0, 255)
  46. time.sleep(1)
  47. turn_off()