| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902 |
- #include "ftp_app.h"
- #include <fal.h>
- #include <rtdevice.h>
- #include <string.h>
- #include <stdlib.h>
- #include <board.h>
- /* 日志配置 */
- #define DBG_ENABLE
- #define LOG_TAG "FTP"
- #define DBG_LVL DBG_INFO
- #include <rtdbg.h>
- /* 超时时间(单位:秒) */
- #define SYS_INIT_WAIT 3
- #define MODULE_BOOT_WAIT 3
- #define AT_CMD_TIMEOUT 5
- #define NETWORK_WAIT_MAX 180
- #define FTP_CMD_TIMEOUT 10
- #define DOWNLOAD_TIMEOUT 600
- /* 缓冲区大小 */
- #define AT_LINE_BUF_SIZE 128
- #define FTP_RESPONSE_BUFFER_SIZE 2048 /* 响应缓冲区大小 */
- /* 全局应用实例 */
- static ftp_app_t g_ftp = {0};
- static volatile rt_bool_t g_ftp_inited = RT_FALSE; /* 标记是否已初始化 */
- /* 私有函数声明 */
- static int uart_init(void);
- static void uart_clean(void);
- static int at_send_command(const char *cmd, const char *expect, uint32_t timeout);
- static int read_response_line(char *buf, int size, uint32_t timeout);
- static int read_response_raw(uint8_t *buf, uint32_t size, uint32_t timeout_ms);
- static int module_power_cycle(void);
- static int check_module_ready(void);
- static int check_network(void);
- static int configure_gprs_bearer(void);
- static int configure_ftp(void);
- static int get_file_size(uint32_t *size);
- static int prepare_flash_storage(uint32_t file_size);
- static int start_ftp_session(void);
- static int enhanced_ftp_download(void);
- static void download_thread_entry(void *arg);
- static void safe_delay(uint32_t ms);
- static void update_state(ftp_state_t state);
- static void update_progress(int percent);
- static int parse_ftpget_response(uint8_t *buffer, uint32_t buffer_size, uint32_t *data_length, uint32_t *data_offset);
- static void print_download_status(uint32_t offset, uint32_t total, int block_count);
- typedef struct
- {
- char protocol[16]; // http, https, ftp等
- char host[32]; // 域名或IP
- int port; // 端口号
- char path[64]; // 完整路径
- char dir[32]; // 目录路径
- char filename[24]; // 文件名
- char username[32]; // FTP用户名(可选)
- char password[32]; // FTP密码(可选)
- } url_info_t;
- // 简易的字符串转小写函数
- static void str_tolower(char *str)
- {
- while (*str)
- {
- *str = tolower((unsigned char)*str);
- str++;
- }
- }
- int parse_url(const char *url, url_info_t *info)
- {
- if (!url || !info)
- return -1;
- memset(info, 0, sizeof(url_info_t));
- // 查找协议分隔符
- const char *protocol_end = strstr(url, "://");
- if (protocol_end)
- {
- size_t proto_len = protocol_end - url;
- if (proto_len >= sizeof(info->protocol))
- return -1;
- strncpy(info->protocol, url, proto_len);
- info->protocol[proto_len] = '\0';
- str_tolower(info->protocol); // 统一转换为小写
- url = protocol_end + 3; // 跳过"://"
- }
- else
- {
- // 没有明确指定协议,默认为http
- strcpy(info->protocol, "http");
- }
- // 设置协议对应的默认端口
- if (strcmp(info->protocol, "ftp") == 0 ||
- strcmp(info->protocol, "ftps") == 0)
- {
- info->port = 21; // FTP默认端口
- }
- else if (strcmp(info->protocol, "http") == 0)
- {
- info->port = 80; // HTTP默认端口
- }
- else if (strcmp(info->protocol, "https") == 0)
- {
- info->port = 443; // HTTPS默认端口
- }
- else
- {
- info->port = 80; // 其他协议默认使用80
- }
- // 复制一份URL用于处理认证信息
- char url_buffer[256] = {0};
- strncpy(url_buffer, url, sizeof(url_buffer) - 1);
- char *current_pos = url_buffer;
- // 处理认证信息(user:pass@host)
- char *at_pos = strchr(current_pos, '@');
- if (at_pos)
- {
- // 包含认证信息
- *at_pos = '\0'; // 分割认证信息和主机部分
- // 分离用户名和密码
- char *colon_pos = strchr(current_pos, ':');
- if (colon_pos)
- {
- // 有密码:user:pass
- size_t user_len = colon_pos - current_pos;
- if (user_len > 0 && user_len < sizeof(info->username))
- {
- strncpy(info->username, current_pos, user_len);
- info->username[user_len] = '\0';
- }
- size_t pass_len = at_pos - (colon_pos + 1);
- if (pass_len > 0 && pass_len < sizeof(info->password))
- {
- strncpy(info->password, colon_pos + 1, pass_len);
- info->password[pass_len] = '\0';
- }
- }
- else
- {
- // 只有用户名:user@
- size_t user_len = at_pos - current_pos;
- if (user_len > 0 && user_len < sizeof(info->username))
- {
- strncpy(info->username, current_pos, user_len);
- info->username[user_len] = '\0';
- }
- }
- // 主机部分从@之后开始
- current_pos = at_pos + 1;
- }
- // 查找路径起始位置
- char *path_start = strchr(current_pos, '/');
- // 解析主机和端口
- if (path_start)
- {
- // 有路径部分
- *path_start = '\0'; // 分割主机和路径
- size_t host_len = strlen(current_pos);
- // 检查是否有端口号
- char *port_start = strchr(current_pos, ':');
- if (port_start)
- {
- // 有端口号
- *port_start = '\0'; // 分割主机和端口
- if (strlen(current_pos) < sizeof(info->host))
- {
- strcpy(info->host, current_pos);
- }
- info->port = atoi(port_start + 1);
- }
- else
- {
- // 没有端口号,使用协议默认端口
- if (host_len < sizeof(info->host))
- {
- strcpy(info->host, current_pos);
- }
- }
- // 恢复路径部分
- *path_start = '/';
- // 复制完整路径
- size_t path_len = strlen(path_start);
- if (path_len > 0 && path_len < sizeof(info->path))
- {
- strcpy(info->path, path_start);
- }
- else
- {
- strcpy(info->path, "/");
- }
- }
- else
- {
- // 没有路径部分,只有主机名
- size_t host_len = strlen(current_pos);
- // 检查是否有端口号
- char *port_start = strchr(current_pos, ':');
- if (port_start)
- {
- // 有端口号
- *port_start = '\0'; // 分割主机和端口
- if (strlen(current_pos) < sizeof(info->host))
- {
- strcpy(info->host, current_pos);
- }
- info->port = atoi(port_start + 1);
- }
- else
- {
- // 没有端口号
- if (host_len < sizeof(info->host))
- {
- strcpy(info->host, current_pos);
- }
- }
- strcpy(info->path, "/");
- }
- // 分离目录和文件名
- if (strlen(info->path) > 0)
- {
- // 查找最后一个斜杠
- char *last_slash = strrchr(info->path, '/');
- if (last_slash)
- {
- // 复制文件名(最后一个斜杠之后的内容)
- if (strlen(last_slash + 1) > 0)
- {
- strncpy(info->filename, last_slash + 1, sizeof(info->filename) - 1);
- }
- // 提取目录(包括最后一个斜杠)
- size_t dir_len = last_slash - info->path + 1; // +1 包含斜杠
- if (dir_len > 0)
- {
- if (dir_len < sizeof(info->dir))
- {
- strncpy(info->dir, info->path, dir_len);
- info->dir[dir_len] = '\0';
- }
- }
- else
- {
- // 根目录
- strcpy(info->dir, "/");
- }
- }
- else
- {
- // 没有斜杠,整个路径作为文件名
- strncpy(info->filename, info->path, sizeof(info->filename) - 1);
- strcpy(info->dir, "/");
- }
- }
- else
- {
- strcpy(info->path, "/");
- strcpy(info->dir, "/");
- }
- return 0;
- }
- // 用于RT-Thread控制台的纯英文测试函数
- void url_parse_test(void)
- {
- printf("=== HTTP URL Test ===\n");
- const char *http_url = "http://www.yfzhwlw.com/update/qxz_bin/qxzH_300.rbl";
- url_info_t info;
- if (parse_url(http_url, &info) == 0)
- {
- printf("Protocol: %s(%d)\n", info.protocol, strlen(info.protocol));
- printf("Host: %s(%d)\n", info.host, strlen(info.host));
- printf("Port: %d(%d)\n", info.port, strlen(info.port));
- printf("User: %s(%d)\n", info.username, strlen(info.username));
- printf("Pass: %s(%d)\n", info.password, strlen(info.password));
- printf("Path: %s(%d)\n", info.path, strlen(info.path));
- printf("Dir: %s(%d)\n", info.dir, strlen(info.dir));
- printf("File: %s(%d)\n", info.filename, strlen(info.filename));
- }
- printf("\n=== FTP URL Test (with auth) ===\n");
- const char *ftp_url = "ftp://updateuser:123456@www.rrwrwwrw.com:21/qxz_bin/qxz_FTP.rbl";
- if (parse_url(ftp_url, &info) == 0)
- {
- printf("Protocol: %s\n", info.protocol);
- printf("Host: %s\n", info.host);
- printf("Port: %d\n", info.port);
- printf("User: %s\n", info.username);
- printf("Pass: %s\n", info.password);
- printf("Path: %s\n", info.path);
- printf("Dir: %s\n", info.dir);
- printf("File: %s\n", info.filename);
- // 验证:FTP目录应该以/结尾
- if (info.dir[strlen(info.dir) - 1] != '/')
- {
- printf("[Note] FTP dir should end with '/'\n");
- }
- }
- printf("\n=== FTP URL Test (anonymous) ===\n");
- const char *ftp_anon_url = "ftp://ftp.example.com/pub/files/data.bin";
- if (parse_url(ftp_anon_url, &info) == 0)
- {
- printf("Protocol: %s\n", info.protocol);
- printf("Host: %s\n", info.host);
- printf("Port: %d\n", info.port);
- printf("User: %s\n", info.username);
- printf("Pass: %s\n", info.password);
- printf("Path: %s\n", info.path);
- printf("Dir: %s\n", info.dir);
- printf("File: %s\n", info.filename);
- }
- printf("\n=== FTP URL Test (user only) ===\n");
- const char *ftp_user_url = "ftp://user@example.com:2121/path/to/file.txt";
- if (parse_url(ftp_user_url, &info) == 0)
- {
- printf("Protocol: %s\n", info.protocol);
- printf("Host: %s\n", info.host);
- printf("Port: %d\n", info.port);
- printf("User: %s\n", info.username);
- printf("Pass: %s\n", info.password);
- printf("Path: %s\n", info.path);
- printf("Dir: %s\n", info.dir);
- printf("File: %s\n", info.filename);
- }
- printf("\n=== Edge Cases Test ===\n");
- }
- // MSH_CMD_EXPORT(url_parse_test, URL parse test for HTTP and FTP);
- // 全局上下文,初始值为 0xFFFFFFFF(INIT)
- static firmware_crc_ctx_t g_fw_crc_ctx = {.crc = 0xFFFFFFFF};
- void firmware_crc_update(firmware_crc_ctx_t *ctx, const uint8_t *data, size_t len)
- {
- // ? 标准 CRC-32/IEEE 的 bit-reflected 多项式
- const uint32_t POLY = 0xEDB88320U;
- uint32_t crc = ctx->crc;
- for (size_t i = 0; i < len; i++)
- {
- crc ^= data[i]; // 输入字节直接异或(REFIN=true 由右移实现)
- for (int j = 0; j < 8; j++)
- {
- if (crc & 1)
- {
- crc = (crc >> 1) ^ POLY;
- }
- else
- {
- crc >>= 1;
- }
- }
- }
- ctx->crc = crc;
- static int cnt = 1;
- // ? XOROUT = 0xFFFFFFFF
- uint32_t final_crc = crc ^ 0xFFFFFFFF;
- // rt_kprintf("firmware_crc_update %d(byte) >> %d > %08X\n", len, cnt, final_crc);
- cnt++;
- }
- /* ====================== 辅助函数 ====================== */
- static void safe_delay(uint32_t ms)
- {
- rt_tick_t start = rt_tick_get();
- rt_tick_t timeout = rt_tick_from_millisecond(ms);
- while ((rt_tick_get() - start) < timeout)
- {
- rt_thread_mdelay(10);
- }
- }
- static void update_state(ftp_state_t state)
- {
- if (!g_ftp_inited)
- return;
- g_ftp.state = state;
- LOG_I("State changed to: %d", state);
- }
- static void update_progress(int percent)
- {
- if (!g_ftp_inited)
- return;
- if (percent < 0)
- percent = 0;
- if (percent > 100)
- percent = 100;
- /* 只有当进度变化时才更新 */
- if (percent != g_ftp.progress)
- {
- g_ftp.progress = percent;
- /* 每5%或者特殊值(0,100)记录日志 */
- if (percent % 5 == 0 || percent == 0 || percent == 100)
- {
- LOG_I("Progress: %d%%", percent);
- }
- }
- }
- /* 实时打印下载状态 */
- static void print_download_status(uint32_t offset, uint32_t total, int block_count)
- {
- int percent = (total > 0) ? (offset * 100) / total : 0;
- /* 每10个块或者每5%进度打印一次详细状态 */
- if (block_count % 10 == 0 || percent % 5 == 0)
- {
- LOG_I("Download: %lu/%lu bytes (%d%%) - Block: %d",
- offset, total, percent, block_count);
- }
- else if (block_count % 5 == 0)
- {
- /* 更频繁但简单的状态更新 */
- // LOG_D("DL: %lu/%lu (%d%%)", offset, total, percent);
- }
- }
- /* ====================== UART通信 ====================== */
- static int uart_init(void)
- {
- struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;
- LOG_I("Initializing UART: %s %dbps", AIR720_UART_NAME, AIR720_UART_BAUD);
- g_ftp.uart_dev = rt_device_find(AIR720_UART_NAME);
- if (!g_ftp.uart_dev)
- {
- LOG_E("UART device not found: %s", AIR720_UART_NAME);
- return -1;
- }
- config.baud_rate = AIR720_UART_BAUD;
- config.data_bits = DATA_BITS_8;
- config.stop_bits = STOP_BITS_1;
- config.parity = PARITY_NONE;
- config.bufsz = 2048; /* 增加缓冲区大小以容纳二进制数据 */
- if (rt_device_control(g_ftp.uart_dev, RT_DEVICE_CTRL_CONFIG, &config) != RT_EOK)
- {
- LOG_E("UART config failed");
- return -1;
- }
- if (rt_device_open(g_ftp.uart_dev, RT_DEVICE_FLAG_INT_RX) != RT_EOK)
- {
- LOG_E("Open UART failed");
- g_ftp.uart_dev = RT_NULL;
- return -1;
- }
- LOG_I("UART initialized");
- return 0;
- }
- static void uart_clean(void)
- {
- char temp_buf[64];
- rt_size_t read_len;
- if (!g_ftp.uart_dev)
- return;
- do
- {
- read_len = rt_device_read(g_ftp.uart_dev, 0, temp_buf, sizeof(temp_buf));
- if (read_len > 0)
- {
- LOG_D("Cleaned %d bytes", read_len);
- rt_thread_mdelay(5);
- }
- } while (read_len > 0);
- }
- static int read_response_line(char *buf, int size, uint32_t timeout_ms)
- {
- int pos = 0;
- char ch;
- rt_size_t read_len;
- rt_tick_t start = rt_tick_get();
- if (!buf || size <= 1)
- return -1;
- buf[0] = '\0';
- while ((rt_tick_get() - start) < rt_tick_from_millisecond(timeout_ms))
- {
- read_len = rt_device_read(g_ftp.uart_dev, 0, &ch, 1);
- if (read_len == 1)
- {
- if (ch == '\n')
- {
- if (pos > 0 && buf[pos - 1] == '\r')
- {
- buf[pos - 1] = '\0';
- }
- else if (pos < size - 1)
- {
- buf[pos] = '\0';
- }
- else
- {
- buf[size - 1] = '\0';
- }
- return 0;
- }
- if (ch == '\r')
- continue;
- if (pos < size - 1)
- {
- buf[pos++] = ch;
- }
- else
- {
- /* 缓冲区已满,直接返回 */
- buf[size - 1] = '\0';
- return 0;
- }
- }
- else
- {
- rt_thread_mdelay(1);
- }
- }
- if (pos > 0)
- {
- if (pos < size)
- buf[pos] = '\0';
- else
- buf[size - 1] = '\0';
- }
- return -1;
- }
- /* 读取原始响应数据 */
- static int read_response_raw(uint8_t *buf, uint32_t size, uint32_t timeout_ms)
- {
- rt_tick_t start = rt_tick_get();
- uint32_t total_read = 0;
- if (!buf || size == 0)
- return -1;
- while ((rt_tick_get() - start) < rt_tick_from_millisecond(timeout_ms))
- {
- rt_size_t read_len = rt_device_read(g_ftp.uart_dev, 0, buf + total_read, size - total_read);
- if (read_len > 0)
- {
- total_read += read_len;
- }
- rt_thread_mdelay(1);
- }
- return total_read; /* 返回实际读取的字节数 */
- }
- static int parse_ftpget_response(uint8_t *buffer, uint32_t buffer_size, uint32_t *data_length, uint32_t *data_offset)
- {
- if (!buffer || !data_length || !data_offset)
- return -1;
- *data_length = 0;
- *data_offset = 0;
- // 查找 "+FTPGET: 2," 或 "+FTPGET:2,"
- for (uint32_t i = 0; i < buffer_size - 12; i++)
- {
- // 匹配 "+FTPGET:2," (无空格)
- if (memcmp(&buffer[i], "+FTPGET:2,", 10) == 0)
- {
- uint32_t num_start = i + 10;
- uint32_t j = num_start;
- while (j < buffer_size && buffer[j] >= '0' && buffer[j] <= '9')
- j++;
- if (j > num_start)
- {
- // 解析长度
- *data_length = 0;
- for (uint32_t k = num_start; k < j; k++)
- {
- *data_length = *data_length * 10 + (buffer[k] - '0');
- }
- if (*data_length == 0)
- return -1;
- // 找到这一行的结束:下一个 \n
- uint32_t line_end = j;
- while (line_end < buffer_size && buffer[line_end] != '\n')
- line_end++;
- if (line_end < buffer_size)
- line_end++; // 跳过 \n
- // 跳过可能的 \r\n 中的 \r
- if (line_end > 0 && buffer[line_end - 1] == '\n')
- {
- if (line_end >= 2 && buffer[line_end - 2] == '\r')
- {
- // 已经包含 \r\n,line_end 指向 \n 后一位
- }
- }
- *data_offset = line_end;
- // LOG_D("Parsed FTPGET: len=%lu, data starts at offset=%lu", *data_length, *data_offset);
- return 0;
- }
- }
- // 匹配 "+FTPGET: 2," (有空格)
- else if (memcmp(&buffer[i], "+FTPGET: 2,", 11) == 0)
- {
- uint32_t num_start = i + 11;
- uint32_t j = num_start;
- while (j < buffer_size && buffer[j] >= '0' && buffer[j] <= '9')
- j++;
- if (j > num_start)
- {
- *data_length = 0;
- for (uint32_t k = num_start; k < j; k++)
- {
- *data_length = *data_length * 10 + (buffer[k] - '0');
- }
- if (*data_length == 0)
- return -1;
- uint32_t line_end = j;
- while (line_end < buffer_size && buffer[line_end] != '\n')
- line_end++;
- if (line_end < buffer_size)
- line_end++;
- *data_offset = line_end;
- // LOG_D("Parsed FTPGET (with space): len=%lu, data starts at offset=%lu", *data_length, *data_offset);
- return 0;
- }
- }
- }
- LOG_W("No valid +FTPGET: 2,... response found in buffer");
- return -1;
- }
- static int at_send_command(const char *cmd, const char *expect, uint32_t timeout_sec)
- {
- char line_buf[AT_LINE_BUF_SIZE];
- rt_size_t write_len;
- if (!g_ftp_inited || !g_ftp.uart_dev || !cmd)
- {
- return -1;
- }
- uart_clean();
- char full_cmd[128];
- int cmd_len = rt_snprintf(full_cmd, sizeof(full_cmd), "%s\r\n", cmd);
- if (cmd_len < 0 || cmd_len >= sizeof(full_cmd))
- {
- LOG_E("AT command too long: %s", cmd);
- return -1;
- }
- write_len = rt_device_write(g_ftp.uart_dev, 0, full_cmd, cmd_len);
- if (write_len != cmd_len)
- {
- LOG_E("AT write failed: %s", cmd);
- return -1;
- }
- LOG_D("TX: %s", cmd);
- rt_tick_t start = rt_tick_get();
- rt_tick_t timeout = rt_tick_from_millisecond(timeout_sec * 1000);
- while ((rt_tick_get() - start) < timeout)
- {
- if (read_response_line(line_buf, sizeof(line_buf), 100) == 0)
- {
- if (strlen(line_buf) == 0)
- continue;
- if (strstr(line_buf, "ERROR") || strstr(line_buf, "CME ERROR"))
- {
- LOG_E("AT error: %s", line_buf);
- return -1;
- }
- if (expect && strstr(line_buf, expect))
- {
- LOG_D("Found expected: %s", expect);
- return 0;
- }
- if (strstr(line_buf, "OK"))
- {
- return 0;
- }
- }
- }
- LOG_E("AT timeout: %s", cmd);
- return -1;
- }
- /* ====================== 模块控制 ====================== */
- static int power_init(void)
- {
- rt_pin_mode(AIR720_POWER_PIN, PIN_MODE_OUTPUT);
- AIR720_POWER_OFF();
- safe_delay(100);
- LOG_I("Power control ready");
- return 0;
- }
- static int module_power_cycle(void)
- {
- if (!g_ftp_inited)
- return -1;
- LOG_I("Module power cycle start");
- update_state(FTP_STATE_MODULE_BOOT);
- AIR720_POWER_OFF();
- LOG_I("Power OFF");
- safe_delay(2000);
- AIR720_POWER_ON();
- LOG_I("Power ON");
- for (int i = MODULE_BOOT_WAIT; i > 0; i--)
- {
- LOG_D("Boot wait: %d", i);
- safe_delay(1000);
- }
- LOG_I("Module boot completed");
- return 0;
- }
- static int check_module_ready(void)
- {
- if (!g_ftp_inited)
- return -1;
- int retry;
- LOG_I("Checking module readiness");
- for (retry = 0; retry < 10; retry++)
- {
- if (at_send_command("AT", "OK", AT_CMD_TIMEOUT) == 0)
- {
- LOG_I("Module ready");
- return 0;
- }
- LOG_W("Module not ready, retry %d", retry + 1);
- safe_delay(500);
- }
- LOG_E("Module check failed");
- Recode_e_code(e_fwdownload_fail, STEP_MODULE_CHECK, "AT command no response");
- return -1;
- }
- static int check_network(void)
- {
- if (!g_ftp_inited)
- return -1;
- int retry_count = 0;
- LOG_I("Checking network registration");
- update_state(FTP_STATE_NETWORK_WAIT);
- if (at_send_command("AT+CPIN?", "READY", AT_CMD_TIMEOUT) != 0)
- {
- LOG_E("SIM card not ready");
- Recode_e_code(e_fwdownload_fail, STEP_SIM_CHECK, "SIM not ready");
- return -1;
- }
- LOG_I("SIM card ready");
- while (retry_count < (NETWORK_WAIT_MAX / 5))
- {
- if (at_send_command("AT+CREG?", "+CREG: 0,1", AT_CMD_TIMEOUT) == 0)
- {
- LOG_I("Network registered");
- if (at_send_command("AT+CSQ", "+CSQ:", AT_CMD_TIMEOUT) == 0)
- {
- LOG_I("Signal OK");
- return 0;
- }
- }
- retry_count++;
- LOG_D("Network wait: %d/%d", retry_count * 5, NETWORK_WAIT_MAX);
- safe_delay(5000);
- }
- LOG_E("Network registration timeout");
- Recode_e_code(e_fwdownload_fail, STEP_NETWORK_REG, "Network timeout");
- return -1;
- }
- /* ====================== FTP配置 ====================== */
- static int configure_gprs_bearer(void)
- {
- return 0;
- }
- #include "sys_config.h"
- extern Sector qxz;
- static int configure_ftp(void)
- {
- if (!g_ftp_inited)
- return -1;
- char cmd_buf[128];
- LOG_I("Configuring FTP connection");
- update_state(FTP_STATE_FTP_SETUP);
- url_info_t info = {0};
- if (parse_url(qxz.Param.upgrade_url, &info) == 0)
- {
- printf("Protocol: %s(%d)\n", info.protocol, strlen(info.protocol));
- printf("Host: %s(%d)\n", info.host, strlen(info.host));
- printf("Port: %d(%d)\n", info.port, strlen(info.port));
- printf("User: %s(%d)\n", info.username, strlen(info.username));
- printf("Pass: %s(%d)\n", info.password, strlen(info.password));
- printf("Path: %s(%d)\n", info.path, strlen(info.path));
- printf("Dir: %s(%d)\n", info.dir, strlen(info.dir));
- printf("File: %s(%d)\n", info.filename, strlen(info.filename));
- }
- if (configure_gprs_bearer() != 0)
- {
- LOG_E("GPRS bearer configuration failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "configure_gprs_bearer");
- return -1;
- }
- safe_delay(100);
- if (at_send_command("AT+FTPTYPE=I", "OK", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set FTPTYPE=I failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "FTPTYPE=I");
- return -1;
- }
- safe_delay(100);
- if (at_send_command("AT+CGATT?", "+CGATT: 1", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set AT+CGATT? failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "AT+CGATT?");
- return -1;
- }
- safe_delay(100);
- if (at_send_command("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"", "OK", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set AT+SAPBR=3,1, failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "AT+SAPBR=3,1,");
- return -1;
- }
- safe_delay(100);
- if (at_send_command("AT+SAPBR=3,1,\"APN\",\"\"", "OK", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set AT+SAPBR=3,1,\"APN\" failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "AT+SAPBR=3,1,\"APN\"");
- return -1;
- }
- safe_delay(100);
- if (at_send_command("AT+SAPBR=1,1", "OK", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set AT+SAPBR=1,1 failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "AT+SAPBR=1,1");
- return -1;
- }
- safe_delay(100);
- if (at_send_command("AT+SAPBR=2,1", "OK", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set AT+SAPBR=2,1 failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "AT+SAPBR=2,1");
- return -1;
- }
- safe_delay(100);
- if (at_send_command("AT+FTPCID=1", "OK", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set FTPCID=1 failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTPCID失败");
- return -1;
- }
- safe_delay(100);
- int len = 0;
- if (strlen(info.host) == 0 || (strstr(qxz.Param.upgrade_url, "ftp") == NULL))
- {
- len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPSERV=\"%s\"", FTP_SERVER_ADDR);
- }
- else
- {
- len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPSERV=\"%s\"", info.host);
- }
- if (len < 0 || len >= sizeof(cmd_buf))
- {
- LOG_E("Server address too long");
- return -1;
- }
- if (at_send_command(cmd_buf, "OK", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set FTP server failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP服务器失败");
- return -1;
- }
- safe_delay(100);
- if (strlen(info.username) == 0 || (strstr(qxz.Param.upgrade_url, "ftp") == NULL))
- {
- len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPUN=\"%s\"", FTP_USERNAME);
- }
- else
- {
- len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPUN=\"%s\"", info.username);
- }
- if (len < 0 || len >= sizeof(cmd_buf))
- {
- LOG_E("Username too long");
- return -1;
- }
- if (at_send_command(cmd_buf, "OK", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set FTP username failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP用户名失败");
- return -1;
- }
- safe_delay(100);
- if (strlen(info.password) == 0 || (strstr(qxz.Param.upgrade_url, "ftp") == NULL))
- {
- len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPPW=\"%s\"", FTP_PASSWORD);
- }
- else
- {
- len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPPW=\"%s\"", info.password);
- }
- if (len < 0 || len >= sizeof(cmd_buf))
- {
- LOG_E("Password too long");
- return -1;
- }
- if (at_send_command(cmd_buf, "OK", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set FTP password failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP密码失败");
- return -1;
- }
- safe_delay(100);
- if (at_send_command("AT+FTPPORT=21", "OK", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set FTP port failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP端口失败");
- return -1;
- }
- safe_delay(100);
- if (at_send_command("AT+FTPMODE=1", "OK", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set FTP passive mode failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP被动模式失败");
- return -1;
- }
- safe_delay(100);
- if (strlen(info.dir) == 0 || (strstr(qxz.Param.upgrade_url, "ftp") == NULL))
- {
- len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPGETPATH=\"%s\"", FTP_FILE_PATH);
- }
- else
- {
- len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPGETPATH=\"%s\"", info.dir);
- }
- if (len < 0 || len >= sizeof(cmd_buf))
- {
- LOG_E("File path too long");
- return -1;
- }
- if (at_send_command(cmd_buf, "OK", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set FTP path failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP路径失败");
- return -1;
- }
- safe_delay(100);
- if (info.filename[0] == 'q' && info.filename[1] == 'x' && info.filename[2] == 'z' && (strstr(info.filename, ".rbl") != NULL))
- {
- LOG_I("Getting remote file name == %s \n", info.filename);
- len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPGETNAME=\"%s\"", info.filename);
- }
- else
- {
- len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPGETNAME=\"%s\"", FTP_FILE_NAME);
- }
- if (len < 0 || len >= sizeof(cmd_buf))
- {
- LOG_E("File name too long");
- return -1;
- }
- if (at_send_command(cmd_buf, "OK", FTP_CMD_TIMEOUT) != 0)
- {
- LOG_E("Set FTP filename failed");
- Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP文件名失败");
- return -1;
- }
- safe_delay(100);
- LOG_I("FTP configuration completed successfully");
- return 0;
- }
- static int get_file_size(uint32_t *size)
- {
- if (!g_ftp_inited || !size)
- return -1;
- char line_buf[AT_LINE_BUF_SIZE];
- char *ptr;
- LOG_I("Getting remote file size");
- if (at_send_command("AT+FTPSIZE", "+FTPSIZE:", FTP_CMD_TIMEOUT) != 0)
- {
- Recode_e_code(e_fwdownload_fail, STEP_FILE_SIZE_GET, "获取文件大小命令失败");
- return -1;
- }
- rt_tick_t start = rt_tick_get();
- while ((rt_tick_get() - start) < rt_tick_from_millisecond(3000))
- {
- if (read_response_line(line_buf, sizeof(line_buf), 100) == 0)
- {
- if (strlen(line_buf) == 0)
- continue;
- LOG_D("Size response: %s", line_buf);
- ptr = strstr(line_buf, "+FTPSIZE:");
- if (ptr)
- {
- char *num_start = ptr + 9;
- int num1, num2, num3;
- if (sscanf(num_start, "%d,%d,%d", &num1, &num2, &num3) == 3)
- {
- *size = num3;
- LOG_I("File size: %lu bytes", *size);
- return 0;
- }
- else if (sscanf(num_start, "%d,%d", &num1, &num2) == 2)
- {
- *size = num2;
- LOG_I("File size: %lu bytes", *size);
- return 0;
- }
- else if (sscanf(num_start, "%d", &num1) == 1)
- {
- *size = num1;
- LOG_I("File size: %lu bytes", *size);
- return 0;
- }
- }
- }
- }
- LOG_E("No valid size response");
- Recode_e_code(e_fwdownload_fail, STEP_FILE_SIZE_GET, "无有效文件大小响应");
- return -1;
- }
- static int prepare_flash_storage(uint32_t file_size)
- {
- if (!g_ftp_inited)
- return -1;
- LOG_I("Preparing flash storage %d ", file_size);
- g_ftp.flash_part = fal_partition_find(FW_PARTITION_NAME);
- if (!g_ftp.flash_part)
- {
- LOG_E("Flash partition not found: %s", FW_PARTITION_NAME);
- Recode_e_code(e_fwdownload_fail, STEP_FLASH_PREPARE, "分区未找到");
- return -1;
- }
- if (g_ftp.flash_part->len < file_size)
- {
- LOG_E("Partition too small: %lu < %lu", g_ftp.flash_part->len, file_size);
- Recode_e_code(e_fwdownload_fail, STEP_FLASH_PREPARE, "分区太小");
- return -1;
- }
- if (fal_partition_erase(g_ftp.flash_part, 0, file_size) < 0)
- {
- LOG_E("Erase failed");
- Recode_e_code(e_fwdownload_fail, STEP_FLASH_PREPARE, "擦除失败");
- return -1;
- }
- LOG_I("Flash prepared");
- return 0;
- }
- /* ====================== 下载实现 ====================== */
- static int start_ftp_session(void)
- {
- if (!g_ftp_inited)
- return -1;
- char line_buf[AT_LINE_BUF_SIZE];
- int retry;
- LOG_I("Starting FTP session");
- uart_clean();
- if (at_send_command("AT+FTPGET=1", "OK", 30) != 0)
- {
- LOG_E("AT+FTPGET=1 command failed");
- return -1;
- }
- for (retry = 0; retry < 30; retry++)
- {
- if (read_response_line(line_buf, sizeof(line_buf), 1000) == 0)
- {
- LOG_D("Response: %s", line_buf);
- if (strstr(line_buf, "+FTPGET:1,1") || strstr(line_buf, "FTPGET: 1,1"))
- {
- LOG_I("FTP session established");
- return 0;
- }
- if (strstr(line_buf, "+FTPGET:1,") || strstr(line_buf, "+FTPGET: 1,"))
- {
- int error_code = 0;
- char *ptr;
- if ((ptr = strstr(line_buf, "+FTPGET:1,")) != NULL)
- {
- error_code = atoi(ptr + 10);
- }
- else if ((ptr = strstr(line_buf, "+FTPGET: 1,")) != NULL)
- {
- error_code = atoi(ptr + 11);
- }
- if (error_code > 0)
- {
- LOG_E("FTP session failed: %d", error_code);
- return -1;
- }
- }
- if (strstr(line_buf, "ERROR") || strstr(line_buf, "CME ERROR"))
- {
- LOG_E("General error: %s", line_buf);
- return -1;
- }
- }
- if (retry % 5 == 0)
- {
- LOG_D("Waiting... (%d/30)", retry);
- }
- }
- LOG_E("Timeout waiting for FTP response");
- return -1;
- }
- /* 智能读取指定长度的数据体,避免固定超时 */
- static int read_ftp_data_block(uint8_t *buf, uint32_t expected_len, uint32_t total_timeout_ms)
- {
- rt_tick_t start = rt_tick_get();
- uint32_t total_read = 0;
- uint32_t last_recv_time = rt_tick_get();
- while (total_read < expected_len)
- {
- if ((rt_tick_get() - start) >= rt_tick_from_millisecond(total_timeout_ms))
- {
- LOG_E("Read block timeout");
- return -1;
- }
- rt_size_t read_len = rt_device_read(g_ftp.uart_dev, 0, buf + total_read, expected_len - total_read);
- if (read_len > 0)
- {
- total_read += read_len;
- last_recv_time = rt_tick_get(); // 更新最后接收时间
- }
- else
- {
- // 若 2 秒无新数据,认为传输结束(防卡死)
- if ((rt_tick_get() - last_recv_time) > rt_tick_from_millisecond(2000))
- {
- break;
- }
- rt_thread_mdelay(2);
- }
- }
- return (int)total_read;
- }
- static int enhanced_ftp_download(void)
- {
- if (!g_ftp_inited)
- return -1;
- uint32_t offset = 0;
- uint32_t request_len = 0;
- uint32_t actual_len = 0;
- int percent = 0;
- int block_count = 0;
- LOG_I("Starting enhanced FTP download");
- update_state(FTP_STATE_DOWNLOADING);
- /* 使用静态缓冲区,避免频繁分配 */
- static uint8_t static_download_buffer[FTP_BLOCK_SIZE];
- static uint8_t static_response_buffer[FTP_RESPONSE_BUFFER_SIZE];
- g_ftp.download_buffer = static_download_buffer;
- if (start_ftp_session() != 0)
- {
- LOG_E("Failed to start FTP session");
- return -1;
- }
- LOG_I("Starting data transfer...");
- LOG_I("File size: %lu bytes, will download in %lu blocks",
- g_ftp.file_size, (g_ftp.file_size + FTP_BLOCK_SIZE - 1) / FTP_BLOCK_SIZE);
- while (offset < g_ftp.file_size && g_ftp.is_running)
- {
- block_count++;
- request_len = (g_ftp.file_size - offset) < FTP_BLOCK_SIZE ? (g_ftp.file_size - offset) : FTP_BLOCK_SIZE;
- /* 不再清空 UART!避免丢弃已到达的数据 */
- // uart_clean(); ← 已移除
- /* 发送获取命令 */
- char cmd_buf[32];
- rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPGET=2,%lu", request_len);
- // LOG_D("TX: %s", cmd_buf);
- rt_device_write(g_ftp.uart_dev, 0, cmd_buf, strlen(cmd_buf));
- rt_device_write(g_ftp.uart_dev, 0, "\r\n", 2);
- /* 动态等待数据:目标是收到完整的 "+FTPGET:2,<len>\r\n<data>" */
- uint32_t total_received = 0;
- uint32_t start_tick = rt_tick_get();
- uint32_t timeout_ticks = rt_tick_from_millisecond(3000); // 3秒超时
- /* 先确保收到至少能解析 header 的字节数 */
- while (total_received < 64)
- {
- if ((rt_tick_get() - start_tick) >= timeout_ticks)
- {
- LOG_E("Timeout waiting for FTP response header");
- Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "等待响应头超时");
- return -1;
- }
- rt_size_t read_len = rt_device_read(g_ftp.uart_dev, 0,
- static_response_buffer + total_received,
- sizeof(static_response_buffer) - total_received);
- if (read_len > 0)
- {
- total_received += read_len;
- }
- else
- {
- rt_thread_mdelay(5); // 避免忙等
- }
- }
- /* 尝试解析响应头 */
- uint32_t data_offset = 0;
- if (parse_ftpget_response(static_response_buffer, total_received, &actual_len, &data_offset) != 0)
- {
- LOG_E("Failed to parse FTPGET response after receiving %lu bytes", total_received);
- Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "解析FTP响应失败");
- return -1;
- }
- if (actual_len == 0 || actual_len > FTP_BLOCK_SIZE)
- {
- LOG_E("Invalid data length: %lu", actual_len);
- Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "无效数据长度");
- return -1;
- }
- /* 如果数据尚未收全,继续读取剩余部分 */
- uint32_t expected_total = data_offset + actual_len;
- while (total_received < expected_total && total_received < sizeof(static_response_buffer))
- {
- if ((rt_tick_get() - start_tick) >= timeout_ticks)
- {
- LOG_E("Timeout waiting for full data block (got %lu/%lu)",
- total_received, expected_total);
- Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "数据块接收超时");
- return -1;
- }
- rt_size_t read_len = rt_device_read(g_ftp.uart_dev, 0,
- static_response_buffer + total_received,
- sizeof(static_response_buffer) - total_received);
- if (read_len > 0)
- {
- total_received += read_len;
- }
- else
- {
- rt_thread_mdelay(2);
- }
- }
- /* 检查是否收全 */
- if (total_received < expected_total)
- {
- LOG_E("Incomplete data: expected %lu, got %lu", expected_total, total_received);
- Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "数据不完整");
- return -1;
- }
- /* 提取有效数据 */
- if (data_offset + actual_len > total_received)
- {
- LOG_E("Data offset out of bounds");
- return -1;
- }
- memcpy(g_ftp.download_buffer, static_response_buffer + data_offset, actual_len);
- /* 写入 Flash */
- if (fal_partition_write(g_ftp.flash_part, offset, g_ftp.download_buffer, actual_len) < 0)
- {
- LOG_E("Flash write failed at offset %lu", offset);
- Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "写入Flash失败");
- return -1;
- }
- // rt_kprintf("\n FW content IS Form 0x%X SIZE 0x%0X \n", offset, actual_len);
- // for (int a = 0; a < actual_len; a++)
- // {
- // rt_kprintf("%02X ", g_ftp.download_buffer[a]);
- // if ((a + 1) % 16 == 0)
- // rt_kprintf("\n");
- // }
- firmware_crc_update(&g_fw_crc_ctx, g_ftp.download_buffer, actual_len);
- offset += actual_len;
- g_ftp.downloaded = offset;
- /* 更新进度 */
- int new_percent = (offset * 100) / g_ftp.file_size;
- if (new_percent != percent)
- {
- percent = new_percent;
- update_progress(percent);
- }
- print_download_status(offset, g_ftp.file_size, block_count);
- if (actual_len < request_len)
- {
- LOG_I("Last block received (size: %lu)", actual_len);
- break;
- }
- /* 让出 CPU,但不再固定延时 */
- if (block_count % 20 == 0)
- {
- rt_thread_yield();
- }
- }
- if (offset >= g_ftp.file_size)
- {
- LOG_I("Download completed: %lu bytes in %d blocks", offset, block_count);
- update_progress(100);
- return 0;
- }
- else if (!g_ftp.is_running)
- {
- LOG_I("Download stopped by user");
- return -1;
- }
- else
- {
- LOG_E("Download incomplete: %lu/%lu", offset, g_ftp.file_size);
- Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "下载不完整");
- return -1;
- }
- }
- // 在 ftp_app.c 中添加以下函数(建议放在 enhanced_ftp_download 函数之后)
- // 专用于验证的 CRC 函数(带独立计数器)
- static void firmware_crc_verify(firmware_crc_ctx_t *ctx, const uint8_t *data, size_t len)
- {
- // ? 标准 CRC-32/IEEE 的 bit-reflected 多项式
- const uint32_t POLY = 0xEDB88320U;
- uint32_t crc = ctx->crc;
- for (size_t i = 0; i < len; i++)
- {
- crc ^= data[i]; // 输入字节直接异或(REFIN=true 由右移实现)
- for (int j = 0; j < 8; j++)
- {
- if (crc & 1)
- {
- crc = (crc >> 1) ^ POLY;
- }
- else
- {
- crc >>= 1;
- }
- }
- }
- ctx->crc = crc;
- static int verify_cnt = 1; // 独立计数器
- uint32_t final_crc = crc ^ 0xFFFFFFFF;
- rt_kprintf("Verify Packet %d CRC: %08X\n", verify_cnt, final_crc);
- verify_cnt++;
- }
- static int8_t verify_firmware_in_flash(void)
- {
- const uint32_t BLOCK_SIZE = 1024;
- uint8_t *verify_buffer = rt_malloc(BLOCK_SIZE);
- if (!verify_buffer)
- {
- LOG_E("Failed to allocate verify buffer");
- return -1;
- }
- firmware_crc_ctx_t verify_ctx = {.crc = 0xFFFFFFFF};
- uint32_t offset = 0;
- uint32_t total_verified = 0; // ← 新增
- LOG_I("Starting firmware verification from flash...");
- while (total_verified < g_ftp.file_size)
- { // ← 改为基于已验证字节数
- uint32_t remaining = g_ftp.file_size - total_verified;
- uint32_t read_len = (remaining < BLOCK_SIZE) ? remaining : BLOCK_SIZE;
- if (fal_partition_read(g_ftp.flash_part, offset, verify_buffer, read_len) != read_len)
- {
- LOG_E("Flash read failed at offset %lu", offset);
- rt_free(verify_buffer);
- return -1;
- }
- firmware_crc_verify(&verify_ctx, verify_buffer, read_len);
- offset += read_len;
- total_verified += read_len; // ← 明确累加
- }
- uint32_t verified_crc = verify_ctx.crc ^ 0xFFFFFFFF;
- rt_kprintf("Verification completed. Final CRC from flash: %08X\n", verified_crc);
- rt_free(verify_buffer);
- uint32_t original_crc = g_fw_crc_ctx.crc ^ 0xFFFFFFFF; // ← 直接计算,避免宏问题
- if (verified_crc == original_crc)
- {
- LOG_I("? Firmware verification PASSED!");
- return 1;
- }
- else
- {
- LOG_E("? Firmware verification FAILED! expected %08X, got %08X", original_crc, verified_crc);
- return 0;
- }
- }
- /* ====================== 下载线程 ====================== */
- extern void RESET_SYSTEM(void);
- static void download_thread_entry(void *arg)
- {
- /* 关键防护:再次确认已初始化 */
- if (!g_ftp_inited)
- {
- LOG_E("FTP app not initialized! Thread abort.");
- return;
- }
- int result = -1;
- LOG_I("FTP download thread started");
- rt_mutex_take(&g_ftp.mutex, RT_WAITING_FOREVER);
- g_ftp.is_running = RT_TRUE;
- rt_mutex_release(&g_ftp.mutex);
- /* 添加线程延时,避免立即开始占用资源 */
- rt_thread_mdelay(100);
- LOG_I("Step 1: Wait for system init (%d seconds)", SYS_INIT_WAIT);
- update_state(FTP_STATE_INIT_WAIT);
- for (int i = SYS_INIT_WAIT; i > 0; i--)
- {
- if (!g_ftp.is_running)
- {
- LOG_I("Download stopped during init wait");
- goto thread_exit;
- }
- LOG_D("Init wait: %d", i);
- safe_delay(1000);
- }
- if (!g_ftp.is_running)
- goto thread_exit;
- if (module_power_cycle() != 0)
- goto exit_with_error;
- if (!g_ftp.is_running)
- goto thread_exit;
- if (uart_init() != 0)
- goto exit_with_error;
- if (!g_ftp.is_running)
- goto thread_exit;
- if (check_module_ready() != 0)
- goto exit_with_error;
- if (!g_ftp.is_running)
- goto thread_exit;
- if (check_network() != 0)
- goto exit_with_error;
- if (!g_ftp.is_running)
- goto thread_exit;
- if (configure_ftp() != 0)
- goto exit_with_error;
- if (!g_ftp.is_running)
- goto thread_exit;
- if (get_file_size(&g_ftp.file_size) != 0)
- goto exit_with_error;
- if (!g_ftp.is_running)
- goto thread_exit;
- if (g_ftp.file_size < 1024 || g_ftp.file_size > 10 * 1024 * 1024) /* 限制文件大小 */
- {
- LOG_E("Invalid file size: %lu", g_ftp.file_size);
- goto exit_with_error;
- }
- if (!g_ftp.is_running)
- goto thread_exit;
- if (prepare_flash_storage(g_ftp.file_size) != 0)
- goto exit_with_error;
- url_info_t info = {0};
- if (parse_url(qxz.Param.upgrade_url, &info) == 0)
- {
- // printf("Protocol: %s(%d)\n", info.protocol, strlen(info.protocol));
- // printf("Host: %s(%d)\n", info.host, strlen(info.host));
- // printf("Port: %d(%d)\n", info.port, strlen(info.port));
- // printf("User: %s(%d)\n", info.username, strlen(info.username));
- // printf("Pass: %s(%d)\n", info.password, strlen(info.password));
- // printf("Path: %s(%d)\n", info.path, strlen(info.path));
- // printf("Dir: %s(%d)\n", info.dir, strlen(info.dir));
- // printf("File: %s(%d)\n", info.filename, strlen(info.filename));
- }
- char aaa[64] = {0};
- sprintf(aaa, "固件下载开始 %s=(%d)bytes", info.filename, g_ftp.file_size);
- Recode_e_code(downloade_fw_succ_ec, STEP_DOWNLOAD_COMPLETE, aaa);
- if (!g_ftp.is_running)
- goto thread_exit;
- if (enhanced_ftp_download() != 0)
- goto exit_with_error;
- LOG_I("Download completed. File size: %lu", g_ftp.file_size);
- update_state(FTP_STATE_COMPLETED);
- uint32_t final_crc = FIRMWARE_CRC_FINAL(&g_fw_crc_ctx);
- rt_kprintf("final_crc %08X \n", final_crc);
- if (verify_firmware_in_flash())
- {
- sprintf(aaa, "固件读出校验成功 %08X", final_crc);
- Recode_e_code(downloade_fw_succ_ec, STEP_DOWNLOAD_COMPLETE, aaa);
- }
- else
- {
- sprintf(aaa, "固件读出校验失败 %08X", final_crc);
- Recode_e_code(downloade_fw_succ_ec, 77, aaa);
- }
- result = 0;
- goto cleanup;
- exit_with_error:
- LOG_E("Download process failed");
- update_state(FTP_STATE_FAILED);
- result = -1;
- cleanup:
- LOG_I("Closing FTP session");
- at_send_command("AT+FTPQUIT", "OK", 5);
- if (g_ftp.uart_dev)
- {
- rt_device_close(g_ftp.uart_dev);
- g_ftp.uart_dev = RT_NULL;
- }
- thread_exit:
- RESET_SYSTEM();
- rt_mutex_take(&g_ftp.mutex, RT_WAITING_FOREVER);
- g_ftp.is_running = RT_FALSE;
- rt_mutex_release(&g_ftp.mutex);
- LOG_I("Download thread exited, result: %s", result == 0 ? "SUCCESS" : "FAILED");
- }
- /* ====================== 公共API ====================== */
- int ftp_app_init(void)
- {
- if (g_ftp_inited)
- {
- LOG_W("FTP app already initialized");
- return 0;
- }
- LOG_I("Initializing FTP application");
- memset(&g_ftp, 0, sizeof(g_ftp));
- g_ftp.state = FTP_STATE_IDLE;
- g_ftp.progress = 0;
- g_ftp.is_running = RT_FALSE;
- g_ftp.thread = RT_NULL;
- g_ftp.uart_dev = RT_NULL;
- g_ftp.flash_part = RT_NULL;
- g_ftp.download_buffer = NULL;
- if (rt_mutex_init(&g_ftp.mutex, "ftp_mutex", RT_IPC_FLAG_FIFO) != RT_EOK)
- {
- LOG_E("Mutex init failed");
- return -1;
- }
- // if (power_init() != 0)
- // {
- // LOG_E("Power init failed");
- // rt_mutex_detach(&g_ftp.mutex);
- // return -1;
- // }
- g_ftp_inited = RT_TRUE;
- LOG_I("FTP application initialized");
- return 0;
- }
- int ftp_start_download(void)
- {
- ftp_app_init();
- if (!g_ftp_inited)
- {
- LOG_E("FTP app not initialized! Call ftp_app_init() first.");
- return -1;
- }
- rt_base_t level = rt_hw_interrupt_disable();
- rt_bool_t running;
- rt_mutex_take(&g_ftp.mutex, RT_WAITING_FOREVER);
- running = g_ftp.is_running;
- rt_mutex_release(&g_ftp.mutex);
- rt_hw_interrupt_enable(level);
- if (running)
- {
- LOG_W("Download already running");
- return -1;
- }
- LOG_I("Starting FTP download");
- g_ftp.thread = rt_thread_create("ftp_dl",
- download_thread_entry,
- RT_NULL,
- 4096,
- 10,
- 10);
- if (g_ftp.thread == RT_NULL)
- {
- LOG_E("Thread create failed");
- return -1;
- }
- if (rt_thread_startup(g_ftp.thread) != RT_EOK)
- {
- LOG_E("Thread startup failed");
- rt_thread_delete(g_ftp.thread);
- g_ftp.thread = RT_NULL;
- return -1;
- }
- return 0;
- }
- int ftp_stop_download(void)
- {
- if (!g_ftp_inited)
- {
- LOG_W("FTP app not initialized");
- return -1;
- }
- rt_base_t level = rt_hw_interrupt_disable();
- rt_bool_t running;
- rt_mutex_take(&g_ftp.mutex, RT_WAITING_FOREVER);
- running = g_ftp.is_running;
- if (running)
- {
- g_ftp.is_running = RT_FALSE;
- }
- rt_mutex_release(&g_ftp.mutex);
- rt_hw_interrupt_enable(level);
- if (!running)
- {
- LOG_W("No download running");
- return -1;
- }
- LOG_I("Stopping FTP download");
- if (g_ftp.thread)
- {
- /* 等待线程结束 */
- for (int i = 0; i < 20; i++) /* 最多等待2秒 */
- {
- rt_mutex_take(&g_ftp.mutex, RT_WAITING_FOREVER);
- if (!g_ftp.is_running)
- {
- rt_mutex_release(&g_ftp.mutex);
- break;
- }
- rt_mutex_release(&g_ftp.mutex);
- rt_thread_mdelay(100);
- }
- g_ftp.thread = RT_NULL;
- }
- update_state(FTP_STATE_STOPPED);
- return 0;
- }
- ftp_state_t ftp_get_state(void)
- {
- if (!g_ftp_inited)
- return FTP_STATE_IDLE;
- return g_ftp.state;
- }
- int ftp_get_progress(void)
- {
- if (!g_ftp_inited)
- return 0;
- return g_ftp.progress;
- }
- /* ====================== 自动初始化 ====================== */
- /* ====================== MSH 命令 ====================== */
- #ifdef RT_USING_FINSH
- #include <shell.h>
- static int cmd_ftp_start(int argc, char **argv)
- {
- rt_kprintf("[FTP] Starting firmware download...\n");
- if (ftp_start_download() == 0)
- {
- rt_kprintf("[FTP] Download started successfully.\n");
- }
- else
- {
- rt_kprintf("[FTP] Failed to start download!\n");
- }
- return 0;
- }
- static int cmd_ftp_stop(int argc, char **argv)
- {
- rt_kprintf("[FTP] Stopping firmware download...\n");
- if (ftp_stop_download() == 0)
- {
- rt_kprintf("[FTP] Download stopped.\n");
- }
- else
- {
- rt_kprintf("[FTP] No active download to stop.\n");
- }
- return 0;
- }
- static int cmd_ftp_status(int argc, char **argv)
- {
- ftp_state_t state = ftp_get_state();
- int progress = ftp_get_progress();
- rt_kprintf("[FTP] Status: ");
- switch (state)
- {
- case FTP_STATE_IDLE:
- rt_kprintf("IDLE");
- break;
- case FTP_STATE_INIT_WAIT:
- rt_kprintf("INIT_WAIT");
- break;
- case FTP_STATE_MODULE_BOOT:
- rt_kprintf("MODULE_BOOT");
- break;
- case FTP_STATE_NETWORK_WAIT:
- rt_kprintf("NETWORK_WAIT");
- break;
- case FTP_STATE_FTP_SETUP:
- rt_kprintf("FTP_SETUP");
- break;
- case FTP_STATE_DOWNLOADING:
- rt_kprintf("DOWNLOADING");
- break;
- case FTP_STATE_COMPLETED:
- rt_kprintf("COMPLETED");
- break;
- case FTP_STATE_FAILED:
- rt_kprintf("FAILED");
- break;
- case FTP_STATE_STOPPED:
- rt_kprintf("STOPPED");
- break;
- default:
- rt_kprintf("UNKNOWN");
- break;
- }
- rt_kprintf("\n[FTP] Progress: %d%%\n", progress);
- /* 显示下载统计信息 */
- if (g_ftp_inited && g_ftp.file_size > 0)
- {
- rt_kprintf("[FTP] File size: %lu bytes\n", g_ftp.file_size);
- rt_kprintf("[FTP] Downloaded: %lu bytes\n", g_ftp.downloaded);
- if (state == FTP_STATE_DOWNLOADING && g_ftp.downloaded > 0)
- {
- uint32_t remaining = g_ftp.file_size - g_ftp.downloaded;
- rt_kprintf("[FTP] Remaining: %lu bytes\n", remaining);
- if (g_ftp.downloaded > 0)
- {
- /* 估算剩余时间(假设平均下载速度) */
- static rt_tick_t start_time = 0;
- static uint32_t last_downloaded = 0;
- if (start_time == 0)
- {
- start_time = rt_tick_get();
- last_downloaded = g_ftp.downloaded;
- }
- else if (g_ftp.downloaded > last_downloaded + 10240) /* 每下载10KB更新一次 */
- {
- rt_tick_t elapsed = rt_tick_get() - start_time;
- uint32_t downloaded_since = g_ftp.downloaded - last_downloaded;
- if (elapsed > 0 && downloaded_since > 0)
- {
- uint32_t bytes_per_tick = (downloaded_since * RT_TICK_PER_SECOND) / elapsed;
- if (bytes_per_tick > 0)
- {
- uint32_t remaining_seconds = remaining / bytes_per_tick;
- rt_kprintf("[FTP] Estimated time remaining: %lu seconds\n", remaining_seconds);
- }
- }
- last_downloaded = g_ftp.downloaded;
- }
- }
- }
- }
- return 0;
- }
- // MSH_CMD_EXPORT(cmd_ftp_start, "Start FTP firmware download");
- #endif /* RT_USING_FINSH */
|