bsp_csv.c 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2025-11-20 RuoFeng the first version
  9. */
  10. /**
  11. * BSP CSV文件操作模块实现
  12. * 优化版:简化操作,提升稳定性,减少Flash占用
  13. */
  14. /*********************↓ define ↓************************/
  15. #define CSV_DISK CH376_MODE_SD_CARD
  16. // #define CSV_DISK CH376_MODE_USB_DISK
  17. /*********************↑ define ↑************************/
  18. /**
  19. *
  20. *
  21. *
  22. *
  23. * */
  24. /*********************↓ include ↓************************/
  25. #include <CH376/bsp/bsp_csv.h>
  26. #include <stdarg.h>
  27. /*********************↑ include ↑************************/
  28. /**
  29. *
  30. *
  31. *
  32. *
  33. * */
  34. /*********************↓ extern ↓************************/
  35. extern uint32_t month;
  36. extern uint32_t day;
  37. extern uint32_t year;
  38. extern uint32_t hour;
  39. extern uint32_t min;
  40. extern uint32_t sec;
  41. extern uint8_t week;
  42. /*********************↑ extern ↑************************/
  43. /**
  44. *
  45. *
  46. *
  47. *
  48. * */
  49. /********************↓ declaration ↓***********************/
  50. static csv_result_t csv_init(ch376_mode_t mode);
  51. static csv_result_t csv_deinit(void);
  52. static csv_result_t csv_create(const char *filename, const char *header);
  53. static csv_result_t csv_open(const char *filename, csv_mode_t mode, const char *header);
  54. static csv_result_t csv_append(const char *format, ...);
  55. static csv_result_t csv_close(void);
  56. static uint32_t csv_get_line_count(void);
  57. static uint32_t csv_count_file_lines(const char *filename);
  58. static uint8_t csv_is_opened(void);
  59. static const char *csv_get_filename(void);
  60. /********************↑ declaration ↑***********************/
  61. /**
  62. *
  63. *
  64. *
  65. *
  66. * */
  67. /*********************↓ global variables ↓************************/
  68. /* 模块内部状态 */
  69. static struct
  70. {
  71. uint8_t file_opened;
  72. uint8_t device_ready;
  73. char current_file[13];
  74. uint32_t line_count;
  75. uint32_t file_size;
  76. } csv_state = {0};
  77. /* 全局操作接口 */
  78. csv_ops_t csv =
  79. {
  80. .init = csv_init,
  81. .deinit = csv_deinit,
  82. .create = csv_create,
  83. .open = csv_open,
  84. .append = csv_append,
  85. .close = csv_close,
  86. .get_line_count = csv_get_line_count,
  87. .count_file_lines = csv_count_file_lines,
  88. .is_opened = csv_is_opened,
  89. .get_filename = csv_get_filename};
  90. static volatile uint8_t busy_flg = 0; // 忙标记
  91. /*********************↑ global variables ↑************************/
  92. /**
  93. *
  94. *
  95. *
  96. *
  97. * */
  98. /* 简化文件名转换 */
  99. static void make_safe_filename(const char *input, char *output)
  100. {
  101. if (!input || strlen(input) == 0)
  102. {
  103. strcpy(output, "/DATA.CSV");
  104. return;
  105. }
  106. if (input[0] == '/')
  107. {
  108. strncpy(output, input, 12);
  109. }
  110. else
  111. {
  112. snprintf(output, 13, "/%s", input);
  113. }
  114. output[12] = '\0';
  115. }
  116. /* 设备初始化 - 简化版 */
  117. static csv_result_t csv_init(ch376_mode_t mode)
  118. {
  119. char busy_check = 0;
  120. static char busy_cnt = 0;
  121. if (busy_cnt >= 3)
  122. {
  123. busy_cnt = 0;
  124. busy_flg = 0;
  125. }
  126. if (busy_flg == 0x9D)
  127. {
  128. busy_check = 1;
  129. for (char a = 0; a < 3; a++)
  130. {
  131. rt_kprintf("CSV BUSY waiting now %d.\n", a);
  132. rt_thread_mdelay(1000);
  133. if (busy_flg != 0x9D)
  134. {
  135. rt_kprintf("CSV Free now.\n");
  136. busy_check = 0;
  137. break;
  138. }
  139. }
  140. if (busy_check)
  141. {
  142. return CSV_DEVICE_NOT_READY;
  143. }
  144. }
  145. if (csv_state.device_ready)
  146. {
  147. busy_flg = 0x9D;
  148. return CSV_SUCCESS;
  149. }
  150. ch376_result_t result = ch376.init();
  151. if (result != CH376_RESULT_SUCCESS)
  152. {
  153. // 简单重试机制
  154. rt_thread_mdelay(100);
  155. result = ch376.init();
  156. if (result != CH376_RESULT_SUCCESS)
  157. {
  158. return CSV_DEVICE_NOT_READY;
  159. }
  160. }
  161. result = ch376.switch_mode(mode);
  162. if (result != CH376_RESULT_SUCCESS)
  163. {
  164. ch376.deinit();
  165. return CSV_DEVICE_NOT_READY;
  166. }
  167. csv_state.device_ready = 1;
  168. busy_flg = 0x9D;
  169. return CSV_SUCCESS;
  170. }
  171. /* 设备反初始化 */
  172. static csv_result_t csv_deinit(void)
  173. {
  174. if (csv_state.file_opened)
  175. {
  176. csv.close();
  177. }
  178. ch376.deinit();
  179. csv_state.device_ready = 0;
  180. memset(&csv_state, 0, sizeof(csv_state));
  181. busy_flg = 0;
  182. return CSV_SUCCESS;
  183. }
  184. /* 创建CSV文件 - 简化版 */
  185. static csv_result_t csv_create(const char *filename, const char *header)
  186. {
  187. if (!filename)
  188. {
  189. return CSV_ERROR;
  190. }
  191. // 确保设备就绪
  192. if (!csv_state.device_ready)
  193. {
  194. if (csv_init(CSV_DISK) != CSV_SUCCESS)
  195. {
  196. return CSV_DEVICE_NOT_READY;
  197. }
  198. }
  199. // 关闭已打开的文件
  200. if (csv_state.file_opened)
  201. {
  202. ch376.file_close();
  203. csv_state.file_opened = 0;
  204. }
  205. // 生成安全文件名
  206. char safe_name[13];
  207. make_safe_filename(filename, safe_name);
  208. // rt_kprintf("[CSV] Creating file: %s\n", safe_name);
  209. // 创建文件
  210. ch376_result_t result = ch376.file_create(safe_name);
  211. if (result != CH376_RESULT_SUCCESS)
  212. {
  213. rt_kprintf("[CSV] File creation failed: %d\n", result);
  214. return CSV_ERROR;
  215. }
  216. else
  217. {
  218. csv_bitmap_mark_exist(year - 2000, month, day);
  219. }
  220. // 写入表头(如果有)
  221. if (header && strlen(header) > 0)
  222. {
  223. char header_line[64]; // 减小缓冲区大小
  224. int len = snprintf(header_line, sizeof(header_line), "%s\n", header);
  225. result = ch376.file_write(header_line, len);
  226. if (result != CH376_RESULT_SUCCESS)
  227. {
  228. rt_kprintf("[CSV] Header write failed: %d\n", result);
  229. ch376.file_close();
  230. return CSV_ERROR;
  231. }
  232. csv_state.line_count = 1;
  233. csv_state.file_size = len;
  234. }
  235. else
  236. {
  237. csv_state.line_count = 0;
  238. csv_state.file_size = 0;
  239. }
  240. // 更新状态
  241. csv_state.file_opened = 1;
  242. strncpy(csv_state.current_file, safe_name, sizeof(csv_state.current_file) - 1);
  243. rt_kprintf("[CSV] File created successfully: %s\n", safe_name);
  244. return CSV_SUCCESS;
  245. }
  246. /* 统计文件行数 - 修复版:区分表头行和数据行 */
  247. static uint32_t csv_count_file_lines(const char *filename)
  248. {
  249. if (!filename)
  250. {
  251. return 0;
  252. }
  253. // 确保设备就绪
  254. if (!csv_state.device_ready)
  255. {
  256. if (csv_init(CSV_DISK) != CSV_SUCCESS)
  257. {
  258. return 0;
  259. }
  260. }
  261. char safe_name[13];
  262. make_safe_filename(filename, safe_name);
  263. // 检查文件是否存在
  264. if (ch376.file_exists(safe_name) != CH376_RESULT_SUCCESS)
  265. {
  266. return 0;
  267. }
  268. ch376_result_t result = ch376.file_open(safe_name);
  269. if (result != CH376_RESULT_SUCCESS)
  270. {
  271. return 0;
  272. }
  273. uint32_t line_count = 0;
  274. uint8_t buffer[256];
  275. uint32_t read_size;
  276. uint32_t bytes_read = 0;
  277. uint8_t has_header = 0;
  278. while (bytes_read < 1024 * 1024) // 限制读取大小 为1M
  279. {
  280. result = ch376.file_read(buffer, sizeof(buffer), &read_size);
  281. if (result != CH376_RESULT_SUCCESS || read_size == 0)
  282. {
  283. break;
  284. }
  285. bytes_read += read_size;
  286. for (uint32_t i = 0; i < read_size; i++)
  287. {
  288. if (buffer[i] == '\n')
  289. {
  290. line_count++;
  291. }
  292. }
  293. }
  294. ch376.file_close();
  295. // 修复:如果文件有内容但行数为0,返回1(至少有一行数据)
  296. if (line_count == 0 && bytes_read > 0)
  297. {
  298. line_count = 1;
  299. }
  300. // rt_kprintf("[CSV] File statistics: %s -> %lu lines (%lu bytes)\n",
  301. // safe_name, line_count, bytes_read);
  302. return line_count;
  303. }
  304. /* 打开CSV文件 - 完全修复追加模式 */
  305. static csv_result_t csv_open(const char *filename, csv_mode_t mode, const char *header)
  306. {
  307. if (!filename)
  308. {
  309. return CSV_ERROR;
  310. }
  311. // 检查是否已有文件打开
  312. if (csv_state.file_opened)
  313. {
  314. rt_kprintf("[CSV] Error: File already open\n");
  315. return CSV_FILE_ALREADY_OPEN;
  316. }
  317. // 确保设备就绪
  318. if (!csv_state.device_ready)
  319. {
  320. if (csv_init(CSV_DISK) != CSV_SUCCESS)
  321. {
  322. return CSV_DEVICE_NOT_READY;
  323. }
  324. }
  325. char safe_name[13];
  326. make_safe_filename(filename, safe_name);
  327. ch376_result_t result;
  328. uint32_t existing_lines = 0;
  329. switch (mode)
  330. {
  331. case CSV_MODE_READ:
  332. // 只读模式
  333. result = ch376.file_open(safe_name);
  334. if (result != CH376_RESULT_SUCCESS)
  335. {
  336. return CSV_FILE_NOT_FOUND;
  337. }
  338. existing_lines = csv_count_file_lines(filename);
  339. break;
  340. case CSV_MODE_APPEND:
  341. // 关键修复:避免重复打开文件
  342. // 先检查文件是否存在,但不重复打开
  343. result = ch376.file_exists(safe_name);
  344. if (result == CH376_RESULT_SUCCESS)
  345. {
  346. // 文件存在,获取行数但不重复打开
  347. existing_lines = csv_count_file_lines(filename);
  348. // 现在打开文件用于追加
  349. result = ch376.file_open(safe_name);
  350. if (result == CH376_RESULT_SUCCESS)
  351. {
  352. csv_bitmap_mark_exist(year - 2000, month, day);
  353. uint32_t file_size = CH376GetFileSize();
  354. // rt_kprintf("[CSV] Append mode:(%s) File size %ld bytes, existing %lu lines\n", filename,file_size, existing_lines);
  355. // 定位到文件末尾
  356. if (ch376.file_seek(file_size) == CH376_RESULT_SUCCESS)
  357. {
  358. // rt_kprintf("[CSV] Successfully positioned to end of file\n");
  359. }
  360. else
  361. {
  362. rt_kprintf("[CSV] Failed to position to end of file\n");
  363. ch376.file_close();
  364. return CSV_ERROR;
  365. }
  366. }
  367. else
  368. {
  369. rt_kprintf("[CSV] File open failed: %d\n", result);
  370. return CSV_ERROR;
  371. }
  372. }
  373. else if (result == CH376_RESULT_FILE_NOT_FOUND)
  374. {
  375. // 文件不存在,创建新文件
  376. result = ch376.file_create(safe_name);
  377. if (result != CH376_RESULT_SUCCESS)
  378. {
  379. return CSV_ERROR;
  380. }
  381. // 写入表头(如果有)
  382. if (header && strlen(header) > 0)
  383. {
  384. if (strstr(header, "\n") == NULL)
  385. {
  386. char header_line[128];
  387. int len = snprintf(header_line, sizeof(header_line), "%s\n", header);
  388. result = ch376.file_write(header_line, len);
  389. }
  390. else
  391. {
  392. result = ch376.file_write(header, strlen(header));
  393. }
  394. if (result != CH376_RESULT_SUCCESS)
  395. {
  396. ch376.file_close();
  397. return CSV_ERROR;
  398. }
  399. existing_lines = 1;
  400. }
  401. }
  402. else
  403. {
  404. return CSV_ERROR;
  405. }
  406. break;
  407. case CSV_MODE_OVERWRITE:
  408. // 覆盖模式
  409. return csv_create(filename, header);
  410. default:
  411. return CSV_ERROR;
  412. }
  413. // 更新状态
  414. csv_state.file_opened = 1;
  415. csv_state.line_count = existing_lines;
  416. strncpy(csv_state.current_file, safe_name, sizeof(csv_state.current_file) - 1);
  417. // rt_kprintf("[CSV] File opened successfully: %s, mode: %d\n", safe_name, mode);
  418. return CSV_SUCCESS;
  419. }
  420. /* 追加数据 - 优化版 */
  421. static csv_result_t csv_append(const char *format, ...)
  422. {
  423. if (!csv_state.file_opened)
  424. {
  425. return CSV_ERROR;
  426. }
  427. if (!format)
  428. {
  429. return CSV_ERROR;
  430. }
  431. // 简化格式化,使用固定大小缓冲区
  432. char buffer[128]; // 减小缓冲区
  433. va_list args;
  434. va_start(args, format);
  435. int len = rt_vsnprintf(buffer, sizeof(buffer) - 2, format, args);
  436. va_end(args);
  437. if (len <= 0)
  438. {
  439. return CSV_ERROR;
  440. }
  441. // 添加换行符
  442. buffer[len] = '\n';
  443. buffer[len + 1] = '\0';
  444. len++;
  445. // 简化写入,单次尝试
  446. ch376_result_t result = ch376.file_write(buffer, len);
  447. if (result == CH376_RESULT_SUCCESS)
  448. {
  449. csv_state.line_count++;
  450. csv_state.file_size += len;
  451. return CSV_SUCCESS;
  452. }
  453. return CSV_ERROR;
  454. }
  455. /* 关闭文件 - 简化版 */
  456. static csv_result_t csv_close(void)
  457. {
  458. if (!csv_state.file_opened)
  459. {
  460. return CSV_SUCCESS;
  461. }
  462. ch376_result_t result = ch376.file_close();
  463. csv_state.file_opened = 0;
  464. csv_state.line_count = 0;
  465. csv_state.file_size = 0;
  466. csv_state.current_file[0] = '\0';
  467. return (result == CH376_RESULT_SUCCESS) ? CSV_SUCCESS : CSV_ERROR;
  468. }
  469. /* 获取当前行数 */
  470. static uint32_t csv_get_line_count(void)
  471. {
  472. return csv_state.line_count;
  473. }
  474. /* 检查文件是否打开 */
  475. static uint8_t csv_is_opened(void)
  476. {
  477. return csv_state.file_opened;
  478. }
  479. /* 获取当前文件名 */
  480. static const char *csv_get_filename(void)
  481. {
  482. return csv_state.current_file;
  483. }
  484. /**
  485. *
  486. * BIT_MAP
  487. *
  488. *
  489. * */
  490. #include "easyflash.h"
  491. // 内部位图结构
  492. typedef struct
  493. {
  494. uint32_t version;
  495. uint8_t bitmap[CSV_BITMAP_BYTES];
  496. } csv_bitmap_t;
  497. static csv_bitmap_t g_bitmap = {0};
  498. static bool g_inited = false;
  499. static struct rt_mutex g_mutex;
  500. // ────────────────────────────────
  501. // 辅助函数:计算儒略日(Julian Day Number)
  502. // 来源:RT-Thread time.c 简化版,支持 2000~2099
  503. // ────────────────────────────────
  504. static long date_to_jdn(int year, int month, int day)
  505. {
  506. if (month <= 2)
  507. {
  508. year--;
  509. month += 12;
  510. }
  511. long a = year / 100;
  512. long b = 2 - a + (a / 4);
  513. return (long)(365.25 * (year + 4716)) + (long)(30.6001 * (month + 1)) + day + b - 1524;
  514. }
  515. // 计算相对于基准日的天数偏移
  516. static int calc_day_offset(int yy, int mm, int dd)
  517. {
  518. int full_year = (yy >= 0 && yy < 100) ? (2000 + yy) : yy;
  519. long jdn_now = date_to_jdn(full_year, mm, dd);
  520. // 基准日:2025-01-01
  521. long jdn_epoch = date_to_jdn(2000 + CSV_BITMAP_EPOCH_YY, CSV_BITMAP_EPOCH_MM, CSV_BITMAP_EPOCH_DD);
  522. long offset = jdn_now - jdn_epoch;
  523. if (offset < 0 || offset >= CSV_BITMAP_MAX_DAYS)
  524. {
  525. return -1; // 超出范围
  526. }
  527. return (int)offset;
  528. }
  529. // ────────────────────────────────
  530. // 公共接口实现
  531. // ────────────────────────────────
  532. void csv_bitmap_init(void)
  533. {
  534. //rt_kprintf("csv_bitmap_init \n\n");
  535. static bool mutex_created = false;
  536. if (!mutex_created)
  537. {
  538. rt_mutex_init(&g_mutex, "csv_bm", RT_IPC_FLAG_FIFO);
  539. mutex_created = true;
  540. }
  541. rt_mutex_take(&g_mutex, RT_WAITING_FOREVER);
  542. if (!g_inited)
  543. {
  544. size_t read_len = 0;
  545. ef_get_env_blob("csv_exist", &g_bitmap, sizeof(g_bitmap), &read_len);
  546. // 校验:长度 + 版本
  547. if (read_len != sizeof(g_bitmap) || g_bitmap.version != CSV_BITMAP_VERSION)
  548. {
  549. // 初始化新位图
  550. memset(&g_bitmap, 0, sizeof(g_bitmap));
  551. g_bitmap.version = CSV_BITMAP_VERSION;
  552. ef_set_env_blob("csv_exist", &g_bitmap, sizeof(g_bitmap));
  553. }
  554. g_inited = true;
  555. }
  556. rt_mutex_release(&g_mutex);
  557. }
  558. int csv_bitmap_mark_exist(int yy, int mm, int dd)
  559. {
  560. if (!g_inited)
  561. csv_bitmap_init();
  562. int offset = calc_day_offset(yy, mm, dd);
  563. if (offset < 0)
  564. return -1;
  565. if (csv_bitmap_is_exist(yy, mm, dd))
  566. {
  567. //rt_kprintf("%02d%02d%02d already marked\n\n", yy, mm, dd);
  568. return 0;
  569. }
  570. rt_mutex_take(&g_mutex, RT_WAITING_FOREVER);
  571. int byte_idx = offset / 8;
  572. int bit_idx = offset % 8;
  573. g_bitmap.bitmap[byte_idx] |= (1U << bit_idx);
  574. int ret = ef_set_env_blob("csv_exist", &g_bitmap, sizeof(g_bitmap));
  575. rt_mutex_release(&g_mutex);
  576. return (ret == EF_NO_ERR) ? 0 : -1;
  577. }
  578. int csv_bitmap_is_exist(int yy, int mm, int dd)
  579. {
  580. if (!g_inited)
  581. csv_bitmap_init();
  582. int offset = calc_day_offset(yy, mm, dd);
  583. if (offset < 0)
  584. return 0;
  585. rt_mutex_take(&g_mutex, RT_WAITING_FOREVER);
  586. int byte_idx = offset / 8;
  587. int bit_idx = offset % 8;
  588. int result = (g_bitmap.bitmap[byte_idx] >> bit_idx) & 1;
  589. rt_mutex_release(&g_mutex);
  590. return result;
  591. }
  592. // === 新增:从 struct tm 计算 offset(供初始化使用)===
  593. int calc_day_offset_from_tm(const struct tm *tm)
  594. {
  595. int yy = tm->tm_year % 100;
  596. int mm = tm->tm_mon + 1;
  597. int dd = tm->tm_mday;
  598. return calc_day_offset(yy, mm, dd); // 复用已有函数
  599. }
  600. // === 新增:从 offset 反推日期(用于遍历)===
  601. int offset_to_date(int offset, struct tm *out_tm)
  602. {
  603. if (!out_tm || offset < 0 || offset >= CSV_BITMAP_MAX_DAYS)
  604. {
  605. return -1;
  606. }
  607. // 基准日:2025-01-01
  608. struct tm epoch = {0};
  609. epoch.tm_year = 2000 + CSV_BITMAP_EPOCH_YY - 1900; // tm_year is years since 1900
  610. epoch.tm_mon = CSV_BITMAP_EPOCH_MM - 1;
  611. epoch.tm_mday = CSV_BITMAP_EPOCH_DD;
  612. epoch.tm_hour = 0;
  613. epoch.tm_min = 0;
  614. epoch.tm_sec = 0;
  615. epoch.tm_isdst = -1;
  616. time_t epoch_time = mktime(&epoch);
  617. if (epoch_time == (time_t)-1)
  618. {
  619. return -1;
  620. }
  621. // 加上 offset 天(86400 秒/天)
  622. time_t target_time = epoch_time + (time_t)offset * 86400;
  623. struct tm *p = localtime(&target_time);
  624. if (!p)
  625. return -1;
  626. *out_tm = *p;
  627. return 0;
  628. }
  629. // === 新增:通过 offset 直接查询位图(内部使用)===
  630. int csv_bitmap_is_exist_by_offset(int offset)
  631. {
  632. if (offset < 0 || offset >= CSV_BITMAP_MAX_DAYS)
  633. return 0;
  634. rt_mutex_take(&g_mutex, RT_WAITING_FOREVER);
  635. int byte_idx = offset / 8;
  636. int bit_idx = offset % 8;
  637. int result = (g_bitmap.bitmap[byte_idx] >> bit_idx) & 1;
  638. rt_mutex_release(&g_mutex);
  639. return result;
  640. }
  641. /**
  642. *
  643. * BIT_MAP
  644. *
  645. *
  646. * */
  647. #define BLOCK_SIZE 512
  648. /**
  649. * @brief 搬运指定日期的 CSV 文件(如 260105.csv)
  650. * @param yy, mm, dd: 日期(如 26, 1, 5)
  651. * @return 0:成功, 1:文件不存在, -1:错误
  652. */
  653. static int transfer_csv_by_date(int yy, int mm, int dd)
  654. {
  655. char filename[13];
  656. rt_snprintf(filename, sizeof(filename), "/%02d%02d%02d.CSV", yy, mm, dd);
  657. rt_kprintf("\n\n transfer_csv_by_date %s \n\n", filename);
  658. uint32_t file_size = 0;
  659. // === 步骤1: 预检查 U 盘是否在位 ===
  660. if (ch376.init() != CH376_RESULT_SUCCESS)
  661. {
  662. rt_kprintf("[CSV] CH376 init failed (USB check)\n");
  663. return -1;
  664. }
  665. if (ch376.switch_mode(CH376_MODE_USB_DISK) != CH376_RESULT_SUCCESS)
  666. {
  667. ch376.deinit();
  668. rt_kprintf("[CSV] Failed to switch to USB mode\n");
  669. return -1;
  670. }
  671. ch376_device_status_t status;
  672. if (ch376.get_status(&status) != CH376_RESULT_SUCCESS || !status.is_device_present)
  673. {
  674. ch376.deinit();
  675. rt_kprintf("[CSV] USB device not present\n");
  676. return -1;
  677. }
  678. ch376.deinit(); // 仅检查,不操作文件
  679. // === 步骤2: 检查 SD 卡上文件是否存在,并获取大小 ===
  680. if (ch376.init() != CH376_RESULT_SUCCESS)
  681. {
  682. rt_kprintf("[CSV] CH376 init failed (SD check)\n");
  683. return -1;
  684. }
  685. if (ch376.switch_mode(CH376_MODE_SD_CARD) != CH376_RESULT_SUCCESS)
  686. {
  687. ch376.deinit();
  688. return -1;
  689. }
  690. if (ch376.get_status(&status) != CH376_RESULT_SUCCESS || !status.is_device_present)
  691. {
  692. ch376.deinit();
  693. return -1;
  694. }
  695. // 检查文件是否存在
  696. if (ch376.file_exists(filename) != CH376_RESULT_SUCCESS)
  697. {
  698. ch376.deinit();
  699. rt_kprintf("file dont exists %s\n", filename);
  700. return 1; // 文件不存在
  701. }
  702. if (ch376.file_open(filename) != CH376_RESULT_SUCCESS)
  703. {
  704. ch376.deinit();
  705. return -1;
  706. }
  707. if (ch376.file_getsize(&file_size) != CH376_RESULT_SUCCESS)
  708. {
  709. ch376.file_close();
  710. ch376.deinit();
  711. return -1;
  712. }
  713. ch376.file_close();
  714. ch376.deinit();
  715. rt_kprintf("[CSV] Start transferring %s (%lu bytes)\n", filename, file_size);
  716. // === 步骤3: 分块搬运(512B/块)===
  717. uint8_t buffer[BLOCK_SIZE];
  718. uint32_t offset = 0;
  719. while (offset < file_size)
  720. {
  721. uint32_t to_read = (file_size - offset > BLOCK_SIZE) ? BLOCK_SIZE : (file_size - offset);
  722. // ---- 从 SD 卡读取一块 ----
  723. if (ch376.init() != CH376_RESULT_SUCCESS)
  724. {
  725. rt_kprintf("[CSV] SD init failed during read\n");
  726. return -1;
  727. }
  728. if (ch376.switch_mode(CH376_MODE_SD_CARD) != CH376_RESULT_SUCCESS)
  729. {
  730. ch376.deinit();
  731. return -1;
  732. }
  733. if (ch376.file_open(filename) != CH376_RESULT_SUCCESS)
  734. {
  735. ch376.deinit();
  736. return -1;
  737. }
  738. if (ch376.file_seek(offset) != CH376_RESULT_SUCCESS)
  739. {
  740. ch376.file_close();
  741. ch376.deinit();
  742. return -1;
  743. }
  744. uint32_t rlen = 0;
  745. if (ch376.file_read(buffer, to_read, &rlen) != CH376_RESULT_SUCCESS || rlen != to_read)
  746. {
  747. ch376.file_close();
  748. ch376.deinit();
  749. return -1;
  750. }
  751. ch376.file_close();
  752. ch376.deinit();
  753. // ---- 写入 U 盘(覆盖指定位置)----
  754. if (ch376.init() != CH376_RESULT_SUCCESS)
  755. {
  756. rt_kprintf("[CSV] USB init failed during write\n");
  757. return -1;
  758. }
  759. if (ch376.switch_mode(CH376_MODE_USB_DISK) != CH376_RESULT_SUCCESS)
  760. {
  761. ch376.deinit();
  762. return -1;
  763. }
  764. // 注意:CH376 的 file_create 会清空文件,file_open 不会创建新文件
  765. // 所以首次写入需 create,后续可 open。但为了统一,我们每次都 create(会丢失之前数据!)
  766. // 更好的做法:只在 offset==0 时 create,否则 open。
  767. if (offset == 0)
  768. {
  769. // 首次写入:创建新文件
  770. if (ch376.file_create(filename) != CH376_RESULT_SUCCESS)
  771. {
  772. ch376.deinit();
  773. return -1;
  774. }
  775. }
  776. else
  777. {
  778. // 后续写入:打开已有文件
  779. if (ch376.file_open(filename) != CH376_RESULT_SUCCESS)
  780. {
  781. ch376.deinit();
  782. return -1;
  783. }
  784. }
  785. if (ch376.file_seek(offset) != CH376_RESULT_SUCCESS)
  786. {
  787. ch376.file_close();
  788. ch376.deinit();
  789. return -1;
  790. }
  791. if (ch376.file_write(buffer, rlen) != CH376_RESULT_SUCCESS)
  792. {
  793. ch376.file_close();
  794. ch376.deinit();
  795. return -1;
  796. }
  797. ch376.file_close();
  798. ch376.deinit();
  799. offset += rlen;
  800. rt_kprintf("[CSV] Transferred %lu / %lu bytes\n", offset, file_size);
  801. }
  802. rt_kprintf("[CSV] Transfer completed: %s\n", filename);
  803. return 0;
  804. }
  805. int transfer_csv_recent_days(int days)
  806. {
  807. time_t now = time(RT_NULL);
  808. if (now == (time_t)-1)
  809. {
  810. rt_kprintf("[CSV] Failed to get current time\n");
  811. return -1;
  812. }
  813. // ? 立即复制当前时间到本地结构体,不保留指针
  814. struct tm current_tm;
  815. struct tm *p = localtime(&now);
  816. if (!p)
  817. {
  818. rt_kprintf("[CSV] localtime failed\n");
  819. return -1;
  820. }
  821. current_tm = *p; // 复制内容!
  822. int success_count = 0;
  823. for (int i = 0; i < days; i++)
  824. {
  825. rt_kprintf("transfer_csv_recent_days >> for times %d / %d ", i, days);
  826. struct tm target = {0};
  827. target.tm_year = current_tm.tm_year;
  828. target.tm_mon = current_tm.tm_mon;
  829. target.tm_mday = current_tm.tm_mday - i;
  830. target.tm_hour = current_tm.tm_hour;
  831. target.tm_min = current_tm.tm_min;
  832. target.tm_sec = current_tm.tm_sec;
  833. target.tm_isdst = -1;
  834. time_t t_target = mktime(&target);
  835. if (t_target == (time_t)-1)
  836. {
  837. rt_kprintf("[CSV] mktime failed for offset %d\n", i);
  838. continue;
  839. }
  840. // 获取归一化后的日期(这次可以安全使用,因为我们不保存指针)
  841. p = localtime(&t_target);
  842. if (!p)
  843. continue;
  844. int yy = p->tm_year % 100;
  845. int mm = p->tm_mon + 1;
  846. int dd = p->tm_mday;
  847. char filename[13];
  848. rt_snprintf(filename, sizeof(filename), "/%02d%02d%02d.CSV", yy, mm, dd);
  849. rt_kprintf("[CSV] Trying: %s\n", filename);
  850. int ret = transfer_csv_by_date(yy, mm, dd);
  851. if (ret == 0)
  852. {
  853. success_count++;
  854. }
  855. else if (ret == -1)
  856. {
  857. rt_kprintf("[CSV] Fatal error on %s\n", filename);
  858. break;
  859. }
  860. // ret == 1: file not exists, continue
  861. }
  862. rt_kprintf("[CSV] Transfer finished. %d files moved.\n", success_count);
  863. return success_count;
  864. }
  865. /**
  866. * @brief 导出所有已知存在的 CSV 文件(从基准日到今天)
  867. * @return 成功搬运的文件数量
  868. */
  869. int transfer_csv_all_known_exists(void)
  870. {
  871. time_t now = time(RT_NULL);
  872. if (now == (time_t)-1)
  873. {
  874. rt_kprintf("[CSV] Failed to get current time\n");
  875. return -1;
  876. }
  877. csv_bitmap_init();
  878. struct tm current_tm;
  879. struct tm *p = localtime(&now);
  880. if (!p)
  881. {
  882. rt_kprintf("[CSV] localtime failed\n");
  883. return -1;
  884. }
  885. current_tm = *p; // 安全复制
  886. // 计算今天的儒略日偏移(相对于基准日)
  887. int today_offset = calc_day_offset_from_tm(&current_tm);
  888. if (today_offset < 0 || today_offset >= MAX_EXPORT_SPAN_DAYS)
  889. {
  890. rt_kprintf("[CSV] Current date out of bitmap range\n");
  891. return -1;
  892. }
  893. int success_count = 0;
  894. // 从基准日(offset=0)遍历到今天(inclusive)
  895. for (int offset = 0; offset <= today_offset; offset++)
  896. {
  897. // 快速查询位图:该天是否存在 CSV?
  898. if (!csv_bitmap_is_exist_by_offset(offset))
  899. {
  900. continue; // 不存在,跳过
  901. }
  902. // 将 offset 转回 yy/mm/dd
  903. struct tm target_tm = {0};
  904. if (offset_to_date(offset, &target_tm) != 0)
  905. {
  906. continue;
  907. }
  908. int yy = target_tm.tm_year % 100;
  909. int mm = target_tm.tm_mon + 1;
  910. int dd = target_tm.tm_mday;
  911. char filename[13];
  912. rt_snprintf(filename, sizeof(filename), "/%02d%02d%02d.CSV", yy, mm, dd);
  913. rt_kprintf("[CSV] Found known file: %s\n", filename);
  914. // 执行搬运
  915. int ret = transfer_csv_by_date(yy, mm, dd);
  916. if (ret == 0)
  917. {
  918. success_count++;
  919. }
  920. else if (ret == -1)
  921. {
  922. rt_kprintf("[CSV] Fatal error on %s, aborting.\n", filename);
  923. break;
  924. }
  925. // ret == 1: 物理文件不存在(但位图标记了)→ 可选:清除位图标记
  926. }
  927. if (success_count <= 0)
  928. {
  929. rt_kprintf("[CSV] Export finished. %d files transferred. Lets Try again!\n", success_count);
  930. success_count = transfer_csv_recent_days(30);
  931. rt_kprintf("[CSV] Export finished. %d files transferred.\n", success_count);
  932. }
  933. else
  934. {
  935. rt_kprintf("[CSV] Export finished. %d files transferred. QUICK\n", success_count);
  936. }
  937. return success_count;
  938. }
  939. MSH_CMD_EXPORT(transfer_csv_all_known_exists, transfer_csv_all_known_exists)