|
|
@@ -0,0 +1,77 @@
|
|
|
+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.tim = Timer(0)
|
|
|
+ self.s = {'status': 'start connect', 'count': 0, 'check_count': 3}
|
|
|
+ self.tim.init(period=1, mode=Timer.ONE_SHOT,callback=self.check_disconnect)
|
|
|
+
|
|
|
+
|
|
|
+ def check_disconnect(self, timer):
|
|
|
+ self.tim.init(period=1000, mode=Timer.ONE_SHOT,
|
|
|
+ callback=self.check_disconnect)
|
|
|
+ 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'
|
|
|
+ self.tim.init(period=1, mode=Timer.ONE_SHOT,
|
|
|
+ callback=self.check_disconnect)
|
|
|
+ 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()
|