| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- import network
- # from machine import Timer
- SSID = "Xiaomi_eng"
- # SSID = "Mi11_eng"
- PASSWORD = "88888888"
- class MyWifi():
- _instance = None
- # _first_init = True
- def __new__(cls, *args, **kwargs):
- if cls._instance is None:
- cls._instance = super().__new__(cls)
- return cls._instance # 返回的是内存地址
- # WiFi 不能被初始化两次,否则会发生内部错误
- # 注意,在重复导入模块时,已经被算作初始化了,如果另一个模块又导入了这个类,很容易重复实例化一个新的WiFi对象
- # 避免重复 init,因为那些值会被重新初始化
- def __init__(self, ssid=SSID, password=PASSWORD) -> None:
- self.wlan = network.WLAN(network.STA_IF)
- self.ssid = ssid
- self.password = password
- self.s = {'status': 'start connect', 'count': 0, 'check_count': 3}
- def check_disconnect(self):
- if self.s['status'] == 'start connect':
- if not self.wlan.isconnected():
- print("Start connect to wifi:", self.ssid)
- self.wlan.active(True)
- self.wlan.connect(self.ssid, self.password)
- print('connecting to network...', self.ssid)
- self.s['status'] = 'check isconnected'
- elif self.s['status'] == 'check isconnected':
- if self.wlan.isconnected():
- self.s['count'] = 0
- self.s['status'] = 'recheck'
- print('Connection successful:', self.wlan.ifconfig())
- else:
- print('try to connect to network...', self.s['count'])
- self.s['count'] += 1
- # 设置连接超时时间
- if self.s['count'] > self.s['check_count']:
- self.s['status'] = 'recheck'
- self.s['count'] = 0
- elif self.s['status'] == 'recheck':
- if not self.wlan.isconnected():
- self.wlan.active(False)
- print('error: wifi disconnect')
- self.s['status'] = 'start connect'
- def _do_connect(self, recheck=False):
- if not self.wlan.isconnected():
- self.wlan.active(True)
- self.wlan.connect(self.ssid, self.password)
- print('connecting to network...', self.ssid)
- while not self.wlan.isconnected():
- pass
- print('network config:', self.wlan.ifconfig())
- def get_wifi_addr(self):
- return self.get_wifi_ifconfig()[0]
- def get_wifi_ifconfig(self):
- # # 等待 check_disconnect() WiFi连接成功再返回
- # while not self.s['status'] == 'recheck':
- # pass
- # # 返回: ('192.168.31.123', '255.255.255.0', '192.168.31.1', '192.168.31.1')
- return self.wlan.ifconfig()
-
- my_wifi = MyWifi()
- # 协程的方式
- import uasyncio
- async def wifi_do_work():
- while True:
- my_wifi.check_disconnect()
- await uasyncio.sleep_ms(1000)
- if __name__ == '__main__':
- uasyncio.run(wifi_do_work())
|