【ESP32+Python】WIFI连接包括固定账号密码+选择WIFI在输入密码

import network
import time

# 创建WLAN对象
wlan = network.WLAN(network.STA_IF)


def scan_and_display_wifi_networks():
    # 激活接口
    wlan.active(True)
    # 扫描附近的WiFi网络
    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]  # MAC地址
        channel = net[2]  # 信道
        RSSI = net[3]  # 信号强度
        authmode = net[4]  # 加密方式
        hidden = net[5]  # 是否隐藏SSID

        # 将加密方式转换为人类可读的格式
        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 networks



def connect_to_wifi(max_attempts=10):
    attempt_count = 0
# ---- 固定wifi -------
    while not wlan.isconnected() and attempt_count < max_attempts:
        print(f"尝试连接WiFi... (第 {attempt_count + 1} 次尝试)")
        wlan.connect('wifi账号', 'wifi密码')# 只支持2.4的wifi
        attempt_count += 1
        time.sleep(3)  # 等待3秒后再次尝试连接

    if wlan.isconnected():
        print("WiFi连接成功!")
        print("IP地址:", wlan.ifconfig()[0])
        mqtt()
        send_post_request()
        start_websocket()
    else:
        print(f"WiFi连接失败,尝试了 {max_attempts} 次。")
# ---- 固定wifi -------
# ---- 选择wifi -------
# try:
#  selection = int(input("请选择要连接的WiFi网络编号:")) - 1
#  if 0 <= selection < len(networks):
#     ssid = networks[selection][0].decode('utf-8')
#     password = input(f"请输入{ssid}的密码:")
#     wlan.connect(ssid, password)
#    if wlan.isconnected():
#       print("WiFi连接成功!")
#       print("IP地址:", wlan.ifconfig()[0])
#       # 其他方法

#   else:
#     print("WiFi连接失败,请检查密码是否正确,并重试。")
#  else:
#       print("选择的网络编号不正确。")
#   except ValueError:
#    print("请输入一个有效的数字。")
# ---- 选择wifi -------

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)  # 等待1秒后重新扫描和连接



if __name__ == "__main__":
    main()

你可能感兴趣的:(ESP32+Python,python,单片机)