ftp_app.c 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902
  1. #include "ftp_app.h"
  2. #include <fal.h>
  3. #include <rtdevice.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <board.h>
  7. /* 日志配置 */
  8. #define DBG_ENABLE
  9. #define LOG_TAG "FTP"
  10. #define DBG_LVL DBG_INFO
  11. #include <rtdbg.h>
  12. /* 超时时间(单位:秒) */
  13. #define SYS_INIT_WAIT 3
  14. #define MODULE_BOOT_WAIT 3
  15. #define AT_CMD_TIMEOUT 5
  16. #define NETWORK_WAIT_MAX 180
  17. #define FTP_CMD_TIMEOUT 10
  18. #define DOWNLOAD_TIMEOUT 600
  19. /* 缓冲区大小 */
  20. #define AT_LINE_BUF_SIZE 128
  21. #define FTP_RESPONSE_BUFFER_SIZE 2048 /* 响应缓冲区大小 */
  22. /* 全局应用实例 */
  23. static ftp_app_t g_ftp = {0};
  24. static volatile rt_bool_t g_ftp_inited = RT_FALSE; /* 标记是否已初始化 */
  25. /* 私有函数声明 */
  26. static int uart_init(void);
  27. static void uart_clean(void);
  28. static int at_send_command(const char *cmd, const char *expect, uint32_t timeout);
  29. static int read_response_line(char *buf, int size, uint32_t timeout);
  30. static int read_response_raw(uint8_t *buf, uint32_t size, uint32_t timeout_ms);
  31. static int module_power_cycle(void);
  32. static int check_module_ready(void);
  33. static int check_network(void);
  34. static int configure_gprs_bearer(void);
  35. static int configure_ftp(void);
  36. static int get_file_size(uint32_t *size);
  37. static int prepare_flash_storage(uint32_t file_size);
  38. static int start_ftp_session(void);
  39. static int enhanced_ftp_download(void);
  40. static void download_thread_entry(void *arg);
  41. static void safe_delay(uint32_t ms);
  42. static void update_state(ftp_state_t state);
  43. static void update_progress(int percent);
  44. static int parse_ftpget_response(uint8_t *buffer, uint32_t buffer_size, uint32_t *data_length, uint32_t *data_offset);
  45. static void print_download_status(uint32_t offset, uint32_t total, int block_count);
  46. typedef struct
  47. {
  48. char protocol[16]; // http, https, ftp等
  49. char host[32]; // 域名或IP
  50. int port; // 端口号
  51. char path[64]; // 完整路径
  52. char dir[32]; // 目录路径
  53. char filename[24]; // 文件名
  54. char username[32]; // FTP用户名(可选)
  55. char password[32]; // FTP密码(可选)
  56. } url_info_t;
  57. // 简易的字符串转小写函数
  58. static void str_tolower(char *str)
  59. {
  60. while (*str)
  61. {
  62. *str = tolower((unsigned char)*str);
  63. str++;
  64. }
  65. }
  66. int parse_url(const char *url, url_info_t *info)
  67. {
  68. if (!url || !info)
  69. return -1;
  70. memset(info, 0, sizeof(url_info_t));
  71. // 查找协议分隔符
  72. const char *protocol_end = strstr(url, "://");
  73. if (protocol_end)
  74. {
  75. size_t proto_len = protocol_end - url;
  76. if (proto_len >= sizeof(info->protocol))
  77. return -1;
  78. strncpy(info->protocol, url, proto_len);
  79. info->protocol[proto_len] = '\0';
  80. str_tolower(info->protocol); // 统一转换为小写
  81. url = protocol_end + 3; // 跳过"://"
  82. }
  83. else
  84. {
  85. // 没有明确指定协议,默认为http
  86. strcpy(info->protocol, "http");
  87. }
  88. // 设置协议对应的默认端口
  89. if (strcmp(info->protocol, "ftp") == 0 ||
  90. strcmp(info->protocol, "ftps") == 0)
  91. {
  92. info->port = 21; // FTP默认端口
  93. }
  94. else if (strcmp(info->protocol, "http") == 0)
  95. {
  96. info->port = 80; // HTTP默认端口
  97. }
  98. else if (strcmp(info->protocol, "https") == 0)
  99. {
  100. info->port = 443; // HTTPS默认端口
  101. }
  102. else
  103. {
  104. info->port = 80; // 其他协议默认使用80
  105. }
  106. // 复制一份URL用于处理认证信息
  107. char url_buffer[256] = {0};
  108. strncpy(url_buffer, url, sizeof(url_buffer) - 1);
  109. char *current_pos = url_buffer;
  110. // 处理认证信息(user:pass@host)
  111. char *at_pos = strchr(current_pos, '@');
  112. if (at_pos)
  113. {
  114. // 包含认证信息
  115. *at_pos = '\0'; // 分割认证信息和主机部分
  116. // 分离用户名和密码
  117. char *colon_pos = strchr(current_pos, ':');
  118. if (colon_pos)
  119. {
  120. // 有密码:user:pass
  121. size_t user_len = colon_pos - current_pos;
  122. if (user_len > 0 && user_len < sizeof(info->username))
  123. {
  124. strncpy(info->username, current_pos, user_len);
  125. info->username[user_len] = '\0';
  126. }
  127. size_t pass_len = at_pos - (colon_pos + 1);
  128. if (pass_len > 0 && pass_len < sizeof(info->password))
  129. {
  130. strncpy(info->password, colon_pos + 1, pass_len);
  131. info->password[pass_len] = '\0';
  132. }
  133. }
  134. else
  135. {
  136. // 只有用户名:user@
  137. size_t user_len = at_pos - current_pos;
  138. if (user_len > 0 && user_len < sizeof(info->username))
  139. {
  140. strncpy(info->username, current_pos, user_len);
  141. info->username[user_len] = '\0';
  142. }
  143. }
  144. // 主机部分从@之后开始
  145. current_pos = at_pos + 1;
  146. }
  147. // 查找路径起始位置
  148. char *path_start = strchr(current_pos, '/');
  149. // 解析主机和端口
  150. if (path_start)
  151. {
  152. // 有路径部分
  153. *path_start = '\0'; // 分割主机和路径
  154. size_t host_len = strlen(current_pos);
  155. // 检查是否有端口号
  156. char *port_start = strchr(current_pos, ':');
  157. if (port_start)
  158. {
  159. // 有端口号
  160. *port_start = '\0'; // 分割主机和端口
  161. if (strlen(current_pos) < sizeof(info->host))
  162. {
  163. strcpy(info->host, current_pos);
  164. }
  165. info->port = atoi(port_start + 1);
  166. }
  167. else
  168. {
  169. // 没有端口号,使用协议默认端口
  170. if (host_len < sizeof(info->host))
  171. {
  172. strcpy(info->host, current_pos);
  173. }
  174. }
  175. // 恢复路径部分
  176. *path_start = '/';
  177. // 复制完整路径
  178. size_t path_len = strlen(path_start);
  179. if (path_len > 0 && path_len < sizeof(info->path))
  180. {
  181. strcpy(info->path, path_start);
  182. }
  183. else
  184. {
  185. strcpy(info->path, "/");
  186. }
  187. }
  188. else
  189. {
  190. // 没有路径部分,只有主机名
  191. size_t host_len = strlen(current_pos);
  192. // 检查是否有端口号
  193. char *port_start = strchr(current_pos, ':');
  194. if (port_start)
  195. {
  196. // 有端口号
  197. *port_start = '\0'; // 分割主机和端口
  198. if (strlen(current_pos) < sizeof(info->host))
  199. {
  200. strcpy(info->host, current_pos);
  201. }
  202. info->port = atoi(port_start + 1);
  203. }
  204. else
  205. {
  206. // 没有端口号
  207. if (host_len < sizeof(info->host))
  208. {
  209. strcpy(info->host, current_pos);
  210. }
  211. }
  212. strcpy(info->path, "/");
  213. }
  214. // 分离目录和文件名
  215. if (strlen(info->path) > 0)
  216. {
  217. // 查找最后一个斜杠
  218. char *last_slash = strrchr(info->path, '/');
  219. if (last_slash)
  220. {
  221. // 复制文件名(最后一个斜杠之后的内容)
  222. if (strlen(last_slash + 1) > 0)
  223. {
  224. strncpy(info->filename, last_slash + 1, sizeof(info->filename) - 1);
  225. }
  226. // 提取目录(包括最后一个斜杠)
  227. size_t dir_len = last_slash - info->path + 1; // +1 包含斜杠
  228. if (dir_len > 0)
  229. {
  230. if (dir_len < sizeof(info->dir))
  231. {
  232. strncpy(info->dir, info->path, dir_len);
  233. info->dir[dir_len] = '\0';
  234. }
  235. }
  236. else
  237. {
  238. // 根目录
  239. strcpy(info->dir, "/");
  240. }
  241. }
  242. else
  243. {
  244. // 没有斜杠,整个路径作为文件名
  245. strncpy(info->filename, info->path, sizeof(info->filename) - 1);
  246. strcpy(info->dir, "/");
  247. }
  248. }
  249. else
  250. {
  251. strcpy(info->path, "/");
  252. strcpy(info->dir, "/");
  253. }
  254. return 0;
  255. }
  256. // 用于RT-Thread控制台的纯英文测试函数
  257. void url_parse_test(void)
  258. {
  259. printf("=== HTTP URL Test ===\n");
  260. const char *http_url = "http://www.yfzhwlw.com/update/qxz_bin/qxzH_300.rbl";
  261. url_info_t info;
  262. if (parse_url(http_url, &info) == 0)
  263. {
  264. printf("Protocol: %s(%d)\n", info.protocol, strlen(info.protocol));
  265. printf("Host: %s(%d)\n", info.host, strlen(info.host));
  266. printf("Port: %d(%d)\n", info.port, strlen(info.port));
  267. printf("User: %s(%d)\n", info.username, strlen(info.username));
  268. printf("Pass: %s(%d)\n", info.password, strlen(info.password));
  269. printf("Path: %s(%d)\n", info.path, strlen(info.path));
  270. printf("Dir: %s(%d)\n", info.dir, strlen(info.dir));
  271. printf("File: %s(%d)\n", info.filename, strlen(info.filename));
  272. }
  273. printf("\n=== FTP URL Test (with auth) ===\n");
  274. const char *ftp_url = "ftp://updateuser:123456@www.rrwrwwrw.com:21/qxz_bin/qxz_FTP.rbl";
  275. if (parse_url(ftp_url, &info) == 0)
  276. {
  277. printf("Protocol: %s\n", info.protocol);
  278. printf("Host: %s\n", info.host);
  279. printf("Port: %d\n", info.port);
  280. printf("User: %s\n", info.username);
  281. printf("Pass: %s\n", info.password);
  282. printf("Path: %s\n", info.path);
  283. printf("Dir: %s\n", info.dir);
  284. printf("File: %s\n", info.filename);
  285. // 验证:FTP目录应该以/结尾
  286. if (info.dir[strlen(info.dir) - 1] != '/')
  287. {
  288. printf("[Note] FTP dir should end with '/'\n");
  289. }
  290. }
  291. printf("\n=== FTP URL Test (anonymous) ===\n");
  292. const char *ftp_anon_url = "ftp://ftp.example.com/pub/files/data.bin";
  293. if (parse_url(ftp_anon_url, &info) == 0)
  294. {
  295. printf("Protocol: %s\n", info.protocol);
  296. printf("Host: %s\n", info.host);
  297. printf("Port: %d\n", info.port);
  298. printf("User: %s\n", info.username);
  299. printf("Pass: %s\n", info.password);
  300. printf("Path: %s\n", info.path);
  301. printf("Dir: %s\n", info.dir);
  302. printf("File: %s\n", info.filename);
  303. }
  304. printf("\n=== FTP URL Test (user only) ===\n");
  305. const char *ftp_user_url = "ftp://user@example.com:2121/path/to/file.txt";
  306. if (parse_url(ftp_user_url, &info) == 0)
  307. {
  308. printf("Protocol: %s\n", info.protocol);
  309. printf("Host: %s\n", info.host);
  310. printf("Port: %d\n", info.port);
  311. printf("User: %s\n", info.username);
  312. printf("Pass: %s\n", info.password);
  313. printf("Path: %s\n", info.path);
  314. printf("Dir: %s\n", info.dir);
  315. printf("File: %s\n", info.filename);
  316. }
  317. printf("\n=== Edge Cases Test ===\n");
  318. }
  319. // MSH_CMD_EXPORT(url_parse_test, URL parse test for HTTP and FTP);
  320. // 全局上下文,初始值为 0xFFFFFFFF(INIT)
  321. static firmware_crc_ctx_t g_fw_crc_ctx = {.crc = 0xFFFFFFFF};
  322. void firmware_crc_update(firmware_crc_ctx_t *ctx, const uint8_t *data, size_t len)
  323. {
  324. // ? 标准 CRC-32/IEEE 的 bit-reflected 多项式
  325. const uint32_t POLY = 0xEDB88320U;
  326. uint32_t crc = ctx->crc;
  327. for (size_t i = 0; i < len; i++)
  328. {
  329. crc ^= data[i]; // 输入字节直接异或(REFIN=true 由右移实现)
  330. for (int j = 0; j < 8; j++)
  331. {
  332. if (crc & 1)
  333. {
  334. crc = (crc >> 1) ^ POLY;
  335. }
  336. else
  337. {
  338. crc >>= 1;
  339. }
  340. }
  341. }
  342. ctx->crc = crc;
  343. static int cnt = 1;
  344. // ? XOROUT = 0xFFFFFFFF
  345. uint32_t final_crc = crc ^ 0xFFFFFFFF;
  346. // rt_kprintf("firmware_crc_update %d(byte) >> %d > %08X\n", len, cnt, final_crc);
  347. cnt++;
  348. }
  349. /* ====================== 辅助函数 ====================== */
  350. static void safe_delay(uint32_t ms)
  351. {
  352. rt_tick_t start = rt_tick_get();
  353. rt_tick_t timeout = rt_tick_from_millisecond(ms);
  354. while ((rt_tick_get() - start) < timeout)
  355. {
  356. rt_thread_mdelay(10);
  357. }
  358. }
  359. static void update_state(ftp_state_t state)
  360. {
  361. if (!g_ftp_inited)
  362. return;
  363. g_ftp.state = state;
  364. LOG_I("State changed to: %d", state);
  365. }
  366. static void update_progress(int percent)
  367. {
  368. if (!g_ftp_inited)
  369. return;
  370. if (percent < 0)
  371. percent = 0;
  372. if (percent > 100)
  373. percent = 100;
  374. /* 只有当进度变化时才更新 */
  375. if (percent != g_ftp.progress)
  376. {
  377. g_ftp.progress = percent;
  378. /* 每5%或者特殊值(0,100)记录日志 */
  379. if (percent % 5 == 0 || percent == 0 || percent == 100)
  380. {
  381. LOG_I("Progress: %d%%", percent);
  382. }
  383. }
  384. }
  385. /* 实时打印下载状态 */
  386. static void print_download_status(uint32_t offset, uint32_t total, int block_count)
  387. {
  388. int percent = (total > 0) ? (offset * 100) / total : 0;
  389. /* 每10个块或者每5%进度打印一次详细状态 */
  390. if (block_count % 10 == 0 || percent % 5 == 0)
  391. {
  392. LOG_I("Download: %lu/%lu bytes (%d%%) - Block: %d",
  393. offset, total, percent, block_count);
  394. }
  395. else if (block_count % 5 == 0)
  396. {
  397. /* 更频繁但简单的状态更新 */
  398. // LOG_D("DL: %lu/%lu (%d%%)", offset, total, percent);
  399. }
  400. }
  401. /* ====================== UART通信 ====================== */
  402. static int uart_init(void)
  403. {
  404. struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;
  405. LOG_I("Initializing UART: %s %dbps", AIR720_UART_NAME, AIR720_UART_BAUD);
  406. g_ftp.uart_dev = rt_device_find(AIR720_UART_NAME);
  407. if (!g_ftp.uart_dev)
  408. {
  409. LOG_E("UART device not found: %s", AIR720_UART_NAME);
  410. return -1;
  411. }
  412. config.baud_rate = AIR720_UART_BAUD;
  413. config.data_bits = DATA_BITS_8;
  414. config.stop_bits = STOP_BITS_1;
  415. config.parity = PARITY_NONE;
  416. config.bufsz = 2048; /* 增加缓冲区大小以容纳二进制数据 */
  417. if (rt_device_control(g_ftp.uart_dev, RT_DEVICE_CTRL_CONFIG, &config) != RT_EOK)
  418. {
  419. LOG_E("UART config failed");
  420. return -1;
  421. }
  422. if (rt_device_open(g_ftp.uart_dev, RT_DEVICE_FLAG_INT_RX) != RT_EOK)
  423. {
  424. LOG_E("Open UART failed");
  425. g_ftp.uart_dev = RT_NULL;
  426. return -1;
  427. }
  428. LOG_I("UART initialized");
  429. return 0;
  430. }
  431. static void uart_clean(void)
  432. {
  433. char temp_buf[64];
  434. rt_size_t read_len;
  435. if (!g_ftp.uart_dev)
  436. return;
  437. do
  438. {
  439. read_len = rt_device_read(g_ftp.uart_dev, 0, temp_buf, sizeof(temp_buf));
  440. if (read_len > 0)
  441. {
  442. LOG_D("Cleaned %d bytes", read_len);
  443. rt_thread_mdelay(5);
  444. }
  445. } while (read_len > 0);
  446. }
  447. static int read_response_line(char *buf, int size, uint32_t timeout_ms)
  448. {
  449. int pos = 0;
  450. char ch;
  451. rt_size_t read_len;
  452. rt_tick_t start = rt_tick_get();
  453. if (!buf || size <= 1)
  454. return -1;
  455. buf[0] = '\0';
  456. while ((rt_tick_get() - start) < rt_tick_from_millisecond(timeout_ms))
  457. {
  458. read_len = rt_device_read(g_ftp.uart_dev, 0, &ch, 1);
  459. if (read_len == 1)
  460. {
  461. if (ch == '\n')
  462. {
  463. if (pos > 0 && buf[pos - 1] == '\r')
  464. {
  465. buf[pos - 1] = '\0';
  466. }
  467. else if (pos < size - 1)
  468. {
  469. buf[pos] = '\0';
  470. }
  471. else
  472. {
  473. buf[size - 1] = '\0';
  474. }
  475. return 0;
  476. }
  477. if (ch == '\r')
  478. continue;
  479. if (pos < size - 1)
  480. {
  481. buf[pos++] = ch;
  482. }
  483. else
  484. {
  485. /* 缓冲区已满,直接返回 */
  486. buf[size - 1] = '\0';
  487. return 0;
  488. }
  489. }
  490. else
  491. {
  492. rt_thread_mdelay(1);
  493. }
  494. }
  495. if (pos > 0)
  496. {
  497. if (pos < size)
  498. buf[pos] = '\0';
  499. else
  500. buf[size - 1] = '\0';
  501. }
  502. return -1;
  503. }
  504. /* 读取原始响应数据 */
  505. static int read_response_raw(uint8_t *buf, uint32_t size, uint32_t timeout_ms)
  506. {
  507. rt_tick_t start = rt_tick_get();
  508. uint32_t total_read = 0;
  509. if (!buf || size == 0)
  510. return -1;
  511. while ((rt_tick_get() - start) < rt_tick_from_millisecond(timeout_ms))
  512. {
  513. rt_size_t read_len = rt_device_read(g_ftp.uart_dev, 0, buf + total_read, size - total_read);
  514. if (read_len > 0)
  515. {
  516. total_read += read_len;
  517. }
  518. rt_thread_mdelay(1);
  519. }
  520. return total_read; /* 返回实际读取的字节数 */
  521. }
  522. static int parse_ftpget_response(uint8_t *buffer, uint32_t buffer_size, uint32_t *data_length, uint32_t *data_offset)
  523. {
  524. if (!buffer || !data_length || !data_offset)
  525. return -1;
  526. *data_length = 0;
  527. *data_offset = 0;
  528. // 查找 "+FTPGET: 2," 或 "+FTPGET:2,"
  529. for (uint32_t i = 0; i < buffer_size - 12; i++)
  530. {
  531. // 匹配 "+FTPGET:2," (无空格)
  532. if (memcmp(&buffer[i], "+FTPGET:2,", 10) == 0)
  533. {
  534. uint32_t num_start = i + 10;
  535. uint32_t j = num_start;
  536. while (j < buffer_size && buffer[j] >= '0' && buffer[j] <= '9')
  537. j++;
  538. if (j > num_start)
  539. {
  540. // 解析长度
  541. *data_length = 0;
  542. for (uint32_t k = num_start; k < j; k++)
  543. {
  544. *data_length = *data_length * 10 + (buffer[k] - '0');
  545. }
  546. if (*data_length == 0)
  547. return -1;
  548. // 找到这一行的结束:下一个 \n
  549. uint32_t line_end = j;
  550. while (line_end < buffer_size && buffer[line_end] != '\n')
  551. line_end++;
  552. if (line_end < buffer_size)
  553. line_end++; // 跳过 \n
  554. // 跳过可能的 \r\n 中的 \r
  555. if (line_end > 0 && buffer[line_end - 1] == '\n')
  556. {
  557. if (line_end >= 2 && buffer[line_end - 2] == '\r')
  558. {
  559. // 已经包含 \r\n,line_end 指向 \n 后一位
  560. }
  561. }
  562. *data_offset = line_end;
  563. // LOG_D("Parsed FTPGET: len=%lu, data starts at offset=%lu", *data_length, *data_offset);
  564. return 0;
  565. }
  566. }
  567. // 匹配 "+FTPGET: 2," (有空格)
  568. else if (memcmp(&buffer[i], "+FTPGET: 2,", 11) == 0)
  569. {
  570. uint32_t num_start = i + 11;
  571. uint32_t j = num_start;
  572. while (j < buffer_size && buffer[j] >= '0' && buffer[j] <= '9')
  573. j++;
  574. if (j > num_start)
  575. {
  576. *data_length = 0;
  577. for (uint32_t k = num_start; k < j; k++)
  578. {
  579. *data_length = *data_length * 10 + (buffer[k] - '0');
  580. }
  581. if (*data_length == 0)
  582. return -1;
  583. uint32_t line_end = j;
  584. while (line_end < buffer_size && buffer[line_end] != '\n')
  585. line_end++;
  586. if (line_end < buffer_size)
  587. line_end++;
  588. *data_offset = line_end;
  589. // LOG_D("Parsed FTPGET (with space): len=%lu, data starts at offset=%lu", *data_length, *data_offset);
  590. return 0;
  591. }
  592. }
  593. }
  594. LOG_W("No valid +FTPGET: 2,... response found in buffer");
  595. return -1;
  596. }
  597. static int at_send_command(const char *cmd, const char *expect, uint32_t timeout_sec)
  598. {
  599. char line_buf[AT_LINE_BUF_SIZE];
  600. rt_size_t write_len;
  601. if (!g_ftp_inited || !g_ftp.uart_dev || !cmd)
  602. {
  603. return -1;
  604. }
  605. uart_clean();
  606. char full_cmd[128];
  607. int cmd_len = rt_snprintf(full_cmd, sizeof(full_cmd), "%s\r\n", cmd);
  608. if (cmd_len < 0 || cmd_len >= sizeof(full_cmd))
  609. {
  610. LOG_E("AT command too long: %s", cmd);
  611. return -1;
  612. }
  613. write_len = rt_device_write(g_ftp.uart_dev, 0, full_cmd, cmd_len);
  614. if (write_len != cmd_len)
  615. {
  616. LOG_E("AT write failed: %s", cmd);
  617. return -1;
  618. }
  619. LOG_D("TX: %s", cmd);
  620. rt_tick_t start = rt_tick_get();
  621. rt_tick_t timeout = rt_tick_from_millisecond(timeout_sec * 1000);
  622. while ((rt_tick_get() - start) < timeout)
  623. {
  624. if (read_response_line(line_buf, sizeof(line_buf), 100) == 0)
  625. {
  626. if (strlen(line_buf) == 0)
  627. continue;
  628. if (strstr(line_buf, "ERROR") || strstr(line_buf, "CME ERROR"))
  629. {
  630. LOG_E("AT error: %s", line_buf);
  631. return -1;
  632. }
  633. if (expect && strstr(line_buf, expect))
  634. {
  635. LOG_D("Found expected: %s", expect);
  636. return 0;
  637. }
  638. if (strstr(line_buf, "OK"))
  639. {
  640. return 0;
  641. }
  642. }
  643. }
  644. LOG_E("AT timeout: %s", cmd);
  645. return -1;
  646. }
  647. /* ====================== 模块控制 ====================== */
  648. static int power_init(void)
  649. {
  650. rt_pin_mode(AIR720_POWER_PIN, PIN_MODE_OUTPUT);
  651. AIR720_POWER_OFF();
  652. safe_delay(100);
  653. LOG_I("Power control ready");
  654. return 0;
  655. }
  656. static int module_power_cycle(void)
  657. {
  658. if (!g_ftp_inited)
  659. return -1;
  660. LOG_I("Module power cycle start");
  661. update_state(FTP_STATE_MODULE_BOOT);
  662. AIR720_POWER_OFF();
  663. LOG_I("Power OFF");
  664. safe_delay(2000);
  665. AIR720_POWER_ON();
  666. LOG_I("Power ON");
  667. for (int i = MODULE_BOOT_WAIT; i > 0; i--)
  668. {
  669. LOG_D("Boot wait: %d", i);
  670. safe_delay(1000);
  671. }
  672. LOG_I("Module boot completed");
  673. return 0;
  674. }
  675. static int check_module_ready(void)
  676. {
  677. if (!g_ftp_inited)
  678. return -1;
  679. int retry;
  680. LOG_I("Checking module readiness");
  681. for (retry = 0; retry < 10; retry++)
  682. {
  683. if (at_send_command("AT", "OK", AT_CMD_TIMEOUT) == 0)
  684. {
  685. LOG_I("Module ready");
  686. return 0;
  687. }
  688. LOG_W("Module not ready, retry %d", retry + 1);
  689. safe_delay(500);
  690. }
  691. LOG_E("Module check failed");
  692. Recode_e_code(e_fwdownload_fail, STEP_MODULE_CHECK, "AT command no response");
  693. return -1;
  694. }
  695. static int check_network(void)
  696. {
  697. if (!g_ftp_inited)
  698. return -1;
  699. int retry_count = 0;
  700. LOG_I("Checking network registration");
  701. update_state(FTP_STATE_NETWORK_WAIT);
  702. if (at_send_command("AT+CPIN?", "READY", AT_CMD_TIMEOUT) != 0)
  703. {
  704. LOG_E("SIM card not ready");
  705. Recode_e_code(e_fwdownload_fail, STEP_SIM_CHECK, "SIM not ready");
  706. return -1;
  707. }
  708. LOG_I("SIM card ready");
  709. while (retry_count < (NETWORK_WAIT_MAX / 5))
  710. {
  711. if (at_send_command("AT+CREG?", "+CREG: 0,1", AT_CMD_TIMEOUT) == 0)
  712. {
  713. LOG_I("Network registered");
  714. if (at_send_command("AT+CSQ", "+CSQ:", AT_CMD_TIMEOUT) == 0)
  715. {
  716. LOG_I("Signal OK");
  717. return 0;
  718. }
  719. }
  720. retry_count++;
  721. LOG_D("Network wait: %d/%d", retry_count * 5, NETWORK_WAIT_MAX);
  722. safe_delay(5000);
  723. }
  724. LOG_E("Network registration timeout");
  725. Recode_e_code(e_fwdownload_fail, STEP_NETWORK_REG, "Network timeout");
  726. return -1;
  727. }
  728. /* ====================== FTP配置 ====================== */
  729. static int configure_gprs_bearer(void)
  730. {
  731. return 0;
  732. }
  733. #include "sys_config.h"
  734. extern Sector qxz;
  735. static int configure_ftp(void)
  736. {
  737. if (!g_ftp_inited)
  738. return -1;
  739. char cmd_buf[128];
  740. LOG_I("Configuring FTP connection");
  741. update_state(FTP_STATE_FTP_SETUP);
  742. url_info_t info = {0};
  743. if (parse_url(qxz.Param.upgrade_url, &info) == 0)
  744. {
  745. printf("Protocol: %s(%d)\n", info.protocol, strlen(info.protocol));
  746. printf("Host: %s(%d)\n", info.host, strlen(info.host));
  747. printf("Port: %d(%d)\n", info.port, strlen(info.port));
  748. printf("User: %s(%d)\n", info.username, strlen(info.username));
  749. printf("Pass: %s(%d)\n", info.password, strlen(info.password));
  750. printf("Path: %s(%d)\n", info.path, strlen(info.path));
  751. printf("Dir: %s(%d)\n", info.dir, strlen(info.dir));
  752. printf("File: %s(%d)\n", info.filename, strlen(info.filename));
  753. }
  754. if (configure_gprs_bearer() != 0)
  755. {
  756. LOG_E("GPRS bearer configuration failed");
  757. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "configure_gprs_bearer");
  758. return -1;
  759. }
  760. safe_delay(100);
  761. if (at_send_command("AT+FTPTYPE=I", "OK", FTP_CMD_TIMEOUT) != 0)
  762. {
  763. LOG_E("Set FTPTYPE=I failed");
  764. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "FTPTYPE=I");
  765. return -1;
  766. }
  767. safe_delay(100);
  768. if (at_send_command("AT+CGATT?", "+CGATT: 1", FTP_CMD_TIMEOUT) != 0)
  769. {
  770. LOG_E("Set AT+CGATT? failed");
  771. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "AT+CGATT?");
  772. return -1;
  773. }
  774. safe_delay(100);
  775. if (at_send_command("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"", "OK", FTP_CMD_TIMEOUT) != 0)
  776. {
  777. LOG_E("Set AT+SAPBR=3,1, failed");
  778. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "AT+SAPBR=3,1,");
  779. return -1;
  780. }
  781. safe_delay(100);
  782. if (at_send_command("AT+SAPBR=3,1,\"APN\",\"\"", "OK", FTP_CMD_TIMEOUT) != 0)
  783. {
  784. LOG_E("Set AT+SAPBR=3,1,\"APN\" failed");
  785. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "AT+SAPBR=3,1,\"APN\"");
  786. return -1;
  787. }
  788. safe_delay(100);
  789. if (at_send_command("AT+SAPBR=1,1", "OK", FTP_CMD_TIMEOUT) != 0)
  790. {
  791. LOG_E("Set AT+SAPBR=1,1 failed");
  792. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "AT+SAPBR=1,1");
  793. return -1;
  794. }
  795. safe_delay(100);
  796. if (at_send_command("AT+SAPBR=2,1", "OK", FTP_CMD_TIMEOUT) != 0)
  797. {
  798. LOG_E("Set AT+SAPBR=2,1 failed");
  799. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "AT+SAPBR=2,1");
  800. return -1;
  801. }
  802. safe_delay(100);
  803. if (at_send_command("AT+FTPCID=1", "OK", FTP_CMD_TIMEOUT) != 0)
  804. {
  805. LOG_E("Set FTPCID=1 failed");
  806. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTPCID失败");
  807. return -1;
  808. }
  809. safe_delay(100);
  810. int len = 0;
  811. if (strlen(info.host) == 0 || (strstr(qxz.Param.upgrade_url, "ftp") == NULL))
  812. {
  813. len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPSERV=\"%s\"", FTP_SERVER_ADDR);
  814. }
  815. else
  816. {
  817. len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPSERV=\"%s\"", info.host);
  818. }
  819. if (len < 0 || len >= sizeof(cmd_buf))
  820. {
  821. LOG_E("Server address too long");
  822. return -1;
  823. }
  824. if (at_send_command(cmd_buf, "OK", FTP_CMD_TIMEOUT) != 0)
  825. {
  826. LOG_E("Set FTP server failed");
  827. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP服务器失败");
  828. return -1;
  829. }
  830. safe_delay(100);
  831. if (strlen(info.username) == 0 || (strstr(qxz.Param.upgrade_url, "ftp") == NULL))
  832. {
  833. len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPUN=\"%s\"", FTP_USERNAME);
  834. }
  835. else
  836. {
  837. len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPUN=\"%s\"", info.username);
  838. }
  839. if (len < 0 || len >= sizeof(cmd_buf))
  840. {
  841. LOG_E("Username too long");
  842. return -1;
  843. }
  844. if (at_send_command(cmd_buf, "OK", FTP_CMD_TIMEOUT) != 0)
  845. {
  846. LOG_E("Set FTP username failed");
  847. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP用户名失败");
  848. return -1;
  849. }
  850. safe_delay(100);
  851. if (strlen(info.password) == 0 || (strstr(qxz.Param.upgrade_url, "ftp") == NULL))
  852. {
  853. len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPPW=\"%s\"", FTP_PASSWORD);
  854. }
  855. else
  856. {
  857. len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPPW=\"%s\"", info.password);
  858. }
  859. if (len < 0 || len >= sizeof(cmd_buf))
  860. {
  861. LOG_E("Password too long");
  862. return -1;
  863. }
  864. if (at_send_command(cmd_buf, "OK", FTP_CMD_TIMEOUT) != 0)
  865. {
  866. LOG_E("Set FTP password failed");
  867. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP密码失败");
  868. return -1;
  869. }
  870. safe_delay(100);
  871. if (at_send_command("AT+FTPPORT=21", "OK", FTP_CMD_TIMEOUT) != 0)
  872. {
  873. LOG_E("Set FTP port failed");
  874. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP端口失败");
  875. return -1;
  876. }
  877. safe_delay(100);
  878. if (at_send_command("AT+FTPMODE=1", "OK", FTP_CMD_TIMEOUT) != 0)
  879. {
  880. LOG_E("Set FTP passive mode failed");
  881. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP被动模式失败");
  882. return -1;
  883. }
  884. safe_delay(100);
  885. if (strlen(info.dir) == 0 || (strstr(qxz.Param.upgrade_url, "ftp") == NULL))
  886. {
  887. len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPGETPATH=\"%s\"", FTP_FILE_PATH);
  888. }
  889. else
  890. {
  891. len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPGETPATH=\"%s\"", info.dir);
  892. }
  893. if (len < 0 || len >= sizeof(cmd_buf))
  894. {
  895. LOG_E("File path too long");
  896. return -1;
  897. }
  898. if (at_send_command(cmd_buf, "OK", FTP_CMD_TIMEOUT) != 0)
  899. {
  900. LOG_E("Set FTP path failed");
  901. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP路径失败");
  902. return -1;
  903. }
  904. safe_delay(100);
  905. if (info.filename[0] == 'q' && info.filename[1] == 'x' && info.filename[2] == 'z' && (strstr(info.filename, ".rbl") != NULL))
  906. {
  907. LOG_I("Getting remote file name == %s \n", info.filename);
  908. len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPGETNAME=\"%s\"", info.filename);
  909. }
  910. else
  911. {
  912. len = rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPGETNAME=\"%s\"", FTP_FILE_NAME);
  913. }
  914. if (len < 0 || len >= sizeof(cmd_buf))
  915. {
  916. LOG_E("File name too long");
  917. return -1;
  918. }
  919. if (at_send_command(cmd_buf, "OK", FTP_CMD_TIMEOUT) != 0)
  920. {
  921. LOG_E("Set FTP filename failed");
  922. Recode_e_code(e_fwdownload_fail, STEP_FTP_CONFIGURE, "设置FTP文件名失败");
  923. return -1;
  924. }
  925. safe_delay(100);
  926. LOG_I("FTP configuration completed successfully");
  927. return 0;
  928. }
  929. static int get_file_size(uint32_t *size)
  930. {
  931. if (!g_ftp_inited || !size)
  932. return -1;
  933. char line_buf[AT_LINE_BUF_SIZE];
  934. char *ptr;
  935. LOG_I("Getting remote file size");
  936. if (at_send_command("AT+FTPSIZE", "+FTPSIZE:", FTP_CMD_TIMEOUT) != 0)
  937. {
  938. Recode_e_code(e_fwdownload_fail, STEP_FILE_SIZE_GET, "获取文件大小命令失败");
  939. return -1;
  940. }
  941. rt_tick_t start = rt_tick_get();
  942. while ((rt_tick_get() - start) < rt_tick_from_millisecond(3000))
  943. {
  944. if (read_response_line(line_buf, sizeof(line_buf), 100) == 0)
  945. {
  946. if (strlen(line_buf) == 0)
  947. continue;
  948. LOG_D("Size response: %s", line_buf);
  949. ptr = strstr(line_buf, "+FTPSIZE:");
  950. if (ptr)
  951. {
  952. char *num_start = ptr + 9;
  953. int num1, num2, num3;
  954. if (sscanf(num_start, "%d,%d,%d", &num1, &num2, &num3) == 3)
  955. {
  956. *size = num3;
  957. LOG_I("File size: %lu bytes", *size);
  958. return 0;
  959. }
  960. else if (sscanf(num_start, "%d,%d", &num1, &num2) == 2)
  961. {
  962. *size = num2;
  963. LOG_I("File size: %lu bytes", *size);
  964. return 0;
  965. }
  966. else if (sscanf(num_start, "%d", &num1) == 1)
  967. {
  968. *size = num1;
  969. LOG_I("File size: %lu bytes", *size);
  970. return 0;
  971. }
  972. }
  973. }
  974. }
  975. LOG_E("No valid size response");
  976. Recode_e_code(e_fwdownload_fail, STEP_FILE_SIZE_GET, "无有效文件大小响应");
  977. return -1;
  978. }
  979. static int prepare_flash_storage(uint32_t file_size)
  980. {
  981. if (!g_ftp_inited)
  982. return -1;
  983. LOG_I("Preparing flash storage %d ", file_size);
  984. g_ftp.flash_part = fal_partition_find(FW_PARTITION_NAME);
  985. if (!g_ftp.flash_part)
  986. {
  987. LOG_E("Flash partition not found: %s", FW_PARTITION_NAME);
  988. Recode_e_code(e_fwdownload_fail, STEP_FLASH_PREPARE, "分区未找到");
  989. return -1;
  990. }
  991. if (g_ftp.flash_part->len < file_size)
  992. {
  993. LOG_E("Partition too small: %lu < %lu", g_ftp.flash_part->len, file_size);
  994. Recode_e_code(e_fwdownload_fail, STEP_FLASH_PREPARE, "分区太小");
  995. return -1;
  996. }
  997. if (fal_partition_erase(g_ftp.flash_part, 0, file_size) < 0)
  998. {
  999. LOG_E("Erase failed");
  1000. Recode_e_code(e_fwdownload_fail, STEP_FLASH_PREPARE, "擦除失败");
  1001. return -1;
  1002. }
  1003. LOG_I("Flash prepared");
  1004. return 0;
  1005. }
  1006. /* ====================== 下载实现 ====================== */
  1007. static int start_ftp_session(void)
  1008. {
  1009. if (!g_ftp_inited)
  1010. return -1;
  1011. char line_buf[AT_LINE_BUF_SIZE];
  1012. int retry;
  1013. LOG_I("Starting FTP session");
  1014. uart_clean();
  1015. if (at_send_command("AT+FTPGET=1", "OK", 30) != 0)
  1016. {
  1017. LOG_E("AT+FTPGET=1 command failed");
  1018. return -1;
  1019. }
  1020. for (retry = 0; retry < 30; retry++)
  1021. {
  1022. if (read_response_line(line_buf, sizeof(line_buf), 1000) == 0)
  1023. {
  1024. LOG_D("Response: %s", line_buf);
  1025. if (strstr(line_buf, "+FTPGET:1,1") || strstr(line_buf, "FTPGET: 1,1"))
  1026. {
  1027. LOG_I("FTP session established");
  1028. return 0;
  1029. }
  1030. if (strstr(line_buf, "+FTPGET:1,") || strstr(line_buf, "+FTPGET: 1,"))
  1031. {
  1032. int error_code = 0;
  1033. char *ptr;
  1034. if ((ptr = strstr(line_buf, "+FTPGET:1,")) != NULL)
  1035. {
  1036. error_code = atoi(ptr + 10);
  1037. }
  1038. else if ((ptr = strstr(line_buf, "+FTPGET: 1,")) != NULL)
  1039. {
  1040. error_code = atoi(ptr + 11);
  1041. }
  1042. if (error_code > 0)
  1043. {
  1044. LOG_E("FTP session failed: %d", error_code);
  1045. return -1;
  1046. }
  1047. }
  1048. if (strstr(line_buf, "ERROR") || strstr(line_buf, "CME ERROR"))
  1049. {
  1050. LOG_E("General error: %s", line_buf);
  1051. return -1;
  1052. }
  1053. }
  1054. if (retry % 5 == 0)
  1055. {
  1056. LOG_D("Waiting... (%d/30)", retry);
  1057. }
  1058. }
  1059. LOG_E("Timeout waiting for FTP response");
  1060. return -1;
  1061. }
  1062. /* 智能读取指定长度的数据体,避免固定超时 */
  1063. static int read_ftp_data_block(uint8_t *buf, uint32_t expected_len, uint32_t total_timeout_ms)
  1064. {
  1065. rt_tick_t start = rt_tick_get();
  1066. uint32_t total_read = 0;
  1067. uint32_t last_recv_time = rt_tick_get();
  1068. while (total_read < expected_len)
  1069. {
  1070. if ((rt_tick_get() - start) >= rt_tick_from_millisecond(total_timeout_ms))
  1071. {
  1072. LOG_E("Read block timeout");
  1073. return -1;
  1074. }
  1075. rt_size_t read_len = rt_device_read(g_ftp.uart_dev, 0, buf + total_read, expected_len - total_read);
  1076. if (read_len > 0)
  1077. {
  1078. total_read += read_len;
  1079. last_recv_time = rt_tick_get(); // 更新最后接收时间
  1080. }
  1081. else
  1082. {
  1083. // 若 2 秒无新数据,认为传输结束(防卡死)
  1084. if ((rt_tick_get() - last_recv_time) > rt_tick_from_millisecond(2000))
  1085. {
  1086. break;
  1087. }
  1088. rt_thread_mdelay(2);
  1089. }
  1090. }
  1091. return (int)total_read;
  1092. }
  1093. static int enhanced_ftp_download(void)
  1094. {
  1095. if (!g_ftp_inited)
  1096. return -1;
  1097. uint32_t offset = 0;
  1098. uint32_t request_len = 0;
  1099. uint32_t actual_len = 0;
  1100. int percent = 0;
  1101. int block_count = 0;
  1102. LOG_I("Starting enhanced FTP download");
  1103. update_state(FTP_STATE_DOWNLOADING);
  1104. /* 使用静态缓冲区,避免频繁分配 */
  1105. static uint8_t static_download_buffer[FTP_BLOCK_SIZE];
  1106. static uint8_t static_response_buffer[FTP_RESPONSE_BUFFER_SIZE];
  1107. g_ftp.download_buffer = static_download_buffer;
  1108. if (start_ftp_session() != 0)
  1109. {
  1110. LOG_E("Failed to start FTP session");
  1111. return -1;
  1112. }
  1113. LOG_I("Starting data transfer...");
  1114. LOG_I("File size: %lu bytes, will download in %lu blocks",
  1115. g_ftp.file_size, (g_ftp.file_size + FTP_BLOCK_SIZE - 1) / FTP_BLOCK_SIZE);
  1116. while (offset < g_ftp.file_size && g_ftp.is_running)
  1117. {
  1118. block_count++;
  1119. request_len = (g_ftp.file_size - offset) < FTP_BLOCK_SIZE ? (g_ftp.file_size - offset) : FTP_BLOCK_SIZE;
  1120. /* 不再清空 UART!避免丢弃已到达的数据 */
  1121. // uart_clean(); ← 已移除
  1122. /* 发送获取命令 */
  1123. char cmd_buf[32];
  1124. rt_snprintf(cmd_buf, sizeof(cmd_buf), "AT+FTPGET=2,%lu", request_len);
  1125. // LOG_D("TX: %s", cmd_buf);
  1126. rt_device_write(g_ftp.uart_dev, 0, cmd_buf, strlen(cmd_buf));
  1127. rt_device_write(g_ftp.uart_dev, 0, "\r\n", 2);
  1128. /* 动态等待数据:目标是收到完整的 "+FTPGET:2,<len>\r\n<data>" */
  1129. uint32_t total_received = 0;
  1130. uint32_t start_tick = rt_tick_get();
  1131. uint32_t timeout_ticks = rt_tick_from_millisecond(3000); // 3秒超时
  1132. /* 先确保收到至少能解析 header 的字节数 */
  1133. while (total_received < 64)
  1134. {
  1135. if ((rt_tick_get() - start_tick) >= timeout_ticks)
  1136. {
  1137. LOG_E("Timeout waiting for FTP response header");
  1138. Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "等待响应头超时");
  1139. return -1;
  1140. }
  1141. rt_size_t read_len = rt_device_read(g_ftp.uart_dev, 0,
  1142. static_response_buffer + total_received,
  1143. sizeof(static_response_buffer) - total_received);
  1144. if (read_len > 0)
  1145. {
  1146. total_received += read_len;
  1147. }
  1148. else
  1149. {
  1150. rt_thread_mdelay(5); // 避免忙等
  1151. }
  1152. }
  1153. /* 尝试解析响应头 */
  1154. uint32_t data_offset = 0;
  1155. if (parse_ftpget_response(static_response_buffer, total_received, &actual_len, &data_offset) != 0)
  1156. {
  1157. LOG_E("Failed to parse FTPGET response after receiving %lu bytes", total_received);
  1158. Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "解析FTP响应失败");
  1159. return -1;
  1160. }
  1161. if (actual_len == 0 || actual_len > FTP_BLOCK_SIZE)
  1162. {
  1163. LOG_E("Invalid data length: %lu", actual_len);
  1164. Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "无效数据长度");
  1165. return -1;
  1166. }
  1167. /* 如果数据尚未收全,继续读取剩余部分 */
  1168. uint32_t expected_total = data_offset + actual_len;
  1169. while (total_received < expected_total && total_received < sizeof(static_response_buffer))
  1170. {
  1171. if ((rt_tick_get() - start_tick) >= timeout_ticks)
  1172. {
  1173. LOG_E("Timeout waiting for full data block (got %lu/%lu)",
  1174. total_received, expected_total);
  1175. Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "数据块接收超时");
  1176. return -1;
  1177. }
  1178. rt_size_t read_len = rt_device_read(g_ftp.uart_dev, 0,
  1179. static_response_buffer + total_received,
  1180. sizeof(static_response_buffer) - total_received);
  1181. if (read_len > 0)
  1182. {
  1183. total_received += read_len;
  1184. }
  1185. else
  1186. {
  1187. rt_thread_mdelay(2);
  1188. }
  1189. }
  1190. /* 检查是否收全 */
  1191. if (total_received < expected_total)
  1192. {
  1193. LOG_E("Incomplete data: expected %lu, got %lu", expected_total, total_received);
  1194. Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "数据不完整");
  1195. return -1;
  1196. }
  1197. /* 提取有效数据 */
  1198. if (data_offset + actual_len > total_received)
  1199. {
  1200. LOG_E("Data offset out of bounds");
  1201. return -1;
  1202. }
  1203. memcpy(g_ftp.download_buffer, static_response_buffer + data_offset, actual_len);
  1204. /* 写入 Flash */
  1205. if (fal_partition_write(g_ftp.flash_part, offset, g_ftp.download_buffer, actual_len) < 0)
  1206. {
  1207. LOG_E("Flash write failed at offset %lu", offset);
  1208. Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "写入Flash失败");
  1209. return -1;
  1210. }
  1211. // rt_kprintf("\n FW content IS Form 0x%X SIZE 0x%0X \n", offset, actual_len);
  1212. // for (int a = 0; a < actual_len; a++)
  1213. // {
  1214. // rt_kprintf("%02X ", g_ftp.download_buffer[a]);
  1215. // if ((a + 1) % 16 == 0)
  1216. // rt_kprintf("\n");
  1217. // }
  1218. firmware_crc_update(&g_fw_crc_ctx, g_ftp.download_buffer, actual_len);
  1219. offset += actual_len;
  1220. g_ftp.downloaded = offset;
  1221. /* 更新进度 */
  1222. int new_percent = (offset * 100) / g_ftp.file_size;
  1223. if (new_percent != percent)
  1224. {
  1225. percent = new_percent;
  1226. update_progress(percent);
  1227. }
  1228. print_download_status(offset, g_ftp.file_size, block_count);
  1229. if (actual_len < request_len)
  1230. {
  1231. LOG_I("Last block received (size: %lu)", actual_len);
  1232. break;
  1233. }
  1234. /* 让出 CPU,但不再固定延时 */
  1235. if (block_count % 20 == 0)
  1236. {
  1237. rt_thread_yield();
  1238. }
  1239. }
  1240. if (offset >= g_ftp.file_size)
  1241. {
  1242. LOG_I("Download completed: %lu bytes in %d blocks", offset, block_count);
  1243. update_progress(100);
  1244. return 0;
  1245. }
  1246. else if (!g_ftp.is_running)
  1247. {
  1248. LOG_I("Download stopped by user");
  1249. return -1;
  1250. }
  1251. else
  1252. {
  1253. LOG_E("Download incomplete: %lu/%lu", offset, g_ftp.file_size);
  1254. Recode_e_code(e_fwdownload_fail, STEP_DOWNLOAD_PROGRESS, "下载不完整");
  1255. return -1;
  1256. }
  1257. }
  1258. // 在 ftp_app.c 中添加以下函数(建议放在 enhanced_ftp_download 函数之后)
  1259. // 专用于验证的 CRC 函数(带独立计数器)
  1260. static void firmware_crc_verify(firmware_crc_ctx_t *ctx, const uint8_t *data, size_t len)
  1261. {
  1262. // ? 标准 CRC-32/IEEE 的 bit-reflected 多项式
  1263. const uint32_t POLY = 0xEDB88320U;
  1264. uint32_t crc = ctx->crc;
  1265. for (size_t i = 0; i < len; i++)
  1266. {
  1267. crc ^= data[i]; // 输入字节直接异或(REFIN=true 由右移实现)
  1268. for (int j = 0; j < 8; j++)
  1269. {
  1270. if (crc & 1)
  1271. {
  1272. crc = (crc >> 1) ^ POLY;
  1273. }
  1274. else
  1275. {
  1276. crc >>= 1;
  1277. }
  1278. }
  1279. }
  1280. ctx->crc = crc;
  1281. static int verify_cnt = 1; // 独立计数器
  1282. uint32_t final_crc = crc ^ 0xFFFFFFFF;
  1283. rt_kprintf("Verify Packet %d CRC: %08X\n", verify_cnt, final_crc);
  1284. verify_cnt++;
  1285. }
  1286. static int8_t verify_firmware_in_flash(void)
  1287. {
  1288. const uint32_t BLOCK_SIZE = 1024;
  1289. uint8_t *verify_buffer = rt_malloc(BLOCK_SIZE);
  1290. if (!verify_buffer)
  1291. {
  1292. LOG_E("Failed to allocate verify buffer");
  1293. return -1;
  1294. }
  1295. firmware_crc_ctx_t verify_ctx = {.crc = 0xFFFFFFFF};
  1296. uint32_t offset = 0;
  1297. uint32_t total_verified = 0; // ← 新增
  1298. LOG_I("Starting firmware verification from flash...");
  1299. while (total_verified < g_ftp.file_size)
  1300. { // ← 改为基于已验证字节数
  1301. uint32_t remaining = g_ftp.file_size - total_verified;
  1302. uint32_t read_len = (remaining < BLOCK_SIZE) ? remaining : BLOCK_SIZE;
  1303. if (fal_partition_read(g_ftp.flash_part, offset, verify_buffer, read_len) != read_len)
  1304. {
  1305. LOG_E("Flash read failed at offset %lu", offset);
  1306. rt_free(verify_buffer);
  1307. return -1;
  1308. }
  1309. firmware_crc_verify(&verify_ctx, verify_buffer, read_len);
  1310. offset += read_len;
  1311. total_verified += read_len; // ← 明确累加
  1312. }
  1313. uint32_t verified_crc = verify_ctx.crc ^ 0xFFFFFFFF;
  1314. rt_kprintf("Verification completed. Final CRC from flash: %08X\n", verified_crc);
  1315. rt_free(verify_buffer);
  1316. uint32_t original_crc = g_fw_crc_ctx.crc ^ 0xFFFFFFFF; // ← 直接计算,避免宏问题
  1317. if (verified_crc == original_crc)
  1318. {
  1319. LOG_I("? Firmware verification PASSED!");
  1320. return 1;
  1321. }
  1322. else
  1323. {
  1324. LOG_E("? Firmware verification FAILED! expected %08X, got %08X", original_crc, verified_crc);
  1325. return 0;
  1326. }
  1327. }
  1328. /* ====================== 下载线程 ====================== */
  1329. extern void RESET_SYSTEM(void);
  1330. static void download_thread_entry(void *arg)
  1331. {
  1332. /* 关键防护:再次确认已初始化 */
  1333. if (!g_ftp_inited)
  1334. {
  1335. LOG_E("FTP app not initialized! Thread abort.");
  1336. return;
  1337. }
  1338. int result = -1;
  1339. LOG_I("FTP download thread started");
  1340. rt_mutex_take(&g_ftp.mutex, RT_WAITING_FOREVER);
  1341. g_ftp.is_running = RT_TRUE;
  1342. rt_mutex_release(&g_ftp.mutex);
  1343. /* 添加线程延时,避免立即开始占用资源 */
  1344. rt_thread_mdelay(100);
  1345. LOG_I("Step 1: Wait for system init (%d seconds)", SYS_INIT_WAIT);
  1346. update_state(FTP_STATE_INIT_WAIT);
  1347. for (int i = SYS_INIT_WAIT; i > 0; i--)
  1348. {
  1349. if (!g_ftp.is_running)
  1350. {
  1351. LOG_I("Download stopped during init wait");
  1352. goto thread_exit;
  1353. }
  1354. LOG_D("Init wait: %d", i);
  1355. safe_delay(1000);
  1356. }
  1357. if (!g_ftp.is_running)
  1358. goto thread_exit;
  1359. if (module_power_cycle() != 0)
  1360. goto exit_with_error;
  1361. if (!g_ftp.is_running)
  1362. goto thread_exit;
  1363. if (uart_init() != 0)
  1364. goto exit_with_error;
  1365. if (!g_ftp.is_running)
  1366. goto thread_exit;
  1367. if (check_module_ready() != 0)
  1368. goto exit_with_error;
  1369. if (!g_ftp.is_running)
  1370. goto thread_exit;
  1371. if (check_network() != 0)
  1372. goto exit_with_error;
  1373. if (!g_ftp.is_running)
  1374. goto thread_exit;
  1375. if (configure_ftp() != 0)
  1376. goto exit_with_error;
  1377. if (!g_ftp.is_running)
  1378. goto thread_exit;
  1379. if (get_file_size(&g_ftp.file_size) != 0)
  1380. goto exit_with_error;
  1381. if (!g_ftp.is_running)
  1382. goto thread_exit;
  1383. if (g_ftp.file_size < 1024 || g_ftp.file_size > 10 * 1024 * 1024) /* 限制文件大小 */
  1384. {
  1385. LOG_E("Invalid file size: %lu", g_ftp.file_size);
  1386. goto exit_with_error;
  1387. }
  1388. if (!g_ftp.is_running)
  1389. goto thread_exit;
  1390. if (prepare_flash_storage(g_ftp.file_size) != 0)
  1391. goto exit_with_error;
  1392. url_info_t info = {0};
  1393. if (parse_url(qxz.Param.upgrade_url, &info) == 0)
  1394. {
  1395. // printf("Protocol: %s(%d)\n", info.protocol, strlen(info.protocol));
  1396. // printf("Host: %s(%d)\n", info.host, strlen(info.host));
  1397. // printf("Port: %d(%d)\n", info.port, strlen(info.port));
  1398. // printf("User: %s(%d)\n", info.username, strlen(info.username));
  1399. // printf("Pass: %s(%d)\n", info.password, strlen(info.password));
  1400. // printf("Path: %s(%d)\n", info.path, strlen(info.path));
  1401. // printf("Dir: %s(%d)\n", info.dir, strlen(info.dir));
  1402. // printf("File: %s(%d)\n", info.filename, strlen(info.filename));
  1403. }
  1404. char aaa[64] = {0};
  1405. sprintf(aaa, "固件下载开始 %s=(%d)bytes", info.filename, g_ftp.file_size);
  1406. Recode_e_code(downloade_fw_succ_ec, STEP_DOWNLOAD_COMPLETE, aaa);
  1407. if (!g_ftp.is_running)
  1408. goto thread_exit;
  1409. if (enhanced_ftp_download() != 0)
  1410. goto exit_with_error;
  1411. LOG_I("Download completed. File size: %lu", g_ftp.file_size);
  1412. update_state(FTP_STATE_COMPLETED);
  1413. uint32_t final_crc = FIRMWARE_CRC_FINAL(&g_fw_crc_ctx);
  1414. rt_kprintf("final_crc %08X \n", final_crc);
  1415. if (verify_firmware_in_flash())
  1416. {
  1417. sprintf(aaa, "固件读出校验成功 %08X", final_crc);
  1418. Recode_e_code(downloade_fw_succ_ec, STEP_DOWNLOAD_COMPLETE, aaa);
  1419. }
  1420. else
  1421. {
  1422. sprintf(aaa, "固件读出校验失败 %08X", final_crc);
  1423. Recode_e_code(downloade_fw_succ_ec, 77, aaa);
  1424. }
  1425. result = 0;
  1426. goto cleanup;
  1427. exit_with_error:
  1428. LOG_E("Download process failed");
  1429. update_state(FTP_STATE_FAILED);
  1430. result = -1;
  1431. cleanup:
  1432. LOG_I("Closing FTP session");
  1433. at_send_command("AT+FTPQUIT", "OK", 5);
  1434. if (g_ftp.uart_dev)
  1435. {
  1436. rt_device_close(g_ftp.uart_dev);
  1437. g_ftp.uart_dev = RT_NULL;
  1438. }
  1439. thread_exit:
  1440. RESET_SYSTEM();
  1441. rt_mutex_take(&g_ftp.mutex, RT_WAITING_FOREVER);
  1442. g_ftp.is_running = RT_FALSE;
  1443. rt_mutex_release(&g_ftp.mutex);
  1444. LOG_I("Download thread exited, result: %s", result == 0 ? "SUCCESS" : "FAILED");
  1445. }
  1446. /* ====================== 公共API ====================== */
  1447. int ftp_app_init(void)
  1448. {
  1449. if (g_ftp_inited)
  1450. {
  1451. LOG_W("FTP app already initialized");
  1452. return 0;
  1453. }
  1454. LOG_I("Initializing FTP application");
  1455. memset(&g_ftp, 0, sizeof(g_ftp));
  1456. g_ftp.state = FTP_STATE_IDLE;
  1457. g_ftp.progress = 0;
  1458. g_ftp.is_running = RT_FALSE;
  1459. g_ftp.thread = RT_NULL;
  1460. g_ftp.uart_dev = RT_NULL;
  1461. g_ftp.flash_part = RT_NULL;
  1462. g_ftp.download_buffer = NULL;
  1463. if (rt_mutex_init(&g_ftp.mutex, "ftp_mutex", RT_IPC_FLAG_FIFO) != RT_EOK)
  1464. {
  1465. LOG_E("Mutex init failed");
  1466. return -1;
  1467. }
  1468. // if (power_init() != 0)
  1469. // {
  1470. // LOG_E("Power init failed");
  1471. // rt_mutex_detach(&g_ftp.mutex);
  1472. // return -1;
  1473. // }
  1474. g_ftp_inited = RT_TRUE;
  1475. LOG_I("FTP application initialized");
  1476. return 0;
  1477. }
  1478. int ftp_start_download(void)
  1479. {
  1480. ftp_app_init();
  1481. if (!g_ftp_inited)
  1482. {
  1483. LOG_E("FTP app not initialized! Call ftp_app_init() first.");
  1484. return -1;
  1485. }
  1486. rt_base_t level = rt_hw_interrupt_disable();
  1487. rt_bool_t running;
  1488. rt_mutex_take(&g_ftp.mutex, RT_WAITING_FOREVER);
  1489. running = g_ftp.is_running;
  1490. rt_mutex_release(&g_ftp.mutex);
  1491. rt_hw_interrupt_enable(level);
  1492. if (running)
  1493. {
  1494. LOG_W("Download already running");
  1495. return -1;
  1496. }
  1497. LOG_I("Starting FTP download");
  1498. g_ftp.thread = rt_thread_create("ftp_dl",
  1499. download_thread_entry,
  1500. RT_NULL,
  1501. 4096,
  1502. 10,
  1503. 10);
  1504. if (g_ftp.thread == RT_NULL)
  1505. {
  1506. LOG_E("Thread create failed");
  1507. return -1;
  1508. }
  1509. if (rt_thread_startup(g_ftp.thread) != RT_EOK)
  1510. {
  1511. LOG_E("Thread startup failed");
  1512. rt_thread_delete(g_ftp.thread);
  1513. g_ftp.thread = RT_NULL;
  1514. return -1;
  1515. }
  1516. return 0;
  1517. }
  1518. int ftp_stop_download(void)
  1519. {
  1520. if (!g_ftp_inited)
  1521. {
  1522. LOG_W("FTP app not initialized");
  1523. return -1;
  1524. }
  1525. rt_base_t level = rt_hw_interrupt_disable();
  1526. rt_bool_t running;
  1527. rt_mutex_take(&g_ftp.mutex, RT_WAITING_FOREVER);
  1528. running = g_ftp.is_running;
  1529. if (running)
  1530. {
  1531. g_ftp.is_running = RT_FALSE;
  1532. }
  1533. rt_mutex_release(&g_ftp.mutex);
  1534. rt_hw_interrupt_enable(level);
  1535. if (!running)
  1536. {
  1537. LOG_W("No download running");
  1538. return -1;
  1539. }
  1540. LOG_I("Stopping FTP download");
  1541. if (g_ftp.thread)
  1542. {
  1543. /* 等待线程结束 */
  1544. for (int i = 0; i < 20; i++) /* 最多等待2秒 */
  1545. {
  1546. rt_mutex_take(&g_ftp.mutex, RT_WAITING_FOREVER);
  1547. if (!g_ftp.is_running)
  1548. {
  1549. rt_mutex_release(&g_ftp.mutex);
  1550. break;
  1551. }
  1552. rt_mutex_release(&g_ftp.mutex);
  1553. rt_thread_mdelay(100);
  1554. }
  1555. g_ftp.thread = RT_NULL;
  1556. }
  1557. update_state(FTP_STATE_STOPPED);
  1558. return 0;
  1559. }
  1560. ftp_state_t ftp_get_state(void)
  1561. {
  1562. if (!g_ftp_inited)
  1563. return FTP_STATE_IDLE;
  1564. return g_ftp.state;
  1565. }
  1566. int ftp_get_progress(void)
  1567. {
  1568. if (!g_ftp_inited)
  1569. return 0;
  1570. return g_ftp.progress;
  1571. }
  1572. /* ====================== 自动初始化 ====================== */
  1573. /* ====================== MSH 命令 ====================== */
  1574. #ifdef RT_USING_FINSH
  1575. #include <shell.h>
  1576. static int cmd_ftp_start(int argc, char **argv)
  1577. {
  1578. rt_kprintf("[FTP] Starting firmware download...\n");
  1579. if (ftp_start_download() == 0)
  1580. {
  1581. rt_kprintf("[FTP] Download started successfully.\n");
  1582. }
  1583. else
  1584. {
  1585. rt_kprintf("[FTP] Failed to start download!\n");
  1586. }
  1587. return 0;
  1588. }
  1589. static int cmd_ftp_stop(int argc, char **argv)
  1590. {
  1591. rt_kprintf("[FTP] Stopping firmware download...\n");
  1592. if (ftp_stop_download() == 0)
  1593. {
  1594. rt_kprintf("[FTP] Download stopped.\n");
  1595. }
  1596. else
  1597. {
  1598. rt_kprintf("[FTP] No active download to stop.\n");
  1599. }
  1600. return 0;
  1601. }
  1602. static int cmd_ftp_status(int argc, char **argv)
  1603. {
  1604. ftp_state_t state = ftp_get_state();
  1605. int progress = ftp_get_progress();
  1606. rt_kprintf("[FTP] Status: ");
  1607. switch (state)
  1608. {
  1609. case FTP_STATE_IDLE:
  1610. rt_kprintf("IDLE");
  1611. break;
  1612. case FTP_STATE_INIT_WAIT:
  1613. rt_kprintf("INIT_WAIT");
  1614. break;
  1615. case FTP_STATE_MODULE_BOOT:
  1616. rt_kprintf("MODULE_BOOT");
  1617. break;
  1618. case FTP_STATE_NETWORK_WAIT:
  1619. rt_kprintf("NETWORK_WAIT");
  1620. break;
  1621. case FTP_STATE_FTP_SETUP:
  1622. rt_kprintf("FTP_SETUP");
  1623. break;
  1624. case FTP_STATE_DOWNLOADING:
  1625. rt_kprintf("DOWNLOADING");
  1626. break;
  1627. case FTP_STATE_COMPLETED:
  1628. rt_kprintf("COMPLETED");
  1629. break;
  1630. case FTP_STATE_FAILED:
  1631. rt_kprintf("FAILED");
  1632. break;
  1633. case FTP_STATE_STOPPED:
  1634. rt_kprintf("STOPPED");
  1635. break;
  1636. default:
  1637. rt_kprintf("UNKNOWN");
  1638. break;
  1639. }
  1640. rt_kprintf("\n[FTP] Progress: %d%%\n", progress);
  1641. /* 显示下载统计信息 */
  1642. if (g_ftp_inited && g_ftp.file_size > 0)
  1643. {
  1644. rt_kprintf("[FTP] File size: %lu bytes\n", g_ftp.file_size);
  1645. rt_kprintf("[FTP] Downloaded: %lu bytes\n", g_ftp.downloaded);
  1646. if (state == FTP_STATE_DOWNLOADING && g_ftp.downloaded > 0)
  1647. {
  1648. uint32_t remaining = g_ftp.file_size - g_ftp.downloaded;
  1649. rt_kprintf("[FTP] Remaining: %lu bytes\n", remaining);
  1650. if (g_ftp.downloaded > 0)
  1651. {
  1652. /* 估算剩余时间(假设平均下载速度) */
  1653. static rt_tick_t start_time = 0;
  1654. static uint32_t last_downloaded = 0;
  1655. if (start_time == 0)
  1656. {
  1657. start_time = rt_tick_get();
  1658. last_downloaded = g_ftp.downloaded;
  1659. }
  1660. else if (g_ftp.downloaded > last_downloaded + 10240) /* 每下载10KB更新一次 */
  1661. {
  1662. rt_tick_t elapsed = rt_tick_get() - start_time;
  1663. uint32_t downloaded_since = g_ftp.downloaded - last_downloaded;
  1664. if (elapsed > 0 && downloaded_since > 0)
  1665. {
  1666. uint32_t bytes_per_tick = (downloaded_since * RT_TICK_PER_SECOND) / elapsed;
  1667. if (bytes_per_tick > 0)
  1668. {
  1669. uint32_t remaining_seconds = remaining / bytes_per_tick;
  1670. rt_kprintf("[FTP] Estimated time remaining: %lu seconds\n", remaining_seconds);
  1671. }
  1672. }
  1673. last_downloaded = g_ftp.downloaded;
  1674. }
  1675. }
  1676. }
  1677. }
  1678. return 0;
  1679. }
  1680. // MSH_CMD_EXPORT(cmd_ftp_start, "Start FTP firmware download");
  1681. #endif /* RT_USING_FINSH */