暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import network
  2. import socket
  3. import time
  4. from machine import Pin
  5. class Wifi:
  6. html = """<!DOCTYPE html>
  7. <html>
  8. <head>
  9. <title>Pico W</title>
  10. </head>
  11. <body>
  12. <h1>%s</h1>
  13. <p>%s</p>
  14. <pre>%s</pre>
  15. </body>
  16. </html>
  17. """
  18. def __init__(self, networks, port = 80):
  19. # Check if wifi details have been set
  20. if len(networks) == 0:
  21. self.led.value(1)
  22. raise RuntimeError('Please set wifi ssid and password in config.py')
  23. self.led = Pin("LED", Pin.OUT)
  24. # Start connection
  25. self.wlan = network.WLAN(network.STA_IF)
  26. self.wlan.active(True)
  27. visible = self.wlan.scan()
  28. ssid = None
  29. password = None
  30. for name, a, b, c, d, e in visible:
  31. for t_ssid, t_password in networks:
  32. if name.decode("utf-8") == t_ssid:
  33. ssid = t_ssid
  34. password = t_password
  35. break
  36. if (ssid == None) or (password == None):
  37. self.led.value(1)
  38. raise RuntimeError("No known network found")
  39. self.wlan.connect(ssid, password)
  40. # Wait for connect success or failure
  41. max_wait = 20
  42. error_count = 20
  43. while max_wait > 0:
  44. if self.wlan.status() >= 3:
  45. break
  46. elif self.wlan.status() < 0:
  47. self.wlan.connect(ssid, password)
  48. error_count -= 1
  49. if error_count <= 0:
  50. break
  51. else:
  52. max_wait -= 1
  53. print('waiting for connection...')
  54. self.led.value(not self.led.value())
  55. time.sleep(0.5)
  56. # Handle connection error
  57. if self.wlan.status() != 3:
  58. self.led.value(1)
  59. raise RuntimeError('wifi connection failed %d' % self.wlan.status())
  60. print('connected')
  61. status = self.wlan.ifconfig()
  62. print('ip = ' + status[0])
  63. # Open socket to the server
  64. self.sock = socket.socket()
  65. self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  66. addr = socket.getaddrinfo('0.0.0.0', port)[0][-1]
  67. self.sock.bind(addr)
  68. self.sock.listen(1)
  69. print('listening on', addr)
  70. self.handlers = []
  71. self.led.value(0)
  72. def add_handler(self, path, callback):
  73. for hp, hc in self.handlers:
  74. if hp == path:
  75. raise RuntimeError('path is already registered %s' % path)
  76. self.led.value(1)
  77. h = (path, callback)
  78. self.handlers.append(h)
  79. def listen_once(self):
  80. # Listen for connections
  81. try:
  82. cl, addr = self.sock.accept()
  83. print('client connected from', addr)
  84. request = cl.recv(1024).decode('utf-8')
  85. #print(request)
  86. response = ""
  87. found = False
  88. for path, callback in self.handlers:
  89. pos = request.find(path)
  90. if ((pos == 4) or (pos == 5)) and ((request[pos + len(path)] == ' ') or (request[pos + len(path)] == '?')):
  91. found = True
  92. response = callback(request)
  93. break
  94. code = 200
  95. title = "OK"
  96. if not found:
  97. code = 404
  98. title = "Not Found"
  99. response = self.html % (str(code), title, request)
  100. elif len(response) == 0:
  101. code = 503
  102. title = "Internal Server Error"
  103. response = self.html % (str(code), title, request)
  104. cl.send('HTTP/1.0 ' + str(code) + ' ' + title + '\r\nContent-type: text/html\r\n\r\n')
  105. cl.send(response)
  106. except OSError as e:
  107. print(e)
  108. finally:
  109. cl.close()
  110. print('connection closed')
  111. def listen(self):
  112. while True:
  113. self.listen_once()