自建OTA服务器,终端每次开机比较版本,如有新版本固件则下载更新
一、利用Apache建立http服务器端,在WEB服务器目录下上传新的固件及版本说明json文件
{
"ver":2022012502,
"file":"rtthread_no_restart.rbl"
}
JSON格式比较简,第一行为版本,最好为数字字符便于终端转换为版本比较,第二行为对应的WEB服务器的新的固件文件。
二、源文件
uint32_t ota_compile_time(char const *time) {
char s_month[5];
int month,day,year;
struct tm t = {0};
static const char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
sscanf(time,"%s %d %d",s_month,&day,&year);
month = (strstr(month_names,s_month)-month_names)/3;
t.tm_mon = month;
t.tm_mday = day;
t.tm_year = year;
uint32_t ver=0;
ver = year*1000000;
ver += (month+1)*10000;
ver += day*100;
ver += 99;
return ver;
}
static uint32_t new_ver;
void ota_task(void *parameter)
{
// while(1)
{
char ver_uri[50]={0};
uint32_t ver=0;
char fm_file[100]={0};
snprintf(ver_uri,50,"%s/ver.json",flash_db_syscfg_ptr()->update_uri);
if ( webclient_get_file(ver_uri, "/flash/new_ver.json") ==0 ){
int fd;
fd = open("/flash/new_ver.json",O_RDONLY);
if( fd>=0 ){
char buf[100]={0};
int size;
size = read(fd, buf, sizeof(buf));
if( size ){
cJSON *item;
cJSON* root = cJSON_Parse((char *)buf);
if( root ){
cJSON *date = cJSON_GetObjectItem(root,"ver"); //获取这个对象成员
if( date ){
ver = (uint32_t)date->valueint;
}
else{
LOG_E( "can not get the version\r\n");
}
if( ver>flash_db_syscfg_ptr()->ver && ver>ota_compile_time(__DATE__) ){
cJSON *file = cJSON_GetObjectItem(root,"file"); //获取这个对象成员
if( file ){
rt_thread_delay(1000);
snprintf(fm_file,sizeof(fm_file),"%s/%s",flash_db_syscfg_ptr()->update_uri,file->valuestring);
new_ver = ver;
http_ota_fw_download(fm_file);
}
}
else{
flash_db_syscfg_ptr()->ver = ver;
LOG_D( "no new version:%d\r\n",flash_db_syscfg_ptr()->ver );
rt_pin_write(UPDATE_OTA_PIN, PIN_HIGH);
}
cJSON_Delete(root);
}
else{
LOG_E( "version filer format error\r\n");
}
}
close(fd);
// unlink("/flash/new_ver.json");
}
}
else{
LOG_E( "can not get the version file\r\n");
}
}
rt_pin_write(UPDATE_OTA_PIN, PIN_HIGH);
ota_running = 0;
}
void ota_save_ver(void)
{
flash_db_syscfg_ptr()->ver = new_ver;
rt_thread_delay(1500);
}
代码说明
webclient_get_file(ver_uri, "/flash/new_ver.json")
下载版本说明文件
cJSON *date = cJSON_GetObjectItem(root,"ver");
ver = (uint32_t)date->valueint;
解释JSON文件获取版本
if( ver>flash_db_syscfg_ptr()->ver && ver>ota_compile_time(__DATE__) ){
比较版本
http_ota_fw_download(fm_file);
下载指定版本固件
服务器可存放多个版本的固件可实现版本回退、自动更新、更新指定版本固件功能