import network
import time
wlan = network.WLAN(network.STA_IF)def scan_and_display_wifi_networks():wlan.active(True)networks = wlan.scan()print("可用的WiFi网络:")for i, net in enumerate(networks):ssid = net[0].decode('utf-8') bssid = ''.join('%02x:' % b for b in net[1])[:-1] channel = net[2] RSSI = net[3] authmode = net[4] hidden = net[5] auth_modes = ['OPEN', 'WEP', 'WPA-PSK', 'WPA2-PSK', 'WPA/WPA2-PSK', 'WPA2']authmode_str = auth_modes[authmode] if authmode < len(auth_modes) else '未知'print(f"{i + 1}: SSID: {ssid}, BSSID: {bssid}, 信道: {channel}, 信号强度: {RSSI}, 加密方式: {authmode_str}, 隐藏: {hidden}")return networksdef connect_to_wifi(max_attempts=10):attempt_count = 0
while not wlan.isconnected() and attempt_count < max_attempts:print(f"尝试连接WiFi... (第 {attempt_count + 1} 次尝试)")wlan.connect('wifi账号', 'wifi密码')attempt_count += 1time.sleep(3) if wlan.isconnected():print("WiFi连接成功!")print("IP地址:", wlan.ifconfig()[0])mqtt()send_post_request()start_websocket()else:print(f"WiFi连接失败,尝试了 {max_attempts} 次。")
def main():while True:networks = scan_and_display_wifi_networks()if networks:print("执行连接。")connect_to_wifi()if wlan.isconnected():break else:print("未扫描到可用的WiFi网络。")time.sleep(3) if __name__ == "__main__":main()