main.py 2.3 KB

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