main.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import _thread
  2. import time
  3. import utils
  4. from config import getConfig
  5. from httpServer import startHttpServer,closeHttpServer
  6. # 硬重启
  7. import machine
  8. def taskCheck():
  9. """
  10. 定时检查连接
  11. :return:
  12. """
  13. time_sleep = 10
  14. count = 0
  15. config = getConfig()
  16. while True:
  17. if getConfig().runTask:
  18. try:
  19. if utils.getStatus():
  20. print('WiFi 正常', utils.getWifiConnectInfo())
  21. if getConfig().mqttStatus :
  22. print('MQTT 正常', getConfig().mqtt.host, getConfig().mqtt.port,getConfig().mqtt.subTopic)
  23. if getConfig().mqtt.clientId is "":
  24. print("设备未绑定")
  25. utils.send_ping()
  26. else:
  27. # 有变化就上报一次
  28. if config != getConfig():
  29. print("上报数据")
  30. utils.reportConfig()
  31. config = getConfig()
  32. else:
  33. utils.send_ping()
  34. count = 0
  35. else:
  36. print('MQTT 未连接', getConfig().mqtt.host, getConfig().mqtt.port,getConfig().mqtt.subTopic)
  37. utils.connectMQTT(time_sleep)
  38. else:
  39. print('WiFi 未连接')
  40. if utils.autoConnectWifi():
  41. utils.connectMQTT(time_sleep)
  42. # 没有客户的id表示没被绑定
  43. if not utils.getStatus() or not getConfig().mqttStatus or getConfig().mqtt.clientId is "":
  44. count += 1
  45. # 连接失败开启热点
  46. utils.openAp()
  47. startHttpServer()
  48. else:
  49. closeHttpServer()
  50. utils.closeAp()
  51. if count > 60:
  52. machine.reset()
  53. except Exception as e:
  54. print(f"连接失败:未知错误 - {e}")
  55. time.sleep(time_sleep)
  56. try:
  57. _thread.start_new_thread(taskCheck, ())
  58. except:
  59. machine.reset()