mserial.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. #ifndef MSEIAL_H
  2. #define MSEIAL_H
  3. #include <QObject>
  4. #include <QtSerialPort/QSerialPort>
  5. #include <QtSerialPort/QSerialPortInfo>
  6. #include <QDateTime> // RX 诊断:记录最后一次收到字节的时刻
  7. #include <QStringList>
  8. #include <QString>
  9. #include <QByteArray>
  10. #include <QJsonDocument> // 组帧完整性校验(isBusinessFrame)
  11. #include <QJsonParseError>
  12. #include <QTextCodec>
  13. #include <QThread>
  14. #include <m_json.h>
  15. #include <QTimer>
  16. #include <QStandardPaths>
  17. #include <QStorageInfo>
  18. #include <QVideoFrame>
  19. #include <atomic>
  20. #include <mysql.h>
  21. #include <m_loger.h>
  22. #include <mcu_console.h>
  23. #include "lwjson/lwjson.h"
  24. #include "ymodem.h"
  25. class SerialThread: public QThread
  26. {
  27. Q_OBJECT
  28. public:
  29. // 数据缓存区
  30. QByteArray dataBuf;
  31. YMODEM* getYmodem(); // 声明 getter
  32. explicit SerialThread(QObject *parent = nullptr);
  33. ~SerialThread();
  34. void setSerialPortSettings(const QString &portName, QSerialPort::BaudRate baudRate,
  35. QSerialPort::DataBits dataBits, QSerialPort::Parity parity,
  36. QSerialPort::StopBits stopBits, QSerialPort::FlowControl flowControl);
  37. void init();
  38. void run() override;
  39. void stop();
  40. void SetLedState(bool sw){
  41. sendData(m_json.setLedState(sw));
  42. }
  43. Q_INVOKABLE void reboot(){
  44. sendData(m_json.CmdReboot());
  45. }
  46. QSerialPort& getSerialPort() {
  47. return m_serialPort;
  48. }
  49. Q_INVOKABLE void readBoardData();
  50. Q_INVOKABLE void uploadData_Mqtt(){
  51. m_dat_f.setInterval(0);
  52. };
  53. Q_INVOKABLE void update_dat_f_main(QString freq); //更新数据上传间隔
  54. Q_INVOKABLE void sendCmd(QString cmd_type,bool sw,QString setup,QString speed);
  55. Q_INVOKABLE QStringList pathinfo(){
  56. QStringList pf_pic;
  57. pf_pic.append(qst_dirPath);
  58. pf_pic.append(QString::number(int_fileCount));
  59. pf_pic.append(QString::number(int_totalSize/1048576));
  60. return pf_pic;
  61. }
  62. Q_INVOKABLE void readPathinfo(){
  63. analyzeDirectory(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
  64. }
  65. Q_INVOKABLE void removepic(){
  66. deleteAllFilesInDirectory(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
  67. }
  68. // ===== 存储空间循环覆写 =====
  69. // 归档图片最少保留的剩余空间:低于该值时删除最老的一组图片
  70. static constexpr qint64 kMinFreeSpace = 1073741824LL; // 1GB
  71. // 指定路径所在存储卷的剩余可用字节数
  72. static qint64 getFreeSpace(const QString &path = QString())
  73. {
  74. const QString target = path.isEmpty()
  75. ? QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)
  76. : path;
  77. QStorageInfo storage(target);
  78. if (storage.isValid() && storage.isReady())
  79. return storage.bytesAvailable();
  80. QStorageInfo fallback(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
  81. return (fallback.isValid() && fallback.isReady()) ? fallback.bytesAvailable() : 0;
  82. }
  83. // 循环覆写:剩余空间不足 minFree 时,按时间由旧到新逐组删除归档图片
  84. // (一组=一个归档目录,即 年/月/日/时间戳 下的时间戳目录),
  85. // 录制视频流(.rawv)不参与删除;返回实际释放的字节数
  86. static qint64 ensureStorageSpace(qint64 minFree = kMinFreeSpace)
  87. {
  88. const QString root = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
  89. qint64 freed = 0;
  90. if (getFreeSpace(root) >= minFree)
  91. return freed;
  92. LOG("存储空间不足{} MB,开始循环覆写", minFree / (1024.0 * 1024.0));
  93. QStringList groups;
  94. collectArchiveGroups(root, root, groups);
  95. groups.sort(); // 归档目录名即时间戳,排序后最前者即最老的一组
  96. int removedGroups = 0;
  97. for (const QString &group : groups) {
  98. if (getFreeSpace(root) >= minFree)
  99. break;
  100. const qint64 f = removeGroupFiles(group);
  101. if (f > 0) {
  102. freed += f;
  103. removedGroups++;
  104. LOG("循环覆写:删除最老一组 {}", group.toStdString());
  105. }
  106. }
  107. LOG("循环覆写结束:删除{}组,释放{} MB,剩余{} MB", removedGroups,
  108. freed / (1024.0 * 1024.0), getFreeSpace(root) / (1024.0 * 1024.0));
  109. return freed;
  110. }
  111. Q_INVOKABLE void setCollt(int sh1 ,int eh1,int sh2,int eh2,int sh3,int eh3){
  112. sendData(m_json.CmdParamconf(sh1,eh1,sh2,eh2,sh3,eh3));
  113. }
  114. Q_INVOKABLE void setCollt_min(int sh1 ,int eh1,int sh2,int eh2,int sh3,int eh3){
  115. sendData(m_json.CmdParamconf_min(sh1,eh1,sh2,eh2,sh3,eh3));
  116. }
  117. Q_INVOKABLE void setTempconf(int tpl ,int tph){
  118. sendData(m_json.CmdParamconf_temp(tpl,tph));
  119. }
  120. Q_INVOKABLE void setHt_xy_dis(int xdis ,int ydis){
  121. sendData(m_json.CmdParamconf_xy_dis(xdis,ydis));
  122. }
  123. Q_INVOKABLE void setLightness(int val){
  124. auto qtContext = QJniObject(QNativeInterface::QAndroidApplication::context()); //activity
  125. if (qtContext.isValid()) {
  126. QJniObject jClass("com/yfkj/bzyv1/Backlight");
  127. jClass.callMethod<void>("setScreenLight","(Landroid/content/Context;I)V",qtContext.object(),val);
  128. //jClass.callStaticMethod<void>("turnScreenOff", "()V");
  129. }
  130. #if 0
  131. if(val==-255){
  132. QJniObject::callStaticMethod<void>("GetUsbPermission",
  133. "turnScreenOff",
  134. "()V");
  135. }
  136. #endif
  137. }
  138. Q_INVOKABLE QString getId(){
  139. return param::imei;
  140. }
  141. Q_INVOKABLE QString getIccid(){
  142. return param::iccid;
  143. }
  144. Q_INVOKABLE QString getlat(){
  145. return param::gps_lat;
  146. }
  147. Q_INVOKABLE QString getlng(){
  148. return param::gps_lng;
  149. }
  150. //Android 面板 GNSS:海拔(m)/可视卫星数/已用卫星数,由 main.cpp GPSInfo 写入 param
  151. Q_INVOKABLE QString getElevation(){
  152. return param::gps_elevation;
  153. }
  154. Q_INVOKABLE QString getSatView(){
  155. return param::gps_sat_view;
  156. }
  157. Q_INVOKABLE QString getSatUsed(){
  158. return param::gps_sat_used;
  159. }
  160. Q_INVOKABLE QString get_app_version(){
  161. return APP_VERSION;
  162. }
  163. //MCU 调试日志采集状态(端口 / 落盘文件 / 已收字节数 / 是否在采):
  164. //现场排障用,QML: serial.mcuConsoleInfo()
  165. Q_INVOKABLE QString mcuConsoleInfo();
  166. //业务串口(ttyS3)接收诊断,QML: serial.serialRxInfo()
  167. //"发得出去、收不回来"时先看这句:bytes 是否在涨、帧数是否在涨
  168. Q_INVOKABLE QString serialRxInfo();
  169. //相机连接状态:测试页 Frames 打开/关闭/失败时回写,主页状态栏"相机状态"展示用。
  170. //放在 serial 这个常驻 context property 上,跨页面都能响应式读取
  171. Q_PROPERTY(bool cameraConnected READ cameraConnected WRITE setCameraConnected NOTIFY cameraConnectedChanged)
  172. bool cameraConnected() const { return m_cameraConnected; }
  173. void setCameraConnected(bool sta){
  174. if(m_cameraConnected == sta) return;
  175. m_cameraConnected = sta;
  176. emit cameraConnectedChanged(sta);
  177. }
  178. Q_INVOKABLE void makeJsonRpc(const QString &method,const QString &value)
  179. {
  180. sendData(m_json.MakeJsonRPC(method,value));
  181. }
  182. signals:
  183. void dataReceived(const QByteArray &data);
  184. void dataUpload(const QByteArray &data);
  185. void updatestart(QString filename);
  186. void auto_takephoto(bool sw);
  187. void takephotodone();
  188. //收到控制板 record_stop:停止录制并处理视频流(分析/融合/删除录制文件/上传融合图)
  189. void recordStop();
  190. void disconnect_485();
  191. void autotestdone();
  192. void translatedone();
  193. void netMessage(const QByteArray &data);
  194. void autoFocusDone();
  195. void autoFocusStart();
  196. void lwjsonStreamDONE(const QByteArray &data);
  197. void cameraConnectedChanged(bool sta);
  198. void signal_movy(const QString stepcount);
  199. void timeout_mov_stop();
  200. void gpsSuccess();
  201. void ymodemReady(QString mtype);
  202. void ymodemProgress(int val,int tval);
  203. void ymodemFinished(int res);
  204. public slots:
  205. void sendData(const QByteArray &data);
  206. void mqtttoserial(const QByteArray &data);
  207. void getmodemresult(int res);
  208. void startYmodem(const QString path);
  209. void startUpgrade(QString path)
  210. {
  211. if(!m_ymodem) return;
  212. //【防重复触发】主板可能重复上报 "system will update",或服务器/界面重复下发升级指令。
  213. // 升级期间第二次进来会打断正在传输的 ACK/'C' 交互,使主板收到的包头错位 ->
  214. // "Update firmware fail." -> 主板复位。这里用 exchange 做原子判定,重复的只记日志。
  215. if(m_upgrading.exchange(true)){
  216. LOG("升级已在进行中,忽略重复的升级指令:{}", path.toStdString());
  217. return;
  218. }
  219. m_ymodem->start_ymodem(path);
  220. }
  221. Q_INVOKABLE void recoverMcuParam();
  222. private slots:
  223. //void readBoardData();
  224. QString selectSerialPortName();
  225. void feedJsonParser(const QByteArray& data)
  226. {
  227. // ---- RX 统计(现场排障用,serial.serialRxInfo() 可读)----
  228. // m_rxBytes 一直不涨 → 端口上根本没有字节:接错口 / RX 线 / MCU 没发 / 被别的进程占了
  229. // m_rxBytes 涨、m_rxDones 不涨 → 字节到了但攒不出完整帧:脏字节、波特率偏差、干扰、解析器错位
  230. m_rxBytes += static_cast<quint64>(data.size());
  231. const qint64 nowMs = QDateTime::currentMSecsSinceEpoch();
  232. m_rxLastMs = nowMs;
  233. // ---- ①【2.8.70】帧超时自愈:帧尾丢了也不能一直等 ----
  234. // 帧尾被线路丢掉时 lwjson 可能一个错误都不报:下一帧的 '{' 会被当成还没结束的
  235. // primitive 继续吞,整帧静默消失,栈深度还越攒越深,永远等不到 STREAMDONE。
  236. // 离线实测(真实的 lwjson 1.8.1):把一帧最后 2 个 '}' 去掉、后面紧跟一整帧好帧,
  237. // 406 字节全部返回 STREAMINPROG —— 0 个错误、0 帧输出,且永不自愈。
  238. // 这正是现场"发得出去、收不回来,重发也没用"的形态,必须按时间兜底。
  239. if (!jsonBuf.isEmpty() && m_frameStartMs > 0
  240. && nowMs - m_frameStartMs > kFrameTimeoutMs) {
  241. dropRxFrame("帧超时", -1, jsonBuf);
  242. }
  243. for (uint8_t b : data) {
  244. const lwjsonr_t ret = lwjson_stream_parse(&lwparser, static_cast<char>(b));
  245. // 只在解析进行中或完成时跟踪字节,避免累积无关数据
  246. if (ret == lwjsonSTREAMINPROG || ret == lwjsonSTREAMDONE) {
  247. if (jsonBuf.isEmpty())
  248. m_frameStartMs = nowMs; // 帧首字节时刻,帧超时从这里开始算
  249. jsonBuf.append(static_cast<char>(b));
  250. }
  251. switch (ret){
  252. case lwjsonERRJSON: // 1, 无效的字符
  253. // ---- ②【2.8.70】出错必须复位解析器(2.8.69 这一行是被注释掉的)----
  254. // lwjson 出错后不会自己回到"等首字符",状态会一直错着。
  255. // 现场 2.8.69 那条 ":"0","rcnt":2,..." 就是这么来的:上一帧被截断
  256. // + 状态带毒,这一帧的后半截恰好语法自洽,于是被当成完整帧 emit 出去,
  257. // 业务层找不到 cmd 静默丢弃 → 界面表现"JSON 解析不完整/收不到数据"。
  258. // 帧外杂字节(jsonBuf 为空)不告警也不复位:此时解析器必然是干净状态。
  259. if (!jsonBuf.isEmpty())
  260. dropRxFrame("错码", static_cast<int>(b), jsonBuf);
  261. break;
  262. case lwjsonSTREAMWAITFIRSTCHAR: // 2, 等待首字符
  263. break;
  264. case lwjsonSTREAMINPROG: // 3, 正在解析中
  265. // 帧内丢了 '}' 时 jsonBuf 会跨帧累积,给一个上限把野状态收掉
  266. if (jsonBuf.size() > kMaxFrameBytes)
  267. dropRxFrame("超长", -1, jsonBuf);
  268. break;
  269. case lwjsonSTREAMDONE: { // 4, 解析已完成
  270. const QByteArray frame = jsonBuf; // 先留副本:复位会把 jsonBuf 清掉
  271. if (!frame.startsWith('{')) {
  272. // 顶层数组/标量不承载任何 cmd 流程(见 processJsonData),静默丢弃
  273. resetRxFrame();
  274. break;
  275. }
  276. // ---- ③【2.8.70】完整性闸门:语法完整 ≠ 这是一整帧 ----
  277. // 丢字节后报文后半截往往本身就是一个合法 JSON 对象(实测:丢掉
  278. // {"cmd":"data","ext": 之后,剩下的 {"dver":...} 完全合法)。
  279. // 只靠 lwjson 无法区分,必须校验协议键,否则残帧会流到 QML:
  280. // JSON.parse 成功但 ext 缺失 → 抛 TypeError / 显示错值。
  281. if (!isBusinessFrame(frame)) {
  282. dropRxFrame("残帧", -1, frame);
  283. break;
  284. }
  285. resetRxFrame();
  286. ++m_rxDones;
  287. // ---- ④【2.8.72】整帧落盘恢复(2.8.70 只打前 96 字节是错的)----
  288. // 96 字节正好切在 "...\"batSt" 上,与"帧在 batSt 处被截断"的历史症状
  289. // 一模一样,现场无法区分"解析成功"和"帧被截断",也看不到字段值可以核对。
  290. // 实际帧率只有 0.2 帧/秒(MCU 只在收到 synchronization 后回一帧),
  291. // 整帧落盘的开销可以忽略;只有超大帧才截断,且**显式标注省略了多少字节**,
  292. // 绝不做无声截断。
  293. if (frame.size() <= 1024) {
  294. LOG("RX 帧 {} 字节: {}", frame.size(), frame.constData());
  295. } else {
  296. const QByteArray head = frame.left(512);
  297. const QByteArray tail = frame.right(256);
  298. LOG("RX 帧 {} 字节(超长, 中间省略 {} 字节): {} …… {}",
  299. frame.size(), frame.size() - 768,
  300. head.constData(), tail.constData());
  301. }
  302. emit lwjsonStreamDONE(frame);
  303. break;
  304. }
  305. case lwjsonERRMEM: // 5, 嵌套的太深("LWJSON_CFG_STREAM_STACK_SIZE")
  306. ERROR("lwjsonERRMEM! 嵌套超过 LWJSON_CFG_STREAM_STACK_SIZE");
  307. dropRxFrame("嵌套过深", -1, jsonBuf);
  308. break;
  309. default: // 流式解析时, 其它的返回值, 都不应该出现
  310. ERROR("未知错误:{:d}",static_cast<int>(ret));
  311. resetRxFrame();
  312. break;
  313. }
  314. }
  315. }
  316. // 丢弃当前半帧:计数 + 限频告警 + 复位解析器。
  317. // 告警 5 秒限频(干扰严重时不刷屏),head/tail 用**十六进制**打印:
  318. // 之前用 constData() 打,遇到 0x00 会直接截断,等于把唯一的证据丢掉了
  319. // (现场那条坏帧的出错字节就是这么被藏起来的)。
  320. void dropRxFrame(const char* why, int badByte, const QByteArray& frame)
  321. {
  322. ++m_rxBadFrames;
  323. const qint64 nowMs = QDateTime::currentMSecsSinceEpoch();
  324. if (nowMs - m_badLogMs >= 5000) {
  325. m_badLogMs = nowMs;
  326. const QByteArray headHex = frame.left(64).toHex(' ');
  327. const QByteArray tailHex = frame.size() > 96 ? frame.right(32).toHex(' ')
  328. : QByteArrayLiteral("-");
  329. if (badByte >= 0) {
  330. WARN("RX 坏帧[{}]: 丢弃 {} 字节(累计坏帧 {}) 出错字节=0x{:02X} head={} tail={}",
  331. why, frame.size(), m_rxBadFrames.load(), badByte,
  332. headHex.constData(), tailHex.constData());
  333. } else {
  334. WARN("RX 坏帧[{}]: 丢弃 {} 字节(累计坏帧 {}) head={} tail={}",
  335. why, frame.size(), m_rxBadFrames.load(),
  336. headHex.constData(), tailHex.constData());
  337. }
  338. }
  339. resetRxFrame();
  340. }
  341. // 业务帧判定:顶层必须是对象,且带 cmd / method / jsonrpc 之一。
  342. // 用 QJsonDocument 而不是字符串 contains("cmd"):既校验语法,又不会把
  343. // 值里恰好出现 "cmd" 的残帧放过去(500 字节一帧,解析开销 ~20μs,可忽略)。
  344. static bool isBusinessFrame(const QByteArray& frame)
  345. {
  346. QJsonParseError err{};
  347. const QJsonDocument doc = QJsonDocument::fromJson(frame, &err);
  348. if (err.error != QJsonParseError::NoError || !doc.isObject())
  349. return false;
  350. const QJsonObject obj = doc.object();
  351. return obj.contains(QStringLiteral("cmd"))
  352. || obj.contains(QStringLiteral("method"))
  353. || obj.contains(QStringLiteral("jsonrpc"));
  354. }
  355. private:
  356. //【线程安全】串口线程主循环读它来决定是否暂停解析,升级流程在另一线程里置位,
  357. // 用 atomic 避免编译器把 while 里的读取提到循环外(或读到半写状态)。
  358. std::atomic<bool> m_upgrading{false};
  359. void processJsonData(const QByteArray &jsonData);
  360. void saveMcuParam(const QJsonObject &params);
  361. //MCU 调试口日志(ttyS2):只读采集,开启即可,不再向 MCU 下发任何串口映射指令
  362. //(console 落在哪一路由 MCU 端自行维护,见 header/mcu_console.h)
  363. void startMcuConsoleLog();
  364. // ---- 下行发送队列(主线程 → 串口线程)----
  365. // QML 里点按钮/发指令时,主线程只负责入队;run() 在自己的循环里取出来写串口。
  366. // 这样既不会跨线程操作 QSerialPort,也能保证"点了就一定发出去"。
  367. void flushTxQueue();
  368. // 真正写串口:只允许在串口线程(run/flushTxQueue)里调用
  369. void writeToPort(const QByteArray &data);
  370. mutable QMutex m_txQueueMutex;
  371. QList<QByteArray> m_txQueue;
  372. QTimer m_dat_f;
  373. QTimer* timeout_mov = nullptr;
  374. QSerialPort m_serialPort;
  375. // ---- 业务串口(ttyS3) RX 诊断计数 ----
  376. // "发送正常、接收不到数据"必须能一眼区分是哪种:
  377. // m_rxBytes 不涨 → 端口上确实没有字节(接线/MCU 没发/驱动/被占用)
  378. // m_rxBytes 涨但帧数不涨 → 字节到了却攒不出完整 JSON(脏字节/波特率/干扰/解析器错位)
  379. std::atomic<quint64> m_rxBytes{0};
  380. std::atomic<quint64> m_rxDones{0};
  381. std::atomic<quint64> m_parseResets{0};
  382. std::atomic<quint64> m_rxBadFrames{0}; // 被丢弃的坏帧数(错码/残帧/超时/超长)
  383. std::atomic<qint64> m_rxLastMs{0};
  384. // 最近一次真正写出报文的时刻:RX 看门狗用它判断"是不是我们刚问过、
  385. // MCU 却没回"(MCU 是应答式的,没人问的时候它本来就不发,不能算故障)
  386. std::atomic<qint64> m_lastTxMs{0};
  387. //MCU 调试口采集(ttyS2):只读、独立线程,与 ttyS3 业务串口互不影响
  388. McuConsoleLog m_mcuConsole;
  389. //【崩溃修复】YMODEM* 必须在声明处初始化为 nullptr。
  390. // 原代码只写 `YMODEM *m_ymodem;`,是野指针(未初始化)。
  391. // run() 里 `m_ymodem = new YMODEM(...)` 是在**串口子线程**执行的,
  392. // 而 SerialThread 对象本身是在主线程构造的(main.cpp: `SerialThread serialThread;`),
  393. // 两者存在启动竞态:主线程若在 run() 赋值之前就通过
  394. // startUpgrade()/getYmodem() 走到 `m_ymodem->start_ymodem(...)`,
  395. // 就会解引用野指针 → SIGSEGV(fault addr 0x0)。
  396. YMODEM *m_ymodem = nullptr; // YMODEM对象
  397. SqliteOperator *sqlConfig = nullptr;
  398. mutable QMutex m_writeMutex;
  399. bool m_running;
  400. bool m_cameraConnected = false; //相机连接状态(见 cameraConnected 属性)
  401. //相机连接状态轮询:后台枚举海康相机,数量>0=已连接,=0=未连接
  402. QTimer m_camStaTimer;
  403. std::atomic<bool> m_camEnumBusy{false}; //上一轮枚举未完成时跳过本轮
  404. void pollCameraDevices(); //发起后台枚举,结果回UI线程更新属性
  405. bool data_upload;
  406. int connect_board; //主板串口连接状态
  407. JsonFunc m_json;
  408. QString qst_dirPath;
  409. int int_fileCount;
  410. qint64 int_totalSize;
  411. // 用于存储目录统计结果的结构体
  412. struct DirectoryStats {
  413. qint64 totalSize = 0;
  414. int fileCount = 0;
  415. };
  416. // ---- 业务串口(ttyS3) 组帧状态(lwjson 流式解析器,见 feedJsonParser)----
  417. lwjson_stream_parser_t lwparser; // 逐字节流式状态机,构造函数里 lwjson_stream_init
  418. QByteArray jsonBuf; // 当前帧累积区(STREAMINPROG/STREAMDONE 期间的字节)
  419. qint64 m_frameStartMs = 0; // 当前帧首字节时刻(0=当前没有半帧),帧超时判据
  420. qint64 m_badLogMs = 0; // 坏帧告警限频(只在串口线程访问,无需 atomic)
  421. // 单帧组装超时:正常一帧约 500 字节 @115200 ≈ 43ms,1.5s 已是"明显不正常",
  422. // 但不能更短 —— 采集/升级等场景下 MCU 分段发一帧时中间可能有秒级间隔。
  423. static constexpr qint64 kFrameTimeoutMs = 1500;
  424. // 单帧字节上限:帧内丢 '}' 时 jsonBuf 会跨帧累积,超过即判野状态
  425. static constexpr int kMaxFrameBytes = 4096;
  426. // 丢弃当前半帧并复位解析器。只在串口线程(feedJsonParser / run)里调用,不跨线程。
  427. // 【2.8.70】这里改用 lwjson_stream_init() 而不是 lwjson_stream_reset():
  428. // reset 只清 parse_state / stack_pos,**不清 prev_c**;若上一个成功处理的字节是
  429. // '\\',残留的 prev_c 会让下一帧起始的 '"' 被当成字符串内容,整帧错位。
  430. // init() 是 memset 整个结构(约 1KB),只在丢帧时调用,开销可忽略。
  431. void resetRxFrame()
  432. {
  433. jsonBuf.clear();
  434. m_frameStartMs = 0;
  435. lwjson_stream_init(&lwparser, nullptr);
  436. }
  437. // 递归收集"一组图片"的归档目录(叶子目录,即时间戳目录)
  438. static void collectArchiveGroups(const QString &rootPath, const QString &directoryPath, QStringList &groups)
  439. {
  440. QDir directory(directoryPath);
  441. if (!directory.exists())
  442. return;
  443. bool hasFile = false;
  444. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  445. foreach (const QFileInfo &fileInfo, fileInfoList) {
  446. if (fileInfo.isDir())
  447. collectArchiveGroups(rootPath, fileInfo.filePath(), groups);
  448. else
  449. hasFile = true;
  450. }
  451. // 根目录本身不算一组(只清理归档子目录)
  452. if (hasFile && directory.absolutePath() != QDir(rootPath).absolutePath())
  453. groups.append(directory.absolutePath());
  454. }
  455. // 删除一组归档目录中的图片(保留 .rawv 录制视频流),空目录一并移除;返回释放的字节数
  456. static qint64 removeGroupFiles(const QString &directoryPath)
  457. {
  458. qint64 freed = 0;
  459. QDir directory(directoryPath);
  460. if (!directory.exists())
  461. return freed;
  462. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  463. foreach (const QFileInfo &fileInfo, fileInfoList) {
  464. if (fileInfo.isDir()) {
  465. freed += removeGroupFiles(fileInfo.filePath());
  466. // 空目录才删除成功,含保留视频流的目录会保留
  467. QDir().rmdir(fileInfo.filePath());
  468. } else if (fileInfo.suffix().compare(QStringLiteral("rawv"), Qt::CaseInsensitive) != 0) {
  469. const qint64 size = fileInfo.size();
  470. if (QFile::remove(fileInfo.filePath()))
  471. freed += size;
  472. }
  473. }
  474. return freed;
  475. }
  476. void deleteAllFilesInDirectory(const QString &directoryPath)
  477. {
  478. QDir directory(directoryPath);
  479. if (!directory.exists()) {
  480. LOG("Directory does not exist.");
  481. return;
  482. }
  483. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  484. foreach (const QFileInfo &fileInfo, fileInfoList) {
  485. if (fileInfo.isDir()) {
  486. // 递归删除子目录中的文件
  487. deleteAllFilesInDirectory(fileInfo.filePath());
  488. } else {
  489. // 删除文件
  490. QFile::remove(fileInfo.filePath());
  491. }
  492. }
  493. analyzeDirectory(directoryPath);
  494. }
  495. // 递归获取目录统计信息
  496. DirectoryStats getDirectoryStats(const QString &directoryPath)
  497. {
  498. QDir directory(directoryPath);
  499. DirectoryStats stats;
  500. if (!directory.exists()) {
  501. LOG("Directory does not exist.");
  502. }
  503. qint64 totalSize = 0;
  504. int fileCount = 0;
  505. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  506. foreach (const QFileInfo &fileInfo, fileInfoList) {
  507. if (fileInfo.isDir()) {
  508. // 递归获取子目录的统计信息
  509. DirectoryStats subStats = getDirectoryStats(fileInfo.filePath());
  510. stats.fileCount += subStats.fileCount;
  511. stats.totalSize += subStats.totalSize;
  512. } else {
  513. stats.fileCount++;
  514. stats.totalSize += fileInfo.size();
  515. }
  516. }
  517. return stats;
  518. qst_dirPath = directoryPath;
  519. int_fileCount = fileCount;
  520. int_totalSize = totalSize;
  521. LOG("Directory:{}",directoryPath.toStdString());
  522. LOG("File count:{}",fileCount);
  523. LOG("Total size:{} bytes",totalSize);
  524. }
  525. // 使用示例
  526. void analyzeDirectory(const QString &directoryPath) {
  527. LOG("Analyzing directory: {}", directoryPath.toStdString());
  528. DirectoryStats stats = getDirectoryStats(directoryPath);
  529. qst_dirPath = directoryPath;
  530. int_fileCount = stats.fileCount;
  531. int_totalSize = stats.totalSize;
  532. LOG("Total files:{}",int_totalSize);
  533. LOG("Total size:{} MB",stats.totalSize / (1024.0 * 1024.0));
  534. }
  535. };
  536. #endif // MSEIAL_H