httpServer.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. # web服务
  2. from microdot import Microdot
  3. import machine
  4. from config import getConfig,saveConfig
  5. import utils
  6. import _thread
  7. app = Microdot()
  8. @app.before_request
  9. # 请求时暂停主循环检查任务
  10. def before_request():
  11. getConfig().runTask = False
  12. @app.after_request
  13. def after_request():
  14. getConfig().runTask = True
  15. @app.route('/ping')
  16. async def ping(req):
  17. return 'esp'
  18. @app.post('/addWifi')
  19. async def addWifi(req):
  20. wifiName = req.form.get('wifiName')
  21. wifiPwd = req.form.get('wifiPwd')
  22. getConfig().wifi[wifiName] = wifiPwd
  23. saveConfig()
  24. return '1'
  25. @app.post('/rmWifi')
  26. async def rmWifi(req):
  27. wifiName = req.form.get('wifiName')
  28. try:
  29. del getConfig().wifi[wifiName]
  30. except:
  31. print('')
  32. saveConfig()
  33. return '1'
  34. @app.post('/connectWifi')
  35. async def connectWifi(req):
  36. ssid = req.form.get('wifiName')
  37. pwd = req.form.get('wifiPwd')
  38. if utils.connectWifi(ssid, pwd):
  39. getConfig().wifi[ssid] = pwd
  40. saveConfig()
  41. getConfig().runTask = True
  42. return '1'
  43. return '2'
  44. @app.post('/updateAp')
  45. async def updateAp(req):
  46. apName = req.form.get('apName')
  47. apPwd = req.form.get('apPwd')
  48. getConfig().ap.ssid = apName
  49. getConfig().ap.pwd = apPwd
  50. saveConfig()
  51. return '1'
  52. @app.get('/scanWifi')
  53. async def scanWifi(request):
  54. return utils.scanWifi()
  55. @app.get('/getInfo')
  56. async def index(request):
  57. return getConfig().toJson()
  58. @app.get('/disconnectWifi')
  59. async def disconnectWifi(request):
  60. utils.disconnectWifi()
  61. @app.route('/restart')
  62. def index(req):
  63. machine.reset()
  64. @app.post('/bind')
  65. async def index(req):
  66. uid = req.form.get('uid')
  67. getConfig().mqtt.clientId = uid
  68. saveConfig()
  69. getConfig().mqttStatus = False
  70. return '1'
  71. def openHttpServer():
  72. if not getConfig().httpServer:
  73. getConfig().httpServer = True
  74. app.run(host='0.0.0.0', port=80, debug=True)
  75. def startHttpServer():
  76. if not getConfig().httpServer:
  77. _thread.start_new_thread(openHttpServer, ())
  78. def closeHttpServer():
  79. if getConfig().httpServer:
  80. getConfig().httpServer = False
  81. app.shutdown()
  82. print('http server 关闭')