main.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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
  9. import gc
  10. gc.collect()
  11. station = network.WLAN(network.STA_IF)
  12. vals = {
  13. 'C': 0,
  14. 'G': 0,
  15. 'R': 0,
  16. 'W': 0,
  17. 'B': 0
  18. }
  19. duration = 50
  20. pwm = {}
  21. def initPWM():
  22. global pwm
  23. pwm = {
  24. 'C': PWM(Pin(Pin.PB_16), channel=2, freq=800, duty=vals['C']),
  25. 'G': PWM(Pin(Pin.PB_13), channel=1, freq=800, duty=vals['G']),
  26. 'R': PWM(Pin(Pin.PA_05), channel=0, freq=800, duty=vals['R']),
  27. 'W': PWM(Pin(Pin.PB_08), channel=4, freq=800, duty=vals['W']),
  28. 'B': PWM(Pin(Pin.PB_15), channel=3, freq=800, duty=vals['B'])
  29. }
  30. initPWM()
  31. def fade():
  32. global pwm, vals, duration
  33. if duration > 2:
  34. diff = {}
  35. for color in pwm:
  36. diff[color] = float(vals[color] - pwm[color].duty()) / (duration-1)
  37. for i in range(duration-1, 1, -1):
  38. for color in pwm:
  39. pwm[color].duty(int(vals[color] - diff[color] * i))
  40. time.sleep(0.02)
  41. for color in pwm:
  42. pwm[color].duty(vals[color])
  43. def sub_cb(topic, msg):
  44. global pwm, vals, duration
  45. try:
  46. cmd = ujson.loads(str(msg, 'utf-8'))
  47. if 'state' in cmd:
  48. if cmd['state'] == "OFF":
  49. for color in pwm:
  50. pwm[color].deinit()
  51. pwm = {}
  52. else:
  53. initPWM()
  54. if 'speed' in cmd:
  55. duration = int(cmd['fade'])
  56. if 'color' in cmd:
  57. for color in vals:
  58. if color in cmd['color']:
  59. val = int(cmd['color'][color])
  60. if val >= 0 and val <= 255:
  61. vals[color] = val
  62. fade()
  63. if 'reset' in cmd:
  64. machine.reset()
  65. except Exception as e:
  66. client.publish(topic_pub, b"error")
  67. def connect_and_subscribe():
  68. global client_id, mqtt_server, topic_sub
  69. client = MQTTClient(client_id, mqtt_server)
  70. client.set_callback(sub_cb)
  71. client.connect()
  72. client.subscribe(topic_sub)
  73. print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
  74. return client
  75. def restart_and_reconnect():
  76. print('Failed to connect to MQTT broker. Reconnecting...')
  77. time.sleep(10)
  78. machine.reset()
  79. try:
  80. client = connect_and_subscribe()
  81. client.set_last_will(topic_pub, b"offline", retain=False, qos=0)
  82. client.sock.settimeout(10)
  83. except OSError as e:
  84. print(e)
  85. restart_and_reconnect()
  86. last_message = 0
  87. message_interval = 10
  88. counter = 0
  89. while True:
  90. try:
  91. client.wait_msg()
  92. if (time.time() - last_message) > message_interval:
  93. msg = b'online #%d' % counter
  94. client.publish(topic_pub, msg)
  95. last_message = time.time()
  96. gc.collect()
  97. counter += 1
  98. except OSError as e:
  99. client.publish(topic_pub, b"OSError")
  100. restart_and_reconnect()
  101. if station.isconnected() == False:
  102. if 'R' in pwm:
  103. pwm['R'].duty(60)