使用 micropython 编写 ESP32-CAM 自动 OTA 更新程序
OTA 是什么 以及为什么要做 OTA?
之前我写过 C++ 版本的 ESP32-CAM OTA 程序(在platform上进行编码),在那边文章中写到过这个问题,在这里就不过多缀叙。
ESP32-CAM OTA解决方案介绍,自动OTA更新程序的编写
OTA更新逻辑
原理:
利用 micropython 中的 urequests 库,获取存放在 AWS S3 上的 version.json 文件,来判断当前 ESP32-CAM 运行的程序是否为最新版本的。如果存在最新版本,就进行 OTA 操作,不存在最新版本就运行当前版本。
AWS S3
因为我们要获取最新版本以及最新版本的程序,所以我们需要一个仓库来存放我们的代码。
这个仓库就是 AWS S3。
将要更新的程序以及其版本上传 AWS S3 存储桶,将 S3 权限设置为公开。
至于怎么设置 S3 存储桶权限,我在这篇文章中有写到。
ESP32 通过HTTPS进行OTA更新固件(在platform上进行编码)
可以看到在 S3 存储桶中存放有我们要更新的程序以及其版本的信息。
boot.py 和 main.py
boot.py 文件是 esp32-cam 在启动时首先运行的文件,默认是空白的,在运行完 boot.py 之后再运行主程序 main.py。
所以我们将 OTA 程序放在 boot.py 中,让它来更新我们的主程序 main.py 。
测试的更新文件
因为我们要进行 OTA更新,所以我们要有一个新的程序让我们更新,这里我准备的是一个 ESP32-CAM 的闪灯程序,能要我们 ESP32-CAM 的led灯以一定的频率闪烁。
我们还要准备一个版本文件说明要更新程序的版本。
这里的程序和文件将要上传AWS S3。
程序代码如下(flashlight.py):
from machine import Timer, Pin, PWM
import time
pwm = PWM(Pin(33))
pwm.freq(10)
版本文件如下(version.json):
{
"version":"1.2.1"
}
urequest
因为 micropython 支持的库只有 urequest ,所以之前没下载的朋友这里需要下载并要将它放在我们的 ESP32-CAM中。
我已将 urequest 上传百度云盘。urequest,提取码ccit
如何放入 ESP32-CAM 我在之前的文章中写过,使用 micropython 编写 ESP32-CAM 自动拍照程序
具体实现
理清楚流程之后,我们将编写程序。
这里的程序将放在 ESP32-CAM 中的 boot.py 文件中
代码如下:
# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
#import webrepl
#webrepl.start()
from machine import Timer, Pin
import time, network, ntptime
def connectWiFi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('your-ssid', 'your-password')
while not wlan.isconnected():
pass
print('network config: ', wlan.ifconfig())
connectWiFi()
import urequests as requests
# 存储桶URL
py_url = ""
version_url = ""
current_version = '1.2.0' # 自己定义版本
buzzer_pin = Pin(12, Pin.OUT)
def getBin():
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'}
response_version = requests.get(version_url, headers = header)
# 最新固件版本
lastest_version = response_version.json()['version']
print(lastest_version)
if lastest_version > current_version:
print("存在新版本!等待更新!")
response_py = requests.get(py_url, headers=header)
downloaded_file = response_py.content
if response_py.status_code == 200:
with open('main.py', 'wb') as f:
f.write(downloaded_file)
print("更新成功!!")
buzzer_pin.value(1)
time.sleep(1)
buzzer_pin.value(0)
else:
print("当前为最新版本!")
getBin()
因为这个程序获取到最新版本的程序之后是将其写入到 main.py 文件中,所以不需要重启 ESP32-CAM 就能直接运行程序。
至此,我已经完成 C++ 和 micropython 版的 OTA 更新程序。
分别在 PlatformIO 和 Thonny 进行编码。
ESP32-CAM OTA解决方案介绍,自动OTA更新程序的编写。
如果疑问欢迎提出。
参考资料:
ESP32-CAM OTA解决方案介绍,自动OTA更新程序的编写
ESP32 通过HTTPS进行OTA更新固件(在platform上进行编码)
使用 micropython 编写 ESP32-CAM 自动拍照程序