main.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # main.py -- put your code here!
  2. import time
  3. import machine
  4. from machine import Pin, PWM
  5. import ujson
  6. import network
  7. from umqttsimple import MQTTClient
  8. from config import MQTT_SERVER, CLIENT_ID, TOPIC_SUB, TOPIC_PUB, LED_LIST
  9. from leds import Leds
  10. import gc
  11. gc.collect()
  12. station = network.WLAN(network.STA_IF)
  13. leds = Leds()
  14. def sub_cb(topic, msg):
  15. try:
  16. cmd = ujson.loads(str(msg, 'utf-8'))
  17. if 'state' in cmd:
  18. if cmd['state'] == "OFF":
  19. leds.disableAll()
  20. else:
  21. leds.enableAll()
  22. if 'speed' in cmd:
  23. leds.steps = int(cmd['fade'])
  24. if 'color' in cmd:
  25. for i, (color, _, _) in enumerate(LED_LIST):
  26. if color in cmd['color']:
  27. val = int(cmd['color'][color])
  28. if val >= 0 and val <= 255:
  29. leds.setColor(i, val)
  30. if 'reset' in cmd:
  31. machine.reset()
  32. except Exception as e:
  33. client.publish(TOPIC_PUB, b"error")
  34. def connect_and_subscribe():
  35. client = MQTTClient(CLIENT_ID, MQTT_SERVER)
  36. client.set_callback(sub_cb)
  37. client.connect()
  38. client.subscribe(TOPIC_SUB)
  39. print('Connected to %s MQTT broker, subscribed to %s topic' % (MQTT_SERVER, TOPIC_SUB))
  40. return client
  41. def restart_and_reconnect():
  42. print('Failed to connect to MQTT broker. Reconnecting...')
  43. time.sleep(10)
  44. machine.reset()
  45. try:
  46. client = connect_and_subscribe()
  47. client.set_last_will(TOPIC_PUB, b"offline", retain=False, qos=0)
  48. client.sock.settimeout(10)
  49. except OSError as e:
  50. print(e)
  51. restart_and_reconnect()
  52. last_message = 0
  53. message_interval = 10
  54. counter = 0
  55. while True:
  56. try:
  57. client.check_msg()
  58. if (time.time() - last_message) > message_interval:
  59. msg = b'online #%d' % counter
  60. client.publish(TOPIC_PUB, msg)
  61. last_message = time.time()
  62. gc.collect()
  63. counter += 1
  64. leds.update()
  65. time.sleep(0.02)
  66. except OSError as e:
  67. client.publish(TOPIC_PUB, b"OSError")
  68. restart_and_reconnect()
  69. if station.isconnected() == False:
  70. leds.enable(0)
  71. leds.setColor(0, 60)