mywifi.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import network
  2. # from machine import Timer
  3. SSID = "Xiaomi_eng"
  4. # SSID = "Mi11_eng"
  5. PASSWORD = "88888888"
  6. class MyWifi():
  7. _instance = None
  8. # _first_init = True
  9. def __new__(cls, *args, **kwargs):
  10. if cls._instance is None:
  11. cls._instance = super().__new__(cls)
  12. return cls._instance # 返回的是内存地址
  13. # WiFi 不能被初始化两次,否则会发生内部错误
  14. # 注意,在重复导入模块时,已经被算作初始化了,如果另一个模块又导入了这个类,很容易重复实例化一个新的WiFi对象
  15. # 避免重复 init,因为那些值会被重新初始化
  16. def __init__(self, ssid=SSID, password=PASSWORD) -> None:
  17. self.wlan = network.WLAN(network.STA_IF)
  18. self.ssid = ssid
  19. self.password = password
  20. self.s = {'status': 'start connect', 'count': 0, 'check_count': 3}
  21. def check_disconnect(self):
  22. if self.s['status'] == 'start connect':
  23. if not self.wlan.isconnected():
  24. print("Start connect to wifi:", self.ssid)
  25. self.wlan.active(True)
  26. self.wlan.connect(self.ssid, self.password)
  27. print('connecting to network...', self.ssid)
  28. self.s['status'] = 'check isconnected'
  29. elif self.s['status'] == 'check isconnected':
  30. if self.wlan.isconnected():
  31. self.s['count'] = 0
  32. self.s['status'] = 'recheck'
  33. print('Connection successful:', self.wlan.ifconfig())
  34. else:
  35. print('try to connect to network...', self.s['count'])
  36. self.s['count'] += 1
  37. # 设置连接超时时间
  38. if self.s['count'] > self.s['check_count']:
  39. self.s['status'] = 'recheck'
  40. self.s['count'] = 0
  41. elif self.s['status'] == 'recheck':
  42. if not self.wlan.isconnected():
  43. self.wlan.active(False)
  44. print('error: wifi disconnect')
  45. self.s['status'] = 'start connect'
  46. def _do_connect(self, recheck=False):
  47. if not self.wlan.isconnected():
  48. self.wlan.active(True)
  49. self.wlan.connect(self.ssid, self.password)
  50. print('connecting to network...', self.ssid)
  51. while not self.wlan.isconnected():
  52. pass
  53. print('network config:', self.wlan.ifconfig())
  54. def get_wifi_addr(self):
  55. return self.get_wifi_ifconfig()[0]
  56. def get_wifi_ifconfig(self):
  57. # # 等待 check_disconnect() WiFi连接成功再返回
  58. # while not self.s['status'] == 'recheck':
  59. # pass
  60. # # 返回: ('192.168.31.123', '255.255.255.0', '192.168.31.1', '192.168.31.1')
  61. return self.wlan.ifconfig()
  62. my_wifi = MyWifi()
  63. # 协程的方式
  64. import uasyncio
  65. async def wifi_do_work():
  66. while True:
  67. my_wifi.check_disconnect()
  68. await uasyncio.sleep_ms(1000)
  69. if __name__ == '__main__':
  70. uasyncio.run(wifi_do_work())