树莓派66/100 - 用Pico W访问互联网
扫描WIFI热点
树莓派Pico W的一个重要功能是可以连接WIFI,所以马上扫描一下附近的WIFI热点信号。
import networkwlan = network.WLAN(network.STA_IF) wlan.active(True) access_points = wlan.scan() for ap in access_points: print(ap)
我的设备输出的信息如下:
(b'H***', b'\xfc`\x9b\xe4{\xe1', 1, -98, 7, 1)(b'TP-LINK***', b'\x14\xcf\x92\x91v\xbe', 8, -41, 7, 9)(b'TP-LINK***\xe5\xa4\xa7\xe7\xbd\x91', b'\xd0v\xe7\xb4\x07\xa6', 3, -72, 7, 1)(b'', b'\xfc`\x9b\xe4}\x0f', 1, -67, 0, 1)(b'TP-LINK***', b'0\xb4\x9e\xc7\xd1v', 4, -84, 7, 1)(b'', b'\xfc`\x9b\xda\xc0N', 1, -74, 0, 1)(b'H***', b'\xfc`\x9b\xe4}\r', 1, -62, 7, 1)(b'w***', b'\xcc4)\x96\x9d\x93', 8, -76, 7, 4)(b'ChinaNet-***', b'\xb8\xa1Jj\xf9E', 4, -83, 3, 1)(b'iTV-***', b'\xba\xa1JZ\xf9E', 4, -80, 3, 1)
访问点的信息由6段信息的无组构成,说明文档在这里。
6段信息为:(ssid, bssid, channel, RSSI, security, hidden)
ssid:服务集标识,Service Set Identifier的缩写,通俗地说,是无线网热点的名称。
bssid:48个二进制位,6个字节,可以理解为访问点的MAC地址。
channel:通道号
RSSI:信号强度(Received signal strength indicator),正常信号强度应为-40 dbm ~ -85 dbm之间,小于 -90 dbm 的信号则很糟糕,几乎无法连接。
security:安全连接方式,说明文档上写着这样几种:
0 – open
1 – WEP
2 – WPA-PSK
3 – WPA2-PSK
4 – WPA/WPA2-PSK
可见还是隐藏:
0 – visible
1 – hidden
下面的代码按信号强弱将连接点排序输出:
import networkimport binasciiwlan = network.WLAN(network.STA_IF) wlan.active(True) access_points = wlan.scan()# 按信号强弱排序access_points.sort(key=lambda x:x[3], reverse=True)for ssid, bssid, channel, RSSI, security, hidden in access_points: print(ssid, binascii.hexlify(bssid), channel, RSSI, security, hidden)
连接WIFI
import networkimport timewlan = network.WLAN(network.STA_IF)wlan.active(True)wlan.connect('你的WIFI名称', '你的WIFI密码')while not wlan.isconnected() and wlan.status() >= 0: print("Waiting to connect:") time.sleep(1) print(wlan.ifconfig())
官方给出的更可靠的、考虑了一些异常情况的代码是:
import networkimport timessid = 'XXXXXXXXX'password = 'PPPPPPPPPPPP'wlan = network.WLAN(network.STA_IF)wlan.active(True)wlan.connect(ssid, password)# Wait for connect or failmax_wait = 10while max_wait > 0: if wlan.status() < 0 or wlan.status() >= 3: break max_wait -= 1 print('waiting for connection...') time.sleep(1)# Handle connection errorif wlan.status() != 3: raise RuntimeError('network connection failed')else: print('connected') status = wlan.ifconfig() print( 'ip = ' + status[0] )
连接状态的对应表:
#define CYW43_LINK_DOWN (0)#define CYW43_LINK_JOIN (1)#define CYW43_LINK_NOIP (2)#define CYW43_LINK_UP (3)#define CYW43_LINK_FAIL (-1)#define CYW43_LINK_NONET (-2)#define CYW43_LINK_BADAUTH (-3)
有时,可能需要设置WIFI的国家代码,中国的代码是CN:
import rp2rp2.country('CN')
查询网卡的MAC地址
import networkimport ubinasciiwlan = network.WLAN(network.STA_IF)wlan.active(True)mac = ubinascii.hexlify(network.WLAN().config('mac'),':').decode()print(mac)# Other things you can queryprint(wlan.config('channel'))print(wlan.config('essid'))print(wlan.config('txpower'))
获取网页内容
获取网页内容也变得非常简单,下面的代码获取南京的天气情况:
import urequestsr = urequests.get('http://api.seniverse.com/v3/weather/now.json?key=SwwwfskBjB6fHVRon&location=nanjing&language=en&unit=c')print(r.content)r.close()
注意连接使用完毕后要close()。