mywifi.py 3.0 KB

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