树莓派Pico W如何实现lot项目中的通信异常捕捉

2. 设置 WiFi 连接

首先,需要连接到 WiFi 网络。可以使用 network 模块进行 WiFi 连接,并捕获可能发生的异常。
 
import network
import time
 
def connect_to_wifi(ssid, password):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print("Connecting to WiFi...")
        wlan.connect(ssid, password)
        start_time = time.time()
        while not wlan.isconnected():
            if time.time() - start_time > 10:
                print("Failed to connect to WiFi")
                return False
            time.sleep(1)
    print("WiFi connected:", wlan.ifconfig())
    return True
 
# 示例调用
ssid = "your_SSID"
password = "your_password"
connect_to_wifi(ssid, password)
 

3. 使用 HTTP 请求进行通信

使用 urequests 模块进行 HTTP 请求,同时捕获可能的异常,例如网络连接错误、超时等。
 
 
import urequests
 
def get_data_from_server(url):
    try:
        response = urequests.get(url)
        response.raise_for_status() # 检查是否有HTTP错误
        print("Response:", response.text)
        return response.json()
    except urequests.exceptions.HTTPError as e:
        print("HTTP error occurred:", e)
    except urequests.exceptions.ConnectionError as e:
        print("Connection error occurred:", e)
    except urequests.exceptions.Timeout as e:
        print("Timeout error occurred:", e)
    except Exception as e:
        print("An unexpected error occurred:", e)
    return None
 
# 示例调用
url = "http://api.ipify.org?format=json"
data = get_data_from_server(url)
 
 

4. 重试机制

为了提高通信的鲁棒性,可以一个重试机制,当请求失败时多次重试。
 
 
def get_data_with_retries(url, retries=3, delay=2):
    attempt = 0
    while attempt < retries:
        try:
            response = urequests.get(url)
            response.raise_for_status()
            print("Response:", response.text)
            return response.json()
        except Exception as e:
            print(f"Attempt {attempt + 1} failed with error: {e}")
            attempt += 1
            time.sleep(delay)
    print("All attempts failed.")
    return None
 
# 示例调用
data = get_data_with_retries(url)
 

综合示例代码

 
import network
import urequests
import time
 
# 连接到WiFi
def connect_to_wifi(ssid, password):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print("Connecting to WiFi...")
        wlan.connect(ssid, password)
        start_time = time.time()
        while not wlan.isconnected():
            if time.time() - start_time > 10:
                print("Failed to connect to WiFi")
                return False
            time.sleep(1)
    print("WiFi connected:", wlan.ifconfig())
    return True
 
# 从服务器获取数据,并实现重试机制
def get_data_with_retries(url, retries=3, delay=2):
    attempt = 0
    while attempt < retries:
        try:
            response = urequests.get(url)
            response.raise_for_status() # 检查是否有HTTP错误
            print("Response:", response.text)
            return response.json()
        except urequests.exceptions.HTTPError as e:
            print(f"Attempt {attempt + 1} failed with HTTP error: {e}")
        except urequests.exceptions.ConnectionError as e:
            print(f"Attempt {attempt + 1} failed with Connection error: {e}")
        except urequests.exceptions.Timeout as e:
            print(f"Attempt {attempt + 1} failed with Timeout error: {e}")
        except Exception as e:
            print(f"Attempt {attempt + 1} failed with unexpected error: {e}")
        attempt += 1
        time.sleep(delay)
    print("All attempts failed.")
    return None
 
# 主程序
def main():
    ssid = "your_SSID"
    password = "your_password"
    url = "http://api.ipify.org?format=json"
    
    # 连接到WiFi
    if connect_to_wifi(ssid, password):
        # 获取数据
        data = get_data_with_retries(url)
        if data:
            print("Received data:", data)
        else:
            print("Failed to retrieve data.")
    else:
        print("Failed to connect to WiFi.")
 
# 运行主程序
main()
 

代码说明

  • connect_to_wifi(ssid, password):该函数连接到指定的 WiFi 网络。如果连接失败,会在 10 秒内不断重试,并在连接成功后打印连接信息。
  • get_data_with_retries(url, retries=3, delay=2):该函数尝试从指定的 URL 获取数据。如果请求失败,会在设定的重试次数内进行多次重试,并在每次重试之间等待指定的延迟。函数会捕获并处理不同类型的异常,包括 HTTP 错误、连接错误、超时错误以及其他意外错误。
  • main():主程序函数,首先连接到 WiFi,然后尝试从服务器获取数据。如果连接成功并成功获取数据,会打印结果;如果失败,则打印错误信息。
 

注意事项

  • 确您将 your_SSID 和 your_password 替换为实际的 WiFi 网络凭据。

  • 确保 URL 地址是有效的,并且能够响应 HTTP 请求。

  • 通过适当调整 retries 和 delay 参数,可以根据需要控制重试的次数和间隔。

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值