1、连接指定WiFi
def connectWifi(ssid, passwd="", mode="", timeout=20):
'''
连接指定WIFI。
mode取值:WEP, WPA, WPA2, WPAPSK, WPA2PSK, UNKWON
'''
global global_logger
pywifi.set_loglevel(logging.ERROR)
wifi = pywifi.PyWiFi()
ifaces = wifi.interfaces()
if len(ifaces) == 0:
global_logger.warning("Can not find wifi interface.")
return False
iface = ifaces[0]
print("Disconnect current wifi.")
iface.disconnect() # 先断开网络。
time.sleep(3)
setmode = const.AKM_TYPE_UNKNOWN
if mode == "WPA":
setmode = const.AKM_TYPE_WPA
elif mode == "WPAPSK":
setmode = const.AKM_TYPE_WPAPSK
elif mode == "WPA2":
setmode = const.AKM_TYPE_WPA2
elif mode == "WPA2PSK":
setmode = const.AKM_TYPE_WPA2PSK
profile = pywifi.Profile()
profile.ssid = ssid # 如: RoboVac_330G_400059
profile.key = passwd
profile.auth = const.AUTH_ALG_OPEN
profile.akm.append(setmode) # 无加密
# profile.cipher = const.CIPHER_TYPE_UNKNOWN
tmp_profile = iface.add_network_profile(profile)
global_logger.info("Connecting to wifi " + ssid)
iface.connect(tmp_profile)
tmout = 0
while (tmout < timeout):
if iface.status() == const.IFACE_CONNECTED:
#global_logger.warning("Connect to wifi success:" + iface.scan_results()[0].ssid)
global_logger.info("Connect to wifi {} SUCCESS!".format(ssid))
return True
else:
time.sleep(5)
tmout = tmout + 5
print("Connect new wifi timeout.")
return False
2、连接智能设备WiFi
def connectMachineWifi(ssid, timeout=20):
'''
连接到智能设备WiFi。用于配网测试。
:param ssid: 智能设备的WIFI名称。
智能设备的WIFI不涉及密码。
返回:连接WIFI成功返回True,失败返回False。
'''
global global_logger
pywifi.set_loglevel(logging.ERROR)
wifi = pywifi.PyWiFi()
ifaces = wifi.interfaces()
if len(ifaces) == 0:
print("Can not find wifi interface.")
return False
iface = ifaces[0]
print("Disconnect current wifi.")
iface.disconnect() #先断开网络。
time.sleep(5)
profile = pywifi.Profile()
profile.ssid = ssid
profile.auth = const.AUTH_ALG_OPEN
profile.akm.append(const.AKM_TYPE_NONE) #无加密
# profile.cipher = const.CIPHER_TYPE_NONE #无加密
tmp_profile = iface.add_network_profile(profile)
global_logger.info("Connecting to wifi {}".format(ssid))
iface.connect(tmp_profile)
tmout = 0
while (tmout < timeout):
if iface.status() == const.IFACE_CONNECTED:
time.sleep(2)
# global_logger.info("Connect to wifi success:{}".format(iface.scan_results()[0].ssid.encode(encoding="utf-8", errors="replace")))
global_logger.info("Connect to {} SUCCESS!".format(ssid))
return True
else:
time.sleep(5)
tmout = tmout + 5
print("Connect new wifi TIMEOUT.")
return False