mserial.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. #ifndef MSEIAL_H
  2. #define MSEIAL_H
  3. #include <QObject>
  4. #include <QtSerialPort/QSerialPort>
  5. #include <QtSerialPort/QSerialPortInfo>
  6. #include <QStringList>
  7. #include <QString>
  8. #include <QByteArray>
  9. #include <QTextCodec>
  10. #include <QThread>
  11. #include <m_json.h>
  12. #include <QTimer>
  13. #include <QStandardPaths>
  14. #include <QStorageInfo>
  15. #include <QVideoFrame>
  16. #include <mysql.h>
  17. #include <m_loger.h>
  18. #include "lwjson/lwjson.h"
  19. #include "ymodem.h"
  20. class SerialThread: public QThread
  21. {
  22. Q_OBJECT
  23. public:
  24. // 数据缓存区
  25. QByteArray dataBuf;
  26. YMODEM* getYmodem(); // 声明 getter
  27. explicit SerialThread(QObject *parent = nullptr);
  28. ~SerialThread();
  29. void setSerialPortSettings(const QString &portName, QSerialPort::BaudRate baudRate,
  30. QSerialPort::DataBits dataBits, QSerialPort::Parity parity,
  31. QSerialPort::StopBits stopBits, QSerialPort::FlowControl flowControl);
  32. void init();
  33. void run() override;
  34. void stop();
  35. void SetLedState(bool sw){
  36. sendData(m_json.setLedState(sw));
  37. }
  38. Q_INVOKABLE void reboot(){
  39. sendData(m_json.CmdReboot());
  40. }
  41. QSerialPort& getSerialPort() {
  42. return m_serialPort;
  43. }
  44. Q_INVOKABLE void readBoardData();
  45. Q_INVOKABLE void uploadData_Mqtt(){
  46. m_dat_f.setInterval(0);
  47. };
  48. Q_INVOKABLE void update_dat_f_main(QString freq); //更新数据上传间隔
  49. Q_INVOKABLE void sendCmd(QString cmd_type,bool sw,QString setup,QString speed);
  50. Q_INVOKABLE QStringList pathinfo(){
  51. QStringList pf_pic;
  52. pf_pic.append(qst_dirPath);
  53. pf_pic.append(QString::number(int_fileCount));
  54. pf_pic.append(QString::number(int_totalSize/1048576));
  55. return pf_pic;
  56. }
  57. Q_INVOKABLE void readPathinfo(){
  58. analyzeDirectory(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
  59. }
  60. Q_INVOKABLE void removepic(){
  61. deleteAllFilesInDirectory(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
  62. }
  63. // ===== 存储空间循环覆写 =====
  64. // 归档图片最少保留的剩余空间:低于该值时删除最老的一组图片
  65. static constexpr qint64 kMinFreeSpace = 1073741824LL; // 1GB
  66. // 指定路径所在存储卷的剩余可用字节数
  67. static qint64 getFreeSpace(const QString &path = QString())
  68. {
  69. const QString target = path.isEmpty()
  70. ? QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)
  71. : path;
  72. QStorageInfo storage(target);
  73. if (storage.isValid() && storage.isReady())
  74. return storage.bytesAvailable();
  75. QStorageInfo fallback(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
  76. return (fallback.isValid() && fallback.isReady()) ? fallback.bytesAvailable() : 0;
  77. }
  78. // 循环覆写:剩余空间不足 minFree 时,按时间由旧到新逐组删除归档图片
  79. // (一组=一个归档目录,即 年/月/日/时间戳 下的时间戳目录),
  80. // 录制视频流(.rawv)不参与删除;返回实际释放的字节数
  81. static qint64 ensureStorageSpace(qint64 minFree = kMinFreeSpace)
  82. {
  83. const QString root = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
  84. qint64 freed = 0;
  85. if (getFreeSpace(root) >= minFree)
  86. return freed;
  87. LOG("存储空间不足{} MB,开始循环覆写", minFree / (1024.0 * 1024.0));
  88. QStringList groups;
  89. collectArchiveGroups(root, root, groups);
  90. groups.sort(); // 归档目录名即时间戳,排序后最前者即最老的一组
  91. int removedGroups = 0;
  92. for (const QString &group : groups) {
  93. if (getFreeSpace(root) >= minFree)
  94. break;
  95. const qint64 f = removeGroupFiles(group);
  96. if (f > 0) {
  97. freed += f;
  98. removedGroups++;
  99. LOG("循环覆写:删除最老一组 {}", group.toStdString());
  100. }
  101. }
  102. LOG("循环覆写结束:删除{}组,释放{} MB,剩余{} MB", removedGroups,
  103. freed / (1024.0 * 1024.0), getFreeSpace(root) / (1024.0 * 1024.0));
  104. return freed;
  105. }
  106. Q_INVOKABLE void setCollt(int sh1 ,int eh1,int sh2,int eh2,int sh3,int eh3){
  107. sendData(m_json.CmdParamconf(sh1,eh1,sh2,eh2,sh3,eh3));
  108. }
  109. Q_INVOKABLE void setCollt_min(int sh1 ,int eh1,int sh2,int eh2,int sh3,int eh3){
  110. sendData(m_json.CmdParamconf_min(sh1,eh1,sh2,eh2,sh3,eh3));
  111. }
  112. Q_INVOKABLE void setTempconf(int tpl ,int tph){
  113. sendData(m_json.CmdParamconf_temp(tpl,tph));
  114. }
  115. Q_INVOKABLE void setHt_xy_dis(int xdis ,int ydis){
  116. sendData(m_json.CmdParamconf_xy_dis(xdis,ydis));
  117. }
  118. Q_INVOKABLE void setLightness(int val){
  119. auto qtContext = QJniObject(QNativeInterface::QAndroidApplication::context()); //activity
  120. if (qtContext.isValid()) {
  121. QJniObject jClass("com/yfkj/cb/Q6iot/Backlight");
  122. jClass.callMethod<void>("setScreenLight","(Landroid/content/Context;I)V",qtContext.object(),val);
  123. //jClass.callStaticMethod<void>("turnScreenOff", "()V");
  124. }
  125. #if 0
  126. if(val==-255){
  127. QJniObject::callStaticMethod<void>("GetUsbPermission",
  128. "turnScreenOff",
  129. "()V");
  130. }
  131. #endif
  132. }
  133. Q_INVOKABLE QString getId(){
  134. return param::imei;
  135. }
  136. Q_INVOKABLE QString getIccid(){
  137. return param::iccid;
  138. }
  139. Q_INVOKABLE QString getlat(){
  140. return param::gps_lat;
  141. }
  142. Q_INVOKABLE QString getlng(){
  143. return param::gps_lng;
  144. }
  145. Q_INVOKABLE QString get_app_version(){
  146. return APP_VERSION;
  147. }
  148. Q_INVOKABLE void makeJsonRpc(const QString &method,const QString &value)
  149. {
  150. sendData(m_json.MakeJsonRPC(method,value));
  151. }
  152. signals:
  153. void dataReceived(const QByteArray &data);
  154. void dataUpload(const QByteArray &data);
  155. void updatestart(QString filename);
  156. void auto_takephoto(bool sw);
  157. void takephotodone();
  158. //收到控制板 record_stop:停止录制并处理视频流(分析/融合/删除录制文件/上传融合图)
  159. void recordStop();
  160. void disconnect_485();
  161. void autotestdone();
  162. void translatedone();
  163. void netMessage(const QByteArray &data);
  164. void autoFocusDone();
  165. void autoFocusStart();
  166. void lwjsonStreamDONE(const QByteArray &data);
  167. void signal_movy(const QString stepcount);
  168. void timeout_mov_stop();
  169. void gpsSuccess();
  170. void ymodemReady(QString mtype);
  171. void ymodemProgress(int val,int tval);
  172. void ymodemFinished(int res);
  173. public slots:
  174. void sendData(const QByteArray &data);
  175. void mqtttoserial(const QByteArray &data);
  176. void getmodemresult(int res);
  177. void startYmodem(const QString path);
  178. void startUpgrade(QString path)
  179. {
  180. if(m_ymodem){
  181. m_upgrading = true;
  182. m_ymodem->start_ymodem(path);
  183. }
  184. }
  185. Q_INVOKABLE void recoverMcuParam();
  186. private slots:
  187. //void readBoardData();
  188. QString selectSerialPortName();
  189. void feedJsonParser(const QByteArray& data)
  190. {
  191. for (uint8_t b : data) {
  192. lwjsonr_t ret = lwjson_stream_parse(&lwparser, b);
  193. // 只在解析进行中或完成时跟踪字节,避免累积无关数据
  194. if (ret == lwjsonSTREAMINPROG || ret == lwjsonSTREAMDONE) {
  195. jsonBuf.append(static_cast<char>(b));
  196. }
  197. switch (ret){
  198. case lwjsonERRJSON: // 1, 无效的字符
  199. jsonBuf.clear();
  200. break;
  201. case lwjsonSTREAMWAITFIRSTCHAR: // 2, 等待首字符
  202. break;
  203. case lwjsonSTREAMINPROG: // 3, 正在解析中
  204. break;
  205. case lwjsonSTREAMDONE: // 4, 解析已完成
  206. LOG("lwjsonSTREAMDONE:{}",jsonBuf.constData());
  207. emit lwjsonStreamDONE(jsonBuf);
  208. jsonBuf.clear();
  209. lwjson_stream_reset(&lwparser);
  210. break;
  211. case lwjsonERRMEM: // 5, 嵌套的太深("LWJSON_CFG_STREAM_STACK_SIZE")
  212. ERROR("lwjsonERRMEM!");
  213. jsonBuf.clear();
  214. lwjson_stream_reset(&lwparser);
  215. break;
  216. default: // 流式解析时, 其它的返回值, 都不应该出现
  217. ERROR("未知错误:{:d}",static_cast<int>(ret));
  218. break;
  219. }
  220. }
  221. }
  222. private:
  223. bool m_upgrading = false;
  224. void processJsonData(const QByteArray &jsonData);
  225. void saveMcuParam(const QJsonObject &params);
  226. QTimer m_dat_f;
  227. QTimer* timeout_mov = nullptr;
  228. QSerialPort m_serialPort;
  229. YMODEM *m_ymodem; // YMODEM对象
  230. SqliteOperator *sqlConfig;
  231. mutable QMutex m_writeMutex;
  232. bool m_running;
  233. bool data_upload;
  234. int connect_board; //主板串口连接状态
  235. JsonFunc m_json;
  236. QString qst_dirPath;
  237. int int_fileCount;
  238. qint64 int_totalSize;
  239. // 用于存储目录统计结果的结构体
  240. struct DirectoryStats {
  241. qint64 totalSize = 0;
  242. int fileCount = 0;
  243. };
  244. lwjson_stream_parser_t lwparser;
  245. QByteArray jsonBuf;
  246. // 递归收集"一组图片"的归档目录(叶子目录,即时间戳目录)
  247. static void collectArchiveGroups(const QString &rootPath, const QString &directoryPath, QStringList &groups)
  248. {
  249. QDir directory(directoryPath);
  250. if (!directory.exists())
  251. return;
  252. bool hasFile = false;
  253. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  254. foreach (const QFileInfo &fileInfo, fileInfoList) {
  255. if (fileInfo.isDir())
  256. collectArchiveGroups(rootPath, fileInfo.filePath(), groups);
  257. else
  258. hasFile = true;
  259. }
  260. // 根目录本身不算一组(只清理归档子目录)
  261. if (hasFile && directory.absolutePath() != QDir(rootPath).absolutePath())
  262. groups.append(directory.absolutePath());
  263. }
  264. // 删除一组归档目录中的图片(保留 .rawv 录制视频流),空目录一并移除;返回释放的字节数
  265. static qint64 removeGroupFiles(const QString &directoryPath)
  266. {
  267. qint64 freed = 0;
  268. QDir directory(directoryPath);
  269. if (!directory.exists())
  270. return freed;
  271. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  272. foreach (const QFileInfo &fileInfo, fileInfoList) {
  273. if (fileInfo.isDir()) {
  274. freed += removeGroupFiles(fileInfo.filePath());
  275. // 空目录才删除成功,含保留视频流的目录会保留
  276. QDir().rmdir(fileInfo.filePath());
  277. } else if (fileInfo.suffix().compare(QStringLiteral("rawv"), Qt::CaseInsensitive) != 0) {
  278. const qint64 size = fileInfo.size();
  279. if (QFile::remove(fileInfo.filePath()))
  280. freed += size;
  281. }
  282. }
  283. return freed;
  284. }
  285. void deleteAllFilesInDirectory(const QString &directoryPath)
  286. {
  287. QDir directory(directoryPath);
  288. if (!directory.exists()) {
  289. LOG("Directory does not exist.");
  290. return;
  291. }
  292. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  293. foreach (const QFileInfo &fileInfo, fileInfoList) {
  294. if (fileInfo.isDir()) {
  295. // 递归删除子目录中的文件
  296. deleteAllFilesInDirectory(fileInfo.filePath());
  297. } else {
  298. // 删除文件
  299. QFile::remove(fileInfo.filePath());
  300. }
  301. }
  302. analyzeDirectory(directoryPath);
  303. }
  304. // 递归获取目录统计信息
  305. DirectoryStats getDirectoryStats(const QString &directoryPath)
  306. {
  307. QDir directory(directoryPath);
  308. DirectoryStats stats;
  309. if (!directory.exists()) {
  310. LOG("Directory does not exist.");
  311. }
  312. qint64 totalSize = 0;
  313. int fileCount = 0;
  314. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  315. foreach (const QFileInfo &fileInfo, fileInfoList) {
  316. if (fileInfo.isDir()) {
  317. // 递归获取子目录的统计信息
  318. DirectoryStats subStats = getDirectoryStats(fileInfo.filePath());
  319. stats.fileCount += subStats.fileCount;
  320. stats.totalSize += subStats.totalSize;
  321. } else {
  322. stats.fileCount++;
  323. stats.totalSize += fileInfo.size();
  324. }
  325. }
  326. return stats;
  327. qst_dirPath = directoryPath;
  328. int_fileCount = fileCount;
  329. int_totalSize = totalSize;
  330. LOG("Directory:{}",directoryPath.toStdString());
  331. LOG("File count:{}",fileCount);
  332. LOG("Total size:{} bytes",totalSize);
  333. }
  334. // 使用示例
  335. void analyzeDirectory(const QString &directoryPath) {
  336. LOG("Analyzing directory: {}", directoryPath.toStdString());
  337. DirectoryStats stats = getDirectoryStats(directoryPath);
  338. qst_dirPath = directoryPath;
  339. int_fileCount = stats.fileCount;
  340. int_totalSize = stats.totalSize;
  341. LOG("Total files:{}",int_totalSize);
  342. LOG("Total size:{} MB",stats.totalSize / (1024.0 * 1024.0));
  343. }
  344. };
  345. #endif // MSEIAL_H