| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586 |
- #ifndef MSEIAL_H
- #define MSEIAL_H
- #include <QObject>
- #include <QtSerialPort/QSerialPort>
- #include <QtSerialPort/QSerialPortInfo>
- #include <QDateTime> // RX 诊断:记录最后一次收到字节的时刻
- #include <QStringList>
- #include <QString>
- #include <QByteArray>
- #include <QJsonDocument> // 组帧完整性校验(isBusinessFrame)
- #include <QJsonParseError>
- #include <QTextCodec>
- #include <QThread>
- #include <m_json.h>
- #include <QTimer>
- #include <QStandardPaths>
- #include <QStorageInfo>
- #include <QVideoFrame>
- #include <atomic>
- #include <mysql.h>
- #include <m_loger.h>
- #include <mcu_console.h>
- #include "lwjson/lwjson.h"
- #include "ymodem.h"
- class SerialThread: public QThread
- {
- Q_OBJECT
- public:
- // 数据缓存区
- QByteArray dataBuf;
- YMODEM* getYmodem(); // 声明 getter
- explicit SerialThread(QObject *parent = nullptr);
- ~SerialThread();
- void setSerialPortSettings(const QString &portName, QSerialPort::BaudRate baudRate,
- QSerialPort::DataBits dataBits, QSerialPort::Parity parity,
- QSerialPort::StopBits stopBits, QSerialPort::FlowControl flowControl);
- void init();
- void run() override;
- void stop();
- void SetLedState(bool sw){
- sendData(m_json.setLedState(sw));
- }
- Q_INVOKABLE void reboot(){
- sendData(m_json.CmdReboot());
- }
- QSerialPort& getSerialPort() {
- return m_serialPort;
- }
- Q_INVOKABLE void readBoardData();
- Q_INVOKABLE void uploadData_Mqtt(){
- m_dat_f.setInterval(0);
- };
- Q_INVOKABLE void update_dat_f_main(QString freq); //更新数据上传间隔
- Q_INVOKABLE void sendCmd(QString cmd_type,bool sw,QString setup,QString speed);
- Q_INVOKABLE QStringList pathinfo(){
- QStringList pf_pic;
- pf_pic.append(qst_dirPath);
- pf_pic.append(QString::number(int_fileCount));
- pf_pic.append(QString::number(int_totalSize/1048576));
- return pf_pic;
- }
- Q_INVOKABLE void readPathinfo(){
- analyzeDirectory(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
- }
- Q_INVOKABLE void removepic(){
- deleteAllFilesInDirectory(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
- }
- // ===== 存储空间循环覆写 =====
- // 归档图片最少保留的剩余空间:低于该值时删除最老的一组图片
- static constexpr qint64 kMinFreeSpace = 1073741824LL; // 1GB
- // 指定路径所在存储卷的剩余可用字节数
- static qint64 getFreeSpace(const QString &path = QString())
- {
- const QString target = path.isEmpty()
- ? QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)
- : path;
- QStorageInfo storage(target);
- if (storage.isValid() && storage.isReady())
- return storage.bytesAvailable();
- QStorageInfo fallback(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
- return (fallback.isValid() && fallback.isReady()) ? fallback.bytesAvailable() : 0;
- }
- // 循环覆写:剩余空间不足 minFree 时,按时间由旧到新逐组删除归档图片
- // (一组=一个归档目录,即 年/月/日/时间戳 下的时间戳目录),
- // 录制视频流(.rawv)不参与删除;返回实际释放的字节数
- static qint64 ensureStorageSpace(qint64 minFree = kMinFreeSpace)
- {
- const QString root = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
- qint64 freed = 0;
- if (getFreeSpace(root) >= minFree)
- return freed;
- LOG("存储空间不足{} MB,开始循环覆写", minFree / (1024.0 * 1024.0));
- QStringList groups;
- collectArchiveGroups(root, root, groups);
- groups.sort(); // 归档目录名即时间戳,排序后最前者即最老的一组
- int removedGroups = 0;
- for (const QString &group : groups) {
- if (getFreeSpace(root) >= minFree)
- break;
- const qint64 f = removeGroupFiles(group);
- if (f > 0) {
- freed += f;
- removedGroups++;
- LOG("循环覆写:删除最老一组 {}", group.toStdString());
- }
- }
- LOG("循环覆写结束:删除{}组,释放{} MB,剩余{} MB", removedGroups,
- freed / (1024.0 * 1024.0), getFreeSpace(root) / (1024.0 * 1024.0));
- return freed;
- }
- Q_INVOKABLE void setCollt(int sh1 ,int eh1,int sh2,int eh2,int sh3,int eh3){
- sendData(m_json.CmdParamconf(sh1,eh1,sh2,eh2,sh3,eh3));
- }
- Q_INVOKABLE void setCollt_min(int sh1 ,int eh1,int sh2,int eh2,int sh3,int eh3){
- sendData(m_json.CmdParamconf_min(sh1,eh1,sh2,eh2,sh3,eh3));
- }
- Q_INVOKABLE void setTempconf(int tpl ,int tph){
- sendData(m_json.CmdParamconf_temp(tpl,tph));
- }
- Q_INVOKABLE void setHt_xy_dis(int xdis ,int ydis){
- sendData(m_json.CmdParamconf_xy_dis(xdis,ydis));
- }
- Q_INVOKABLE void setLightness(int val){
- auto qtContext = QJniObject(QNativeInterface::QAndroidApplication::context()); //activity
- if (qtContext.isValid()) {
- QJniObject jClass("com/yfkj/bzyv1/Backlight");
- jClass.callMethod<void>("setScreenLight","(Landroid/content/Context;I)V",qtContext.object(),val);
- //jClass.callStaticMethod<void>("turnScreenOff", "()V");
- }
- #if 0
- if(val==-255){
- QJniObject::callStaticMethod<void>("GetUsbPermission",
- "turnScreenOff",
- "()V");
- }
- #endif
- }
- Q_INVOKABLE QString getId(){
- return param::imei;
- }
- Q_INVOKABLE QString getIccid(){
- return param::iccid;
- }
- Q_INVOKABLE QString getlat(){
- return param::gps_lat;
- }
- Q_INVOKABLE QString getlng(){
- return param::gps_lng;
- }
- //Android 面板 GNSS:海拔(m)/可视卫星数/已用卫星数,由 main.cpp GPSInfo 写入 param
- Q_INVOKABLE QString getElevation(){
- return param::gps_elevation;
- }
- Q_INVOKABLE QString getSatView(){
- return param::gps_sat_view;
- }
- Q_INVOKABLE QString getSatUsed(){
- return param::gps_sat_used;
- }
- Q_INVOKABLE QString get_app_version(){
- return APP_VERSION;
- }
- //MCU 调试日志采集状态(端口 / 落盘文件 / 已收字节数 / 是否在采):
- //现场排障用,QML: serial.mcuConsoleInfo()
- Q_INVOKABLE QString mcuConsoleInfo();
- //业务串口(ttyS3)接收诊断,QML: serial.serialRxInfo()
- //"发得出去、收不回来"时先看这句:bytes 是否在涨、帧数是否在涨
- Q_INVOKABLE QString serialRxInfo();
- //相机连接状态:测试页 Frames 打开/关闭/失败时回写,主页状态栏"相机状态"展示用。
- //放在 serial 这个常驻 context property 上,跨页面都能响应式读取
- Q_PROPERTY(bool cameraConnected READ cameraConnected WRITE setCameraConnected NOTIFY cameraConnectedChanged)
- bool cameraConnected() const { return m_cameraConnected; }
- void setCameraConnected(bool sta){
- if(m_cameraConnected == sta) return;
- m_cameraConnected = sta;
- emit cameraConnectedChanged(sta);
- }
- Q_INVOKABLE void makeJsonRpc(const QString &method,const QString &value)
- {
- sendData(m_json.MakeJsonRPC(method,value));
- }
- signals:
- void dataReceived(const QByteArray &data);
- void dataUpload(const QByteArray &data);
- void updatestart(QString filename);
- void auto_takephoto(bool sw);
- void takephotodone();
- //收到控制板 record_stop:停止录制并处理视频流(分析/融合/删除录制文件/上传融合图)
- void recordStop();
- void disconnect_485();
- void autotestdone();
- void translatedone();
- void netMessage(const QByteArray &data);
- void autoFocusDone();
- void autoFocusStart();
- void lwjsonStreamDONE(const QByteArray &data);
- void cameraConnectedChanged(bool sta);
- void signal_movy(const QString stepcount);
- void timeout_mov_stop();
- void gpsSuccess();
- void ymodemReady(QString mtype);
- void ymodemProgress(int val,int tval);
- void ymodemFinished(int res);
- public slots:
- void sendData(const QByteArray &data);
- void mqtttoserial(const QByteArray &data);
- void getmodemresult(int res);
- void startYmodem(const QString path);
- void startUpgrade(QString path)
- {
- if(!m_ymodem) return;
- //【防重复触发】主板可能重复上报 "system will update",或服务器/界面重复下发升级指令。
- // 升级期间第二次进来会打断正在传输的 ACK/'C' 交互,使主板收到的包头错位 ->
- // "Update firmware fail." -> 主板复位。这里用 exchange 做原子判定,重复的只记日志。
- if(m_upgrading.exchange(true)){
- LOG("升级已在进行中,忽略重复的升级指令:{}", path.toStdString());
- return;
- }
- m_ymodem->start_ymodem(path);
- }
- Q_INVOKABLE void recoverMcuParam();
- private slots:
- //void readBoardData();
- QString selectSerialPortName();
- void feedJsonParser(const QByteArray& data)
- {
- // ---- RX 统计(现场排障用,serial.serialRxInfo() 可读)----
- // m_rxBytes 一直不涨 → 端口上根本没有字节:接错口 / RX 线 / MCU 没发 / 被别的进程占了
- // m_rxBytes 涨、m_rxDones 不涨 → 字节到了但攒不出完整帧:脏字节、波特率偏差、干扰、解析器错位
- m_rxBytes += static_cast<quint64>(data.size());
- const qint64 nowMs = QDateTime::currentMSecsSinceEpoch();
- m_rxLastMs = nowMs;
- // ---- ①【2.8.70】帧超时自愈:帧尾丢了也不能一直等 ----
- // 帧尾被线路丢掉时 lwjson 可能一个错误都不报:下一帧的 '{' 会被当成还没结束的
- // primitive 继续吞,整帧静默消失,栈深度还越攒越深,永远等不到 STREAMDONE。
- // 离线实测(真实的 lwjson 1.8.1):把一帧最后 2 个 '}' 去掉、后面紧跟一整帧好帧,
- // 406 字节全部返回 STREAMINPROG —— 0 个错误、0 帧输出,且永不自愈。
- // 这正是现场"发得出去、收不回来,重发也没用"的形态,必须按时间兜底。
- if (!jsonBuf.isEmpty() && m_frameStartMs > 0
- && nowMs - m_frameStartMs > kFrameTimeoutMs) {
- dropRxFrame("帧超时", -1, jsonBuf);
- }
- for (uint8_t b : data) {
- const lwjsonr_t ret = lwjson_stream_parse(&lwparser, static_cast<char>(b));
- // 只在解析进行中或完成时跟踪字节,避免累积无关数据
- if (ret == lwjsonSTREAMINPROG || ret == lwjsonSTREAMDONE) {
- if (jsonBuf.isEmpty())
- m_frameStartMs = nowMs; // 帧首字节时刻,帧超时从这里开始算
- jsonBuf.append(static_cast<char>(b));
- }
- switch (ret){
- case lwjsonERRJSON: // 1, 无效的字符
- // ---- ②【2.8.70】出错必须复位解析器(2.8.69 这一行是被注释掉的)----
- // lwjson 出错后不会自己回到"等首字符",状态会一直错着。
- // 现场 2.8.69 那条 ":"0","rcnt":2,..." 就是这么来的:上一帧被截断
- // + 状态带毒,这一帧的后半截恰好语法自洽,于是被当成完整帧 emit 出去,
- // 业务层找不到 cmd 静默丢弃 → 界面表现"JSON 解析不完整/收不到数据"。
- // 帧外杂字节(jsonBuf 为空)不告警也不复位:此时解析器必然是干净状态。
- if (!jsonBuf.isEmpty())
- dropRxFrame("错码", static_cast<int>(b), jsonBuf);
- break;
- case lwjsonSTREAMWAITFIRSTCHAR: // 2, 等待首字符
- break;
- case lwjsonSTREAMINPROG: // 3, 正在解析中
- // 帧内丢了 '}' 时 jsonBuf 会跨帧累积,给一个上限把野状态收掉
- if (jsonBuf.size() > kMaxFrameBytes)
- dropRxFrame("超长", -1, jsonBuf);
- break;
- case lwjsonSTREAMDONE: { // 4, 解析已完成
- const QByteArray frame = jsonBuf; // 先留副本:复位会把 jsonBuf 清掉
- if (!frame.startsWith('{')) {
- // 顶层数组/标量不承载任何 cmd 流程(见 processJsonData),静默丢弃
- resetRxFrame();
- break;
- }
- // ---- ③【2.8.70】完整性闸门:语法完整 ≠ 这是一整帧 ----
- // 丢字节后报文后半截往往本身就是一个合法 JSON 对象(实测:丢掉
- // {"cmd":"data","ext": 之后,剩下的 {"dver":...} 完全合法)。
- // 只靠 lwjson 无法区分,必须校验协议键,否则残帧会流到 QML:
- // JSON.parse 成功但 ext 缺失 → 抛 TypeError / 显示错值。
- if (!isBusinessFrame(frame)) {
- dropRxFrame("残帧", -1, frame);
- break;
- }
- resetRxFrame();
- ++m_rxDones;
- // ---- ④【2.8.72】整帧落盘恢复(2.8.70 只打前 96 字节是错的)----
- // 96 字节正好切在 "...\"batSt" 上,与"帧在 batSt 处被截断"的历史症状
- // 一模一样,现场无法区分"解析成功"和"帧被截断",也看不到字段值可以核对。
- // 实际帧率只有 0.2 帧/秒(MCU 只在收到 synchronization 后回一帧),
- // 整帧落盘的开销可以忽略;只有超大帧才截断,且**显式标注省略了多少字节**,
- // 绝不做无声截断。
- if (frame.size() <= 1024) {
- LOG("RX 帧 {} 字节: {}", frame.size(), frame.constData());
- } else {
- const QByteArray head = frame.left(512);
- const QByteArray tail = frame.right(256);
- LOG("RX 帧 {} 字节(超长, 中间省略 {} 字节): {} …… {}",
- frame.size(), frame.size() - 768,
- head.constData(), tail.constData());
- }
- emit lwjsonStreamDONE(frame);
- break;
- }
- case lwjsonERRMEM: // 5, 嵌套的太深("LWJSON_CFG_STREAM_STACK_SIZE")
- ERROR("lwjsonERRMEM! 嵌套超过 LWJSON_CFG_STREAM_STACK_SIZE");
- dropRxFrame("嵌套过深", -1, jsonBuf);
- break;
- default: // 流式解析时, 其它的返回值, 都不应该出现
- ERROR("未知错误:{:d}",static_cast<int>(ret));
- resetRxFrame();
- break;
- }
- }
- }
- // 丢弃当前半帧:计数 + 限频告警 + 复位解析器。
- // 告警 5 秒限频(干扰严重时不刷屏),head/tail 用**十六进制**打印:
- // 之前用 constData() 打,遇到 0x00 会直接截断,等于把唯一的证据丢掉了
- // (现场那条坏帧的出错字节就是这么被藏起来的)。
- void dropRxFrame(const char* why, int badByte, const QByteArray& frame)
- {
- ++m_rxBadFrames;
- const qint64 nowMs = QDateTime::currentMSecsSinceEpoch();
- if (nowMs - m_badLogMs >= 5000) {
- m_badLogMs = nowMs;
- const QByteArray headHex = frame.left(64).toHex(' ');
- const QByteArray tailHex = frame.size() > 96 ? frame.right(32).toHex(' ')
- : QByteArrayLiteral("-");
- if (badByte >= 0) {
- WARN("RX 坏帧[{}]: 丢弃 {} 字节(累计坏帧 {}) 出错字节=0x{:02X} head={} tail={}",
- why, frame.size(), m_rxBadFrames.load(), badByte,
- headHex.constData(), tailHex.constData());
- } else {
- WARN("RX 坏帧[{}]: 丢弃 {} 字节(累计坏帧 {}) head={} tail={}",
- why, frame.size(), m_rxBadFrames.load(),
- headHex.constData(), tailHex.constData());
- }
- }
- resetRxFrame();
- }
- // 业务帧判定:顶层必须是对象,且带 cmd / method / jsonrpc 之一。
- // 用 QJsonDocument 而不是字符串 contains("cmd"):既校验语法,又不会把
- // 值里恰好出现 "cmd" 的残帧放过去(500 字节一帧,解析开销 ~20μs,可忽略)。
- static bool isBusinessFrame(const QByteArray& frame)
- {
- QJsonParseError err{};
- const QJsonDocument doc = QJsonDocument::fromJson(frame, &err);
- if (err.error != QJsonParseError::NoError || !doc.isObject())
- return false;
- const QJsonObject obj = doc.object();
- return obj.contains(QStringLiteral("cmd"))
- || obj.contains(QStringLiteral("method"))
- || obj.contains(QStringLiteral("jsonrpc"));
- }
- private:
- //【线程安全】串口线程主循环读它来决定是否暂停解析,升级流程在另一线程里置位,
- // 用 atomic 避免编译器把 while 里的读取提到循环外(或读到半写状态)。
- std::atomic<bool> m_upgrading{false};
- void processJsonData(const QByteArray &jsonData);
- void saveMcuParam(const QJsonObject ¶ms);
- //MCU 调试口日志(ttyS2):只读采集,开启即可,不再向 MCU 下发任何串口映射指令
- //(console 落在哪一路由 MCU 端自行维护,见 header/mcu_console.h)
- void startMcuConsoleLog();
- // ---- 下行发送队列(主线程 → 串口线程)----
- // QML 里点按钮/发指令时,主线程只负责入队;run() 在自己的循环里取出来写串口。
- // 这样既不会跨线程操作 QSerialPort,也能保证"点了就一定发出去"。
- void flushTxQueue();
- // 真正写串口:只允许在串口线程(run/flushTxQueue)里调用
- void writeToPort(const QByteArray &data);
- mutable QMutex m_txQueueMutex;
- QList<QByteArray> m_txQueue;
- QTimer m_dat_f;
- QTimer* timeout_mov = nullptr;
- QSerialPort m_serialPort;
- // ---- 业务串口(ttyS3) RX 诊断计数 ----
- // "发送正常、接收不到数据"必须能一眼区分是哪种:
- // m_rxBytes 不涨 → 端口上确实没有字节(接线/MCU 没发/驱动/被占用)
- // m_rxBytes 涨但帧数不涨 → 字节到了却攒不出完整 JSON(脏字节/波特率/干扰/解析器错位)
- std::atomic<quint64> m_rxBytes{0};
- std::atomic<quint64> m_rxDones{0};
- std::atomic<quint64> m_parseResets{0};
- std::atomic<quint64> m_rxBadFrames{0}; // 被丢弃的坏帧数(错码/残帧/超时/超长)
- std::atomic<qint64> m_rxLastMs{0};
- // 最近一次真正写出报文的时刻:RX 看门狗用它判断"是不是我们刚问过、
- // MCU 却没回"(MCU 是应答式的,没人问的时候它本来就不发,不能算故障)
- std::atomic<qint64> m_lastTxMs{0};
- //MCU 调试口采集(ttyS2):只读、独立线程,与 ttyS3 业务串口互不影响
- McuConsoleLog m_mcuConsole;
- //【崩溃修复】YMODEM* 必须在声明处初始化为 nullptr。
- // 原代码只写 `YMODEM *m_ymodem;`,是野指针(未初始化)。
- // run() 里 `m_ymodem = new YMODEM(...)` 是在**串口子线程**执行的,
- // 而 SerialThread 对象本身是在主线程构造的(main.cpp: `SerialThread serialThread;`),
- // 两者存在启动竞态:主线程若在 run() 赋值之前就通过
- // startUpgrade()/getYmodem() 走到 `m_ymodem->start_ymodem(...)`,
- // 就会解引用野指针 → SIGSEGV(fault addr 0x0)。
- YMODEM *m_ymodem = nullptr; // YMODEM对象
- SqliteOperator *sqlConfig = nullptr;
- mutable QMutex m_writeMutex;
- bool m_running;
- bool m_cameraConnected = false; //相机连接状态(见 cameraConnected 属性)
- //相机连接状态轮询:后台枚举海康相机,数量>0=已连接,=0=未连接
- QTimer m_camStaTimer;
- std::atomic<bool> m_camEnumBusy{false}; //上一轮枚举未完成时跳过本轮
- void pollCameraDevices(); //发起后台枚举,结果回UI线程更新属性
- bool data_upload;
- int connect_board; //主板串口连接状态
- JsonFunc m_json;
- QString qst_dirPath;
- int int_fileCount;
- qint64 int_totalSize;
- // 用于存储目录统计结果的结构体
- struct DirectoryStats {
- qint64 totalSize = 0;
- int fileCount = 0;
- };
- // ---- 业务串口(ttyS3) 组帧状态(lwjson 流式解析器,见 feedJsonParser)----
- lwjson_stream_parser_t lwparser; // 逐字节流式状态机,构造函数里 lwjson_stream_init
- QByteArray jsonBuf; // 当前帧累积区(STREAMINPROG/STREAMDONE 期间的字节)
- qint64 m_frameStartMs = 0; // 当前帧首字节时刻(0=当前没有半帧),帧超时判据
- qint64 m_badLogMs = 0; // 坏帧告警限频(只在串口线程访问,无需 atomic)
- // 单帧组装超时:正常一帧约 500 字节 @115200 ≈ 43ms,1.5s 已是"明显不正常",
- // 但不能更短 —— 采集/升级等场景下 MCU 分段发一帧时中间可能有秒级间隔。
- static constexpr qint64 kFrameTimeoutMs = 1500;
- // 单帧字节上限:帧内丢 '}' 时 jsonBuf 会跨帧累积,超过即判野状态
- static constexpr int kMaxFrameBytes = 4096;
- // 丢弃当前半帧并复位解析器。只在串口线程(feedJsonParser / run)里调用,不跨线程。
- // 【2.8.70】这里改用 lwjson_stream_init() 而不是 lwjson_stream_reset():
- // reset 只清 parse_state / stack_pos,**不清 prev_c**;若上一个成功处理的字节是
- // '\\',残留的 prev_c 会让下一帧起始的 '"' 被当成字符串内容,整帧错位。
- // init() 是 memset 整个结构(约 1KB),只在丢帧时调用,开销可忽略。
- void resetRxFrame()
- {
- jsonBuf.clear();
- m_frameStartMs = 0;
- lwjson_stream_init(&lwparser, nullptr);
- }
- // 递归收集"一组图片"的归档目录(叶子目录,即时间戳目录)
- static void collectArchiveGroups(const QString &rootPath, const QString &directoryPath, QStringList &groups)
- {
- QDir directory(directoryPath);
- if (!directory.exists())
- return;
- bool hasFile = false;
- QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
- foreach (const QFileInfo &fileInfo, fileInfoList) {
- if (fileInfo.isDir())
- collectArchiveGroups(rootPath, fileInfo.filePath(), groups);
- else
- hasFile = true;
- }
- // 根目录本身不算一组(只清理归档子目录)
- if (hasFile && directory.absolutePath() != QDir(rootPath).absolutePath())
- groups.append(directory.absolutePath());
- }
- // 删除一组归档目录中的图片(保留 .rawv 录制视频流),空目录一并移除;返回释放的字节数
- static qint64 removeGroupFiles(const QString &directoryPath)
- {
- qint64 freed = 0;
- QDir directory(directoryPath);
- if (!directory.exists())
- return freed;
- QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
- foreach (const QFileInfo &fileInfo, fileInfoList) {
- if (fileInfo.isDir()) {
- freed += removeGroupFiles(fileInfo.filePath());
- // 空目录才删除成功,含保留视频流的目录会保留
- QDir().rmdir(fileInfo.filePath());
- } else if (fileInfo.suffix().compare(QStringLiteral("rawv"), Qt::CaseInsensitive) != 0) {
- const qint64 size = fileInfo.size();
- if (QFile::remove(fileInfo.filePath()))
- freed += size;
- }
- }
- return freed;
- }
- void deleteAllFilesInDirectory(const QString &directoryPath)
- {
- QDir directory(directoryPath);
- if (!directory.exists()) {
- LOG("Directory does not exist.");
- return;
- }
- QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
- foreach (const QFileInfo &fileInfo, fileInfoList) {
- if (fileInfo.isDir()) {
- // 递归删除子目录中的文件
- deleteAllFilesInDirectory(fileInfo.filePath());
- } else {
- // 删除文件
- QFile::remove(fileInfo.filePath());
- }
- }
- analyzeDirectory(directoryPath);
- }
- // 递归获取目录统计信息
- DirectoryStats getDirectoryStats(const QString &directoryPath)
- {
- QDir directory(directoryPath);
- DirectoryStats stats;
- if (!directory.exists()) {
- LOG("Directory does not exist.");
- }
- qint64 totalSize = 0;
- int fileCount = 0;
- QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
- foreach (const QFileInfo &fileInfo, fileInfoList) {
- if (fileInfo.isDir()) {
- // 递归获取子目录的统计信息
- DirectoryStats subStats = getDirectoryStats(fileInfo.filePath());
- stats.fileCount += subStats.fileCount;
- stats.totalSize += subStats.totalSize;
- } else {
- stats.fileCount++;
- stats.totalSize += fileInfo.size();
- }
- }
- return stats;
- qst_dirPath = directoryPath;
- int_fileCount = fileCount;
- int_totalSize = totalSize;
- LOG("Directory:{}",directoryPath.toStdString());
- LOG("File count:{}",fileCount);
- LOG("Total size:{} bytes",totalSize);
- }
- // 使用示例
- void analyzeDirectory(const QString &directoryPath) {
- LOG("Analyzing directory: {}", directoryPath.toStdString());
- DirectoryStats stats = getDirectoryStats(directoryPath);
- qst_dirPath = directoryPath;
- int_fileCount = stats.fileCount;
- int_totalSize = stats.totalSize;
- LOG("Total files:{}",int_totalSize);
- LOG("Total size:{} MB",stats.totalSize / (1024.0 * 1024.0));
- }
- };
- #endif // MSEIAL_H
|