#ifndef MSEIAL_H #define MSEIAL_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #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/cb/Q6iot/Backlight"); jClass.callMethod("setScreenLight","(Landroid/content/Context;I)V",qtContext.object(),val); //jClass.callStaticMethod("turnScreenOff", "()V"); } #if 0 if(val==-255){ QJniObject::callStaticMethod("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; } //相机连接状态:测试页 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){ m_upgrading = true; m_ymodem->start_ymodem(path); } } Q_INVOKABLE void recoverMcuParam(); private slots: //void readBoardData(); QString selectSerialPortName(); void feedJsonParser(const QByteArray& data) { for (uint8_t b : data) { lwjsonr_t ret = lwjson_stream_parse(&lwparser, b); // 只在解析进行中或完成时跟踪字节,避免累积无关数据 if (ret == lwjsonSTREAMINPROG || ret == lwjsonSTREAMDONE) { jsonBuf.append(static_cast(b)); } switch (ret){ case lwjsonERRJSON: // 1, 无效的字符 jsonBuf.clear(); break; case lwjsonSTREAMWAITFIRSTCHAR: // 2, 等待首字符 break; case lwjsonSTREAMINPROG: // 3, 正在解析中 break; case lwjsonSTREAMDONE: // 4, 解析已完成 LOG("lwjsonSTREAMDONE:{}",jsonBuf.constData()); emit lwjsonStreamDONE(jsonBuf); jsonBuf.clear(); lwjson_stream_reset(&lwparser); break; case lwjsonERRMEM: // 5, 嵌套的太深("LWJSON_CFG_STREAM_STACK_SIZE") ERROR("lwjsonERRMEM!"); jsonBuf.clear(); lwjson_stream_reset(&lwparser); break; default: // 流式解析时, 其它的返回值, 都不应该出现 ERROR("未知错误:{:d}",static_cast(ret)); break; } } } private: //【线程安全】串口线程主循环读它来决定是否暂停解析,升级流程在另一线程里置位, // 用 atomic 避免编译器把 while 里的读取提到循环外(或读到半写状态)。 std::atomic m_upgrading{false}; void processJsonData(const QByteArray &jsonData); void saveMcuParam(const QJsonObject ¶ms); QTimer m_dat_f; QTimer* timeout_mov = nullptr; QSerialPort m_serialPort; YMODEM *m_ymodem; // YMODEM对象 SqliteOperator *sqlConfig; mutable QMutex m_writeMutex; bool m_running; bool m_cameraConnected = false; //相机连接状态(见 cameraConnected 属性) //相机连接状态轮询:后台枚举海康相机,数量>0=已连接,=0=未连接 QTimer m_camStaTimer; std::atomic 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; }; lwjson_stream_parser_t lwparser; QByteArray jsonBuf; // 递归收集"一组图片"的归档目录(叶子目录,即时间戳目录) 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