You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将curl+Bash烧录Arduino的脚本转Python时遇超时问题求助

解决Python上传Hex文件到ESP-link超时的问题

我看了你的问题,同步步骤正常但上传固件时超时,核心原因是Python代码的文件上传格式和原curl脚本不一致,导致ESP-link的服务器无法正确处理请求,进而卡住不返回响应,最终触发超时。

问题分析

原bash脚本里的curl命令:

curl -m 20 -s -g -d @/tmp/arduino_build_274266/SMI_6_0_1.ino.hex http://192.168.4.1/pgmmega/upload

这里的-d @file是把Hex文件的原始内容直接作为POST请求的主体发送,请求格式是纯文本/二进制,没有额外的multipart包装。

而你的Python代码用了files参数:

file = {'upload_file': open('/home/wander/app_llamadores/SMI_6_0_1.ino.hex', 'rb')}
rupload = requests.post(urlupload, files=file, timeout=20)

files参数会自动构建multipart/form-data格式的请求,包含字段名、文件名、边界分隔符等额外信息——这和curl发送的请求格式完全不同,ESP-link的pgmmega/upload端点大概率只期望直接接收Hex文件的原始数据,所以无法解析multipart请求,导致服务器挂起,最终触发读取超时。

修改后的Python代码

把文件上传部分改成直接发送原始内容,用data参数替代files,同时加上更完善的异常处理:

#!/usr/bin/env python3
import requests
import time

urlsync = 'http://192.168.4.1/pgmmega/sync'
urlupload = 'http://192.168.4.1/pgmmega/upload'

# 发送POST请求重置Arduino(对应原curl的-m 10,设置超时10秒)
try:
    rsync_post = requests.post(urlsync, timeout=10)
    print(f"POST Sync Status: {rsync_post.status_code}")
except requests.exceptions.RequestException as e:
    print(f"POST Sync Failed: {str(e)}")
time.sleep(0.5)

# 发送GET请求完成同步
try:
    rsync_get = requests.get(urlsync, timeout=10)
    print(f"GET Sync Status: {rsync_get.status_code}")
except requests.exceptions.RequestException as e:
    print(f"GET Sync Failed: {str(e)}")
time.sleep(0.1)

# 上传Hex文件:读取原始内容作为POST请求体
hex_file_path = '/home/wander/app_llamadores/SMI_6_0_1.ino.hex'
try:
    # 使用with语句自动关闭文件,更安全
    with open(hex_file_path, 'rb') as hex_file:
        hex_content = hex_file.read()
    
    # 发送原始文件内容,对应curl的-d @file
    upload_response = requests.post(urlupload, data=hex_content, timeout=20)
    print(f"Upload Status: {upload_response.status_code}")
    print(f"Upload Response: {upload_response.text}")
except requests.exceptions.RequestException as e:
    print(f"Upload Failed: {str(e)}")

额外注意点

  1. 超时设置:原curl的-m 20是总超时(连接+读取),requests的timeout=20和它行为一致;如果需要更精细控制,可以设为tuple(连接超时, 读取超时),比如timeout=(5, 20)。
  2. 请求格式验证:可以用curl -v查看原请求的详细头信息,对比Python代码发送的请求(可以手动指定headers={'Content-Type': 'text/plain'},和curl默认的application/x-www-form-urlencoded接近,但ESP-link可能不关心这个,只要内容是原始Hex即可)。
  3. 文件读取:用with语句打开文件能确保文件自动关闭,避免资源泄漏。

内容的提问来源于stack exchange,提问作者Wander Jose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:51:53