前言
使用掌控板,获取当前检测到的wifi信息.
代码
#---------------------------------------------
# func5: 联网5--youkai
#
#---------------------------------------------
import network
import time
# 十进制数字转换为字符
def int2char (x):
numbers = {
0 : '0',
1 : '1',
2 : '2',
3 : '3',
4 : '4',
5 : '5',
6 : '6',
7 : '7',
8 : '8',
9 : '9',
10 : 'a',
11 : 'b',
12 : 'c',
13 : 'd',
14 : 'e',
15 : 'f',
}
return numbers.get(x,None)
def int_2_dec( value , key_num):
a=value%key_num
result=''
#print("value",value)
if (a == 0) & (value == 0 ):
result = '0'
return result
#print("result",result)
#print("a!=0",a!=0)
#print("value > 0",value > 0)
while True :
if a == 0:
if value <= 0:
break
#print("enter")
#print("a",a)
temp=int2char(a)
#temp=hex(a).replace('0x','')
result=temp+result
#print("result",result)
value=(value-a)//key_num
#print("value",value)
a=value%key_num
#print("a",a)
return result
def print_scan_wifi (y):
print(type(y)) # 返回值为list类型
print(y[0][0]) # b'youkai'
print(type(y[0][0])) # b'youkai'
print(y[1]) # (b'TP-LINK_D89B', b'\xb0\x95\x8e\xc4\xd8\x9b', 6, -31, 4, False)
scan_wifi_list_len=len(y) # 获取返回值list的长度,识别到N个wifi
print('scan_wifi_list_len =',scan_wifi_list_len)
for temp in range(scan_wifi_list_len):
wifi_name=y[temp][0]
# PS:注意使用XX.decode(),否则会报类型错误 参考 https://www.cnblogs.com/fh-fendou/p/8310425.html
#print('wifi_name',wifi_name)
#print('wifi_name type',type(wifi_name))
temp_y=int_2_dec(temp,10) +' '+ wifi_name.decode()
print('wifi',temp_y)
return
def wifi_connect():
# 1. 创建wifi
wlan = network.WLAN(network.STA_IF)
# 2. 启动wifi
wlan.active(True)
# 3. 搜索当前可识别的wifi
y=wlan.scan()
# 4. 打印信息
print_scan_wifi(y)
# 5.连接wifi
wlan_status=wlan.isconnected() # check if the station is connected to an AP
if wlan_status == True:
print("connect wifi")
else:
print("don't connect wifi")
wlan.connect(SSID, PASSWORD) # connect to an AP
#time.sleep(100)
#wlan.disconnect()
# 6. 打印连接的wifi信息
temp_mac=wlan.config('mac') # get the interface's MAC address
print('temp_mac',temp_mac)
print('temp_mac_type',type(temp_mac))
temp_IP=wlan.ifconfig() # get the interface's IP/netmask/gw/DNS addresses
print('temp_IP',temp_IP)
wlan_status2=wlan.isconnected()
print('wlan_status2',wlan_status2)
if wlan_status2 == True:
print("connect wifi")
else:
print("don't connect wifi")
return
SSID = "XXX" #WiFi名称
PASSWORD = "XXXXXXXX" #WiFi密码
wifi_connect()
结果
PS:wifi_name.decode()
注意使用XX.decode(),否则会报类型错误 参考 https://www.cnblogs.com/fh-fendou/p/8310425.html
TypeError: can’t convert ‘bytes’ object to str implicitly
存疑
为什么使用wlan.isconnected(),一直返回false