app_update
authorkyz <kyz@kyz-vbox.myguest.virtualbox.org>
Fri, 18 Jul 2025 07:00:15 +0000 (15:00 +0800)
committerkyz <kyz@kyz-vbox.myguest.virtualbox.org>
Fri, 18 Jul 2025 07:00:15 +0000 (15:00 +0800)
app/inc/alarmmonitor.h
app/inc/am_version.h
app/inc/downloader.h
app/src/am_main.c
app/src/downloader.c
app/src/iot_report.c
app/src/lcd.c
app/src/ota.c

index 11ab66180e2d3883afb2d19ce2c79b609ca413ed..1de729e95107007e1f905b504897528f55540b2c 100644 (file)
@@ -26,8 +26,6 @@
 //#include "led.h"
 //#include "sensor.h"
 
-#define SW_VERSION  "v1.0"
-
 #ifdef __x86_64__
 
 //ON PC for debug ........
index 0526dbd1136ee5b6281894946babcbad0c0cab14..10bfeccdd57693231016c5ab536cd5ac3ebf5955 100644 (file)
@@ -1,6 +1,6 @@
 #ifndef __AM_VERSION_H__
 #define __AM_VERSION_H__
 
-#define  AM_VERSION "1.0"
+#define  AM_VERSION "1.2"
 
 #endif //ifndef __AM_VERSION_H__
index 60fe1328986e8eeaee199ef65b5cd15009eaf1e9..2b38aee0ab1f02d06c317f668b15a374aca00ee0 100644 (file)
@@ -4,19 +4,33 @@
 #include <uv.h>
 #include <curl/curl.h>
 #include <stdint.h>
+#include <stddef.h>
 
+typedef void (*complete_cb_t)(int status, void* userdata);
+typedef void (*progress_cb_t)(double percentage, void* userdata);
+int http_download( char * url, char *save_path, progress_cb_t progress_cb, complete_cb_t complete_cb );
+
+// OTA 升级上下文结构
+struct download_request;
+typedef struct ota_context {
+    char temp_path[256];       // 临时文件路径
+    char** saved_argv;         // 程序参数 (用于重启)
+    int argc;                  // 参数数量
+    struct download_request *req;
+} ota_context;
+
+// 下载请求结构
 typedef struct download_request {
-    char url[256];
-    char output_path[256];
-    uv_loop_t* loop;
-    uv_fs_t file_handle;
-    FILE* file_ptr;
-    CURL* curl_handle;
-    int64_t total_size;
-    int64_t downloaded;
-    void (*progress_cb)(double percentage, void* userdata);
-    void (*complete_cb)(int status, void* userdata);
-    void* userdata;
+    char url[256];             // 下载URL
+    char output_path[256];     // 输出文件路径
+    uv_loop_t* loop;           // libuv事件循环
+    FILE* file_ptr;            // 文件指针
+    CURL* curl_handle;         // CURL句柄
+    int64_t total_size;        // 文件总大小
+    int64_t downloaded;        // 已下载大小
+    void (*progress_cb)(double percentage, void* userdata); // 进度回调
+    void (*complete_cb)(int status, void* userdata);        // 完成回调
+    void* userdata;            // 用户数据
 } download_request;
 
 // 初始化下载模块
index fc8932c329f89fd7e0e8a785b7bc09a72bcd10c5..bfb04c44d3a3b1423c4c31db4ab963f601a13416 100644 (file)
@@ -498,7 +498,7 @@ int main( int argc, char ** argv )
     am_dev_t *dev = &g_dev;
 
     if( argc > 1 ){
-        printf( "\n\nam_app version: %s\n\n", SW_VERSION );
+        printf( "\n\nam_app version: V%s\n\n", AM_VERSION );
         exit( 0 );
     }
 
@@ -510,7 +510,7 @@ int main( int argc, char ** argv )
 
     am_log_init();
 
-    AM_LOGI( "Alarm Monitor start ..." );
+    AM_LOGI( "Alarm Monitor[%s] start ...", AM_VERSION );
 
     memset( dev, 0, sizeof( am_dev_t ) );
     dev->loop = uv_default_loop();
@@ -561,7 +561,7 @@ int main( int argc, char ** argv )
 {
 
 extern int download_test( void );
-    download_test();
+//    download_test();
 }
     uv_run( dev->loop, UV_RUN_DEFAULT );
 
index 861aed42cd3a3f4b6b521a8ee8afeac4d15a322c..82903e86f387d6acfbb2ef9035562da50b8f72d9 100644 (file)
@@ -5,9 +5,9 @@
 #include <unistd.h>
 #include <fcntl.h>
 #include <sys/stat.h>
-#include "alarmmonitor.h"
+#include <errno.h>
 
-static CURLM* curl_multi_handle;
+static CURLM* curl_multi_handle = NULL;
 static uv_timer_t timeout;
 
 // libcurl socket回调
@@ -30,11 +30,18 @@ static size_t write_data(void* ptr, size_t size, size_t nmemb, void* userdata);
 
 // 初始化下载模块
 void download_init(uv_loop_t* loop) {
+    if (curl_multi_handle) return; // 防止重复初始化
+    
     curl_global_init(CURL_GLOBAL_ALL);
     curl_multi_handle = curl_multi_init();
+    if (!curl_multi_handle) {
+        fprintf(stderr, "Failed to create curl multi handle\n");
+        return;
+    }
+    
     curl_multi_setopt(curl_multi_handle, CURLMOPT_SOCKETFUNCTION, curl_socket_cb);
     curl_multi_setopt(curl_multi_handle, CURLMOPT_SOCKETDATA, loop);
-
+    
     uv_timer_init(loop, &timeout);
 }
 
@@ -49,6 +56,12 @@ download_request* download_file(
 ) {
     // 创建请求对象
     download_request* req = calloc(1, sizeof(download_request));
+    if (!req) {
+        fprintf(stderr, "Failed to allocate download_request\n");
+        return NULL;
+    }
+    
+    // 设置基本属性
     strncpy(req->url, url, sizeof(req->url)-1);
     strncpy(req->output_path, output_path, sizeof(req->output_path)-1);
     req->loop = loop;
@@ -57,38 +70,25 @@ download_request* download_file(
     req->userdata = userdata;
     req->total_size = -1;
     req->downloaded = 0;
-
-    // 打开文件前检查目录是否存在
-    char* dir_path = strdup(output_path);
-    char* dir_end = strrchr(dir_path, '/');
-    if (dir_end) {
-        *dir_end = '\0'; // 截断到目录部分
-
-        // 检查目录是否存在
-        if (access(dir_path, F_OK) != 0) {
-            fprintf(stderr, "Directory does not exist: %s\n", dir_path);
-            free(dir_path);
-            if (complete_cb) complete_cb(-1, userdata);
-            free(req);
-            return NULL;
-        }
-    }
-    free(dir_path);
-
+    
     // 打开文件
-    int fd = open(output_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
-    if (fd < 0) {
-        perror("open file failed");
-        if (complete_cb) complete_cb(-1, userdata);
+    req->file_ptr = fopen(output_path, "wb");
+    if (!req->file_ptr) {
+        fprintf(stderr, "Failed to open file: %s, error: %s\n", 
+                output_path, strerror(errno));
         free(req);
         return NULL;
     }
-    req->file_handle.data = req;
-    uv_fs_open(loop, &req->file_handle, output_path, O_WRONLY | O_CREAT | O_TRUNC, 0644, NULL);
-    req->file_ptr = fdopen(fd, "wb");
-
+    
     // 配置CURL
     req->curl_handle = curl_easy_init();
+    if (!req->curl_handle) {
+        fprintf(stderr, "Failed to create curl easy handle\n");
+        fclose(req->file_ptr);
+        free(req);
+        return NULL;
+    }
+    
     curl_easy_setopt(req->curl_handle, CURLOPT_URL, url);
     curl_easy_setopt(req->curl_handle, CURLOPT_WRITEFUNCTION, write_data);
     curl_easy_setopt(req->curl_handle, CURLOPT_WRITEDATA, req);
@@ -97,39 +97,47 @@ download_request* download_file(
     curl_easy_setopt(req->curl_handle, CURLOPT_PROGRESSDATA, req);
     curl_easy_setopt(req->curl_handle, CURLOPT_FOLLOWLOCATION, 1L);
     curl_easy_setopt(req->curl_handle, CURLOPT_TIMEOUT, 30L); // 30秒超时
-    curl_easy_setopt(req->curl_handle, CURLOPT_PRIVATE, req);
-
-    // 添加 HTTP 状态码和错误重定向设置
-    curl_easy_setopt(req->curl_handle, CURLOPT_FAILONERROR, 1L); // 400+ 状态码视为错误
-    curl_easy_setopt(req->curl_handle, CURLOPT_FOLLOWLOCATION, 1L); // 跟随重定向
-    curl_easy_setopt(req->curl_handle, CURLOPT_MAXREDIRS, 5L); // 最大重定向次数
-
+    curl_easy_setopt(req->curl_handle, CURLOPT_PRIVATE, req); // 关联请求对象
+    curl_easy_setopt(req->curl_handle, CURLOPT_FAILONERROR, 1L); // 将HTTP错误视为失败
+    
     // 添加到multi handle
-    curl_multi_add_handle(curl_multi_handle, req->curl_handle);
-
+    CURLMcode res = curl_multi_add_handle(curl_multi_handle, req->curl_handle);
+    if (res != CURLM_OK) {
+        fprintf(stderr, "curl_multi_add_handle failed: %s\n", curl_multi_strerror(res));
+        curl_easy_cleanup(req->curl_handle);
+        fclose(req->file_ptr);
+        free(req);
+        return NULL;
+    }
+    
     // 检查超时
     int running_handles;
     curl_multi_socket_action(curl_multi_handle, CURL_SOCKET_TIMEOUT, 0, &running_handles);
     timeout_cb(NULL); // 立即检查超时
-
+    
     return req;
 }
 
 // 清理下载资源
 void download_cleanup(download_request* req) {
     if (!req) return;
-
+    
+    // 关闭文件
     if (req->file_ptr) {
-        fclose(req->file_ptr);
+        if (fclose(req->file_ptr)) {
+            perror("Failed to close file");
+        }
         req->file_ptr = NULL;
     }
-
+    
+    // 清理CURL资源
     if (req->curl_handle) {
         curl_multi_remove_handle(curl_multi_handle, req->curl_handle);
         curl_easy_cleanup(req->curl_handle);
         req->curl_handle = NULL;
     }
-
+    
+    // 释放请求对象
     free(req);
 }
 
@@ -139,22 +147,35 @@ static int curl_socket_cb(CURL* easy, curl_socket_t s, int action, void* userp,
     uv_loop_t* loop = (uv_loop_t*)userp;
     uv_poll_t* poll_handle;
     int events = 0;
-
+    
     if (action == CURL_POLL_IN || action == CURL_POLL_OUT || action == CURL_POLL_INOUT) {
         if (!socketp) {
             // 新建poll handle
             poll_handle = malloc(sizeof(uv_poll_t));
-            uv_poll_init_socket(loop, poll_handle, s);
+            if (!poll_handle) {
+                fprintf(stderr, "Failed to allocate poll_handle\n");
+                return -1;
+            }
+            
+            if (uv_poll_init_socket(loop, poll_handle, s)) {
+                fprintf(stderr, "uv_poll_init_socket failed\n");
+                free(poll_handle);
+                return -1;
+            }
+            
             curl_multi_assign(curl_multi_handle, s, poll_handle);
         } else {
             poll_handle = (uv_poll_t*)socketp;
         }
-
+        
         if (action == CURL_POLL_IN) events = UV_READABLE;
         else if (action == CURL_POLL_OUT) events = UV_WRITABLE;
         else if (action == CURL_POLL_INOUT) events = UV_READABLE | UV_WRITABLE;
-
-        uv_poll_start(poll_handle, events, poll_cb);
+        
+        if (uv_poll_start(poll_handle, events, poll_cb)) {
+            fprintf(stderr, "uv_poll_start failed\n");
+            return -1;
+        }
     } else if (action == CURL_POLL_REMOVE) {
         if (socketp) {
             uv_poll_t* poll_handle = (uv_poll_t*)socketp;
@@ -163,28 +184,38 @@ static int curl_socket_cb(CURL* easy, curl_socket_t s, int action, void* userp,
             curl_multi_assign(curl_multi_handle, s, NULL);
         }
     }
-
+    
     return 0;
 }
 
 static void destroy_curl_handle(uv_poll_t* poll_handle) {
+    if (!poll_handle) return;
     uv_close((uv_handle_t*)poll_handle, (uv_close_cb)free);
 }
 
 static void poll_cb(uv_poll_t* handle, int status, int events) {
+    if (status < 0) {
+        fprintf(stderr, "poll_cb error: %s\n", uv_strerror(status));
+        return;
+    }
+    
     int flags = 0;
     if (events & UV_READABLE) flags |= CURL_CSELECT_IN;
     if (events & UV_WRITABLE) flags |= CURL_CSELECT_OUT;
-
+    
     int running_handles;
-    curl_multi_socket_action(curl_multi_handle, handle->io_watcher.fd, flags, &running_handles);
+    CURLMcode res = curl_multi_socket_action(curl_multi_handle, handle->io_watcher.fd, flags, &running_handles);
+    if (res != CURLM_OK) {
+        fprintf(stderr, "curl_multi_socket_action failed: %s\n", curl_multi_strerror(res));
+    }
+    
     timeout_cb(NULL);
 }
 
 static void timeout_cb(uv_timer_t* handle) {
     int running_handles;
     curl_multi_socket_action(curl_multi_handle, CURL_SOCKET_TIMEOUT, 0, &running_handles);
-
+    
     // 检查完成传输
     CURLMsg* msg;
     int msgs_left;
@@ -193,28 +224,28 @@ static void timeout_cb(uv_timer_t* handle) {
             CURL* easy = msg->easy_handle;
             download_request* req;
             CURLcode res = curl_easy_getinfo(easy, CURLINFO_PRIVATE, &req);
-
-            // 错误处理
+            
+            // 错误检查
             if (res != CURLE_OK) {
                 fprintf(stderr, "curl_easy_getinfo error: %s\n", curl_easy_strerror(res));
             }
-
+            
             if (!req) {
                 fprintf(stderr, "Error: Request object is NULL\n");
                 curl_multi_remove_handle(curl_multi_handle, easy);
                 curl_easy_cleanup(easy);
                 continue;
             }
-
+            
             // 获取 HTTP 状态码
             long http_code = 0;
             curl_easy_getinfo(easy, CURLINFO_RESPONSE_CODE, &http_code);
-
+            
             int result = -1; // 默认失败
-
+            
             // 检查传输错误和 HTTP 状态码
-            if (msg->data.result == CURLE_OK && http_code == 200) {
-                result = 0; // 成功
+            if (msg->data.result == CURLE_OK && http_code >= 200 && http_code < 300) {
+                result = 0; // 成功 (2xx 状态码)
             } else {
                 // 记录错误信息
                 if (msg->data.result != CURLE_OK) {
@@ -223,98 +254,88 @@ static void timeout_cb(uv_timer_t* handle) {
                     fprintf(stderr, "HTTP error: %ld\n", http_code);
                 }
             }
-
-            // 如果失败,删除无效文件
-            if (result != 0 && req->file_ptr) {
-                fclose(req->file_ptr);
-                req->file_ptr = NULL;
-
-                // 删除无效文件
-                if (access(req->output_path, F_OK) == 0) {
-                    unlink(req->output_path);
-                    fprintf(stderr, "Deleted invalid file: %s\n", req->output_path);
-                }
-            }
-            // 成功时正常关闭文件
-            else if (req->file_ptr) {
-                fclose(req->file_ptr);
-                req->file_ptr = NULL;
-            }
-
+            
             // 调用完成回调
             if (req->complete_cb) {
                 req->complete_cb(result, req->userdata);
             }
-
-            // 清理资源
-            curl_multi_remove_handle(curl_multi_handle, easy);
-            curl_easy_cleanup(easy);
-            free(req);
+            
+            // 注意:不要在这里清理 req,由 complete_cb 处理
         }
     }
-
+    
     // 设置下次超时检查
     long timeout_ms;
     curl_multi_timeout(curl_multi_handle, &timeout_ms);
-    if (timeout_ms < 0) timeout_ms = 100;
-
+    if (timeout_ms < 0) timeout_ms = 100; // 默认100ms
+    
     uv_timer_start(&timeout, timeout_cb, timeout_ms, 0);
 }
 
 static int progress_callback(void* clientp, double dltotal, double dlnow, double ultotal, double ulnow) {
     download_request* req = (download_request*)clientp;
-
+    
+    if (!req) return -1;
+    
     // 更新进度
     if (dltotal > 0) {
         double percentage = (dlnow / dltotal) * 100.0;
         if (req->progress_cb) {
             req->progress_cb(percentage, req->userdata);
         }
-
+        
         // 更新内部状态
         req->total_size = (int64_t)dltotal;
         req->downloaded = (int64_t)dlnow;
     }
-
+    
     return 0;
 }
 
 static size_t write_data(void* ptr, size_t size, size_t nmemb, void* userdata) {
     download_request* req = (download_request*)userdata;
+    if (!req || !req->file_ptr) return 0;
+    
     size_t written = fwrite(ptr, size, nmemb, req->file_ptr);
-    return written;
-}
-
-//test
-#include "downloader.h"
-#include <stdio.h>
-
-void progress_cb(double percentage, void* userdata) {
-    printf("下载进度: %.2f%%\n", percentage);
-}
-
-void complete_cb(int status, void* userdata) {
-    if (status == 0) {
-        printf("下载成功!\n");
-    } else {
-        printf("下载失败!\n");
+    if (written < nmemb) {
+        perror("fwrite error");
     }
+static int64_t total = 0;
+total += size*nmemb;
+printf("写入数据块: %zu 字节, 累计: %ld\n", size*nmemb, total );
+    return written;
 }
 
-int download_test( void )
+//--------------------------------------------------------------------------------------------------------
+int http_download( char * url, char *save_path, progress_cb_t progress_cb, complete_cb_t complete_cb )
 {
+    progress_cb_t p_cb;
+    complete_cb_t c_cb;
     // 初始化下载器
     download_init(uv_default_loop());
 
+    p_cb = progress_cb;
+    c_cb = complete_cb;
+
+    if( !p_cb ) p_cb = progress_cb;
+    if( !c_cb ) c_cb = complete_cb;
+
     // 开始下载
     download_file(
-        uv_default_loop(),
-        "http://kyz.pub/download/test_100M.bin",
-        "/tmp/firmware.bin",
-        progress_cb,
-        complete_cb,
-        NULL
-    );
+            uv_default_loop(),
+            url,
+            save_path,
+            p_cb,
+            c_cb,
+            NULL
+            );
 
     return 0;
 }
+
+int download_test( void )
+{
+//    http_download( "http://kyz.pub/download/test.bin", "/tmp/firmware.bin", progress_cb, complete_cb );
+    return 0;
+}
+
index 945ea979e552ce65d2087f6750ecac833b95dab0..0c71e2e8be89a761ebc9df667160a9b6547043e0 100644 (file)
@@ -668,7 +668,7 @@ extern void remote_jbkzq_power( int on );
 extern void remote_alarm( int alarm, char *tts_text );
 extern void dev_unlocked( void );
 extern void dev_locked( uint8_t lock );
-extern void ota_prompt_start( void );
+extern void ota_start( char * url );
 
 char* handle_iot_rx_data( char * data, int sz )
 {
@@ -800,11 +800,9 @@ char* handle_iot_rx_data( char * data, int sz )
             printf( "---------OTA value:%s\n", item_devices_value->valuestring );
             printf( "\n\n---------OTA, url:%s\n", item_devices_tagcode->valuestring );
             //TODO
-            char cmd[256];
-            sprintf( cmd, "echo %s > /userdata/ota_req.txt", item_devices_tagcode->valuestring );
-            system( cmd );
+            ota_start( item_devices_tagcode->valuestring );
+
             resp = wrap_ctrl_resp_json( item_ccode->valuestring, item_devices_device->valuestring, "true", item_devices_tagcode->valuestring, item_devices_value->valuestring, NULL, "write" );
-            ota_prompt_start();
         }else if( strcmp(item_devices_device->valuestring, "xj" )==0 ){
             //xj
             printf( "\n\n---------XJ, ID:%s, start:%s\n", item_devices_tagcode->valuestring, item_devices_value->valuestring );
index a7c765269ad9cbd171f06a840ae9022d255cf5d5..2e5ada9a164983aede53315d7ef4ddcdd515f98d 100644 (file)
@@ -566,7 +566,6 @@ int32_t  lcd_write_alarm( int alarm, int alarm_time )
 
 int32_t lcd_write_ota_info( int st )
 {
-    //spk pwr
     if( st == 1 )
         lcd_write_str( &s_lcd, "main.q1.picc=21\xFF\xFF\xFF" );
     else if( st == 2 )
index a5df6d2fb37d020f4054fddcef65e6f42ef4fa63..a1c673d544b67071be124d4d1da1259389a69c90 100644 (file)
@@ -111,3 +111,341 @@ void ota_prompt_start( void )
     uv_timer_start( &ota_timer, ota_timer_cb, 2000, 0);
 }
 
+
+//---------------------------
+#include <stdint.h>
+
+#define HEADER_SIZE 512
+#define MAGIC_NUMBER 0x4F544121 // "OTA!" in hex
+
+#pragma pack(push, 1)
+typedef struct {
+    uint32_t magic;         // 0x4F544121 ("OTA!")
+    char version[32];       // Version string (null-terminated)
+    uint64_t file_size;     // Size of actual application
+    uint32_t crc32;         // CRC32 of application data
+    uint8_t reserved[464];  // Reserved area
+} FirmwareHeader;
+#pragma pack(pop)
+
+// 验证固件文件
+int validate_firmware(const char *file_path);
+
+// 提取应用程序
+int extract_application(const char *input_path, const char *output_path);
+
+//---------------------------
+#include <zlib.h>
+#include <unistd.h>
+#include <sys/stat.h>
+
+// 验证固件文件
+int validate_firmware(const char *file_path)
+{
+
+char cmd[256];
+sprintf( cmd, "cp %s  /tmp/app.bin", file_path );
+system( cmd );
+
+    FILE *fp = fopen(file_path, "rb");
+    if (!fp) {
+        perror("fopen");
+        return -1;
+    }
+
+    // 读取文件头
+    FirmwareHeader header;
+    size_t read = fread(&header, 1, sizeof(header), fp);
+    if (read != sizeof(header)) {
+        if (ferror(fp)) {
+            perror("Error reading header");
+        } else {
+            fprintf(stderr, "Incomplete header read: %zu/%zu bytes\n", 
+                    read, sizeof(header));
+        }
+        fclose(fp);
+        return -1;
+    }
+    
+    // 验证魔数
+    if (header.magic != MAGIC_NUMBER) {
+        fprintf(stderr, "Invalid magic number: 0x%08X (expected 0x%08X)\n", 
+                header.magic, MAGIC_NUMBER);
+        fclose(fp);
+        return -1;
+    }
+    
+    // 获取文件总大小
+    fseek(fp, 0, SEEK_END);
+    long total_size = ftell(fp);
+    fseek(fp, sizeof(header), SEEK_SET); // 回到数据开始位置
+    
+    // 验证文件大小
+    if (total_size < HEADER_SIZE) {
+        fprintf(stderr, "File too small: %ld bytes (min %d)\n", total_size, HEADER_SIZE);
+        fclose(fp);
+        return -1;
+    }
+    
+    if (total_size != (long)(HEADER_SIZE + header.file_size)) {
+        fprintf(stderr, "Size mismatch: header claims %lu, file has %ld\n",
+                HEADER_SIZE + header.file_size, total_size);
+        fclose(fp);
+        return -1;
+    }
+    
+    // 读取应用程序数据
+    uint8_t *file_data = malloc(header.file_size);
+    if (!file_data) {
+        perror("malloc");
+        fclose(fp);
+        return -1;
+    }
+    
+    read = fread(file_data, 1, header.file_size, fp);
+    if (read != header.file_size) {
+        fprintf(stderr, "Incomplete data read: %zu/%lu bytes\n",
+                read, (unsigned long)header.file_size);
+        free(file_data);
+        fclose(fp);
+        return -1;
+    }
+    fclose(fp);
+    
+    // 计算CRC32
+    uint32_t calculated_crc = crc32(0L, Z_NULL, 0);
+    calculated_crc = crc32(calculated_crc, file_data, header.file_size);
+    
+    // 验证CRC32
+    if (calculated_crc != header.crc32) {
+        fprintf(stderr, "CRC32 mismatch: expected 0x%08X, calculated 0x%08X\n",
+                header.crc32, calculated_crc);
+        free(file_data);
+        return -1;
+    }
+    
+    printf("Firmware validation successful\n");
+    printf("Version: %s\n", header.version);
+    printf("Size: %lu bytes\n", (unsigned long)header.file_size);
+    printf("CRC32: 0x%08X\n", header.crc32);
+    
+    free(file_data);
+    return 0;
+}
+
+// 提取应用程序
+int extract_application(const char *input_path, const char *output_path) {
+    FILE *in_fp = fopen(input_path, "rb");
+    if (!in_fp) {
+        perror("fopen input");
+        return -1;
+    }
+    
+    // 跳过文件头
+    if (fseek(in_fp, HEADER_SIZE, SEEK_SET)) {
+        perror("fseek");
+        fclose(in_fp);
+        return -1;
+    }
+    
+    FILE *out_fp = fopen(output_path, "wb");
+    if (!out_fp) {
+        fclose(in_fp);
+        perror("fopen output");
+        return -1;
+    }
+    
+    // 复制内容
+    uint8_t buffer[4096];
+    size_t bytes_read;
+    while ((bytes_read = fread(buffer, 1, sizeof(buffer), in_fp))) {
+        size_t written = fwrite(buffer, 1, bytes_read, out_fp);
+        if (written != bytes_read) {
+            perror("fwrite");
+            fclose(in_fp);
+            fclose(out_fp);
+            return -1;
+        }
+    }
+    
+    if (ferror(in_fp)) {
+        perror("fread");
+        fclose(in_fp);
+        fclose(out_fp);
+        return -1;
+    }
+    
+    fclose(in_fp);
+    
+    if (fclose(out_fp)) {
+        perror("fclose output");
+        return -1;
+    }
+    
+    // 设置可执行权限
+    if (chmod(output_path, 0755)) {
+        perror("chmod");
+        return -1;
+    }
+    
+    printf("Application extracted to %s\n", output_path);
+    return 0;
+}
+
+
+//--------------------------
+#include "downloader.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <uv.h>
+
+// 全局变量保存程序参数
+char** saved_argv;
+int saved_argc;
+
+// 下载进度回调
+void download_progress_cb(double percentage, void* userdata) {
+    printf("下载进度: %.2f%%\n", percentage);
+}
+
+// 下载完成回调
+void download_complete_cb(int status, void* userdata) {
+    ota_context* ctx = (ota_context*)userdata;
+    
+    if (!ctx) {
+        fprintf(stderr, "错误: 完成回调中缺少上下文\n");
+        return;
+    }
+    
+    printf("下载完成回调: ctx:%p, 状态:%d, 文件:%s\n", 
+           (void*)ctx, status, ctx->temp_path);
+    
+    if (status == 0) {
+        printf("下载成功,开始验证和安装...\n");
+     
+        if( ctx->req->file_ptr )
+            fflush( ctx->req->file_ptr);   
+
+        // 验证固件
+        if (validate_firmware(ctx->temp_path)) {
+            fprintf(stderr, "固件验证失败\n");
+            unlink(ctx->temp_path);
+            free(ctx);
+            return;
+        }
+        
+        printf("固件验证成功,开始安装...\n");
+        
+        sleep(3);
+        lcd_write_ota_info( 2 );
+
+        const char* target_path = "/app/alarmmonitor";
+        const char* backup_path = "/app/alarmmonitor.bak";
+        
+        // 备份当前版本
+        if (rename(target_path, backup_path)) {
+            perror("备份失败");
+            unlink(ctx->temp_path);
+            free(ctx);
+            return;
+        }
+        
+        // 提取应用程序
+        if (extract_application(ctx->temp_path, target_path)) {
+            fprintf(stderr, "提取失败,恢复备份\n");
+            rename(backup_path, target_path);
+            unlink(ctx->temp_path);
+            free(ctx);
+            return;
+        }
+        
+        // 清理
+        unlink(ctx->temp_path);
+        unlink(backup_path);
+        
+        printf("固件升级成功,重启应用程序\n");
+        sleep(3);
+        lcd_write_ota_info( 0 );
+        
+        // 重启应用程序
+        execv(target_path, ctx->saved_argv);
+        perror("execv 失败");
+        exit(EXIT_FAILURE);
+    } else {
+        fprintf(stderr, "下载失败,清理临时文件\n");
+        
+        // 删除无效文件
+        if (access(ctx->temp_path, F_OK) == 0) {
+            if (unlink(ctx->temp_path)) {
+                perror("删除临时文件失败");
+            } else {
+                printf("已删除无效文件: %s\n", ctx->temp_path);
+            }
+        }
+    }
+    
+    // 清理上下文
+    free(ctx);
+
+    sleep(3);
+    lcd_write_ota_info( 0 );
+}
+
+
+int app_update( char *url )
+{
+    // 初始化下载器
+    download_init(uv_default_loop());
+
+    // 创建临时文件路径 (使用PID确保唯一性)
+    char temp_path[256];
+    snprintf(temp_path, sizeof(temp_path), "/tmp/firmware_%d.bin", getpid());
+
+    // 创建OTA上下文
+    ota_context* ctx = calloc(1, sizeof(ota_context));
+    if (!ctx) {
+        fprintf(stderr, "分配OTA上下文失败\n");
+        return EXIT_FAILURE;
+    }
+
+    snprintf(ctx->temp_path, sizeof(ctx->temp_path)-1, "/tmp/firmware_%d.bin", getpid());
+
+    printf("开始下载: %s -> %s\n", url, temp_path);
+
+    // 开始下载
+    lcd_write_ota_info( 1 );
+    download_request* req = download_file(
+            uv_default_loop(),
+            url,
+            temp_path,
+            download_progress_cb,
+            download_complete_cb,
+            ctx
+            );
+    ctx->req = req;
+
+    if (!req) {
+        fprintf(stderr, "启动下载失败\n");
+        free(ctx);
+        return EXIT_FAILURE;
+    }
+
+
+
+    return EXIT_SUCCESS;
+}
+
+int ota_start( char * http_url )
+{
+    if( strstr( http_url, "rfjb_app" )){
+        app_update( http_url);
+        return 0;
+    }
+    char cmd[256];
+    sprintf( cmd, "echo %s > /userdata/ota_req.txt", http_url );
+    system( cmd );
+    ota_prompt_start();
+    return 0;
+}