No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

wifi.py 3.5KB

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