mserial.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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 <atomic>
  17. #include <mysql.h>
  18. #include <m_loger.h>
  19. #include "lwjson/lwjson.h"
  20. #include "ymodem.h"
  21. class SerialThread: public QThread
  22. {
  23. Q_OBJECT
  24. public:
  25. // 数据缓存区
  26. QByteArray dataBuf;
  27. YMODEM* getYmodem(); // 声明 getter
  28. explicit SerialThread(QObject *parent = nullptr);
  29. ~SerialThread();
  30. void setSerialPortSettings(const QString &portName, QSerialPort::BaudRate baudRate,
  31. QSerialPort::DataBits dataBits, QSerialPort::Parity parity,
  32. QSerialPort::StopBits stopBits, QSerialPort::FlowControl flowControl);
  33. void init();
  34. void run() override;
  35. void stop();
  36. void SetLedState(bool sw){
  37. sendData(m_json.setLedState(sw));
  38. }
  39. Q_INVOKABLE void reboot(){
  40. sendData(m_json.CmdReboot());
  41. }
  42. QSerialPort& getSerialPort() {
  43. return m_serialPort;
  44. }
  45. Q_INVOKABLE void readBoardData();
  46. Q_INVOKABLE void uploadData_Mqtt(){
  47. m_dat_f.setInterval(0);
  48. };
  49. Q_INVOKABLE void update_dat_f_main(QString freq); //更新数据上传间隔
  50. Q_INVOKABLE void sendCmd(QString cmd_type,bool sw,QString setup,QString speed);
  51. Q_INVOKABLE QStringList pathinfo(){
  52. QStringList pf_pic;
  53. pf_pic.append(qst_dirPath);
  54. pf_pic.append(QString::number(int_fileCount));
  55. pf_pic.append(QString::number(int_totalSize/1048576));
  56. return pf_pic;
  57. }
  58. Q_INVOKABLE void readPathinfo(){
  59. analyzeDirectory(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
  60. }
  61. Q_INVOKABLE void removepic(){
  62. deleteAllFilesInDirectory(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
  63. }
  64. // ===== 存储空间循环覆写 =====
  65. // 归档图片最少保留的剩余空间:低于该值时删除最老的一组图片
  66. static constexpr qint64 kMinFreeSpace = 1073741824LL; // 1GB
  67. // 指定路径所在存储卷的剩余可用字节数
  68. static qint64 getFreeSpace(const QString &path = QString())
  69. {
  70. const QString target = path.isEmpty()
  71. ? QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)
  72. : path;
  73. QStorageInfo storage(target);
  74. if (storage.isValid() && storage.isReady())
  75. return storage.bytesAvailable();
  76. QStorageInfo fallback(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
  77. return (fallback.isValid() && fallback.isReady()) ? fallback.bytesAvailable() : 0;
  78. }
  79. // 循环覆写:剩余空间不足 minFree 时,按时间由旧到新逐组删除归档图片
  80. // (一组=一个归档目录,即 年/月/日/时间戳 下的时间戳目录),
  81. // 录制视频流(.rawv)不参与删除;返回实际释放的字节数
  82. static qint64 ensureStorageSpace(qint64 minFree = kMinFreeSpace)
  83. {
  84. const QString root = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
  85. qint64 freed = 0;
  86. if (getFreeSpace(root) >= minFree)
  87. return freed;
  88. LOG("存储空间不足{} MB,开始循环覆写", minFree / (1024.0 * 1024.0));
  89. QStringList groups;
  90. collectArchiveGroups(root, root, groups);
  91. groups.sort(); // 归档目录名即时间戳,排序后最前者即最老的一组
  92. int removedGroups = 0;
  93. for (const QString &group : groups) {
  94. if (getFreeSpace(root) >= minFree)
  95. break;
  96. const qint64 f = removeGroupFiles(group);
  97. if (f > 0) {
  98. freed += f;
  99. removedGroups++;
  100. LOG("循环覆写:删除最老一组 {}", group.toStdString());
  101. }
  102. }
  103. LOG("循环覆写结束:删除{}组,释放{} MB,剩余{} MB", removedGroups,
  104. freed / (1024.0 * 1024.0), getFreeSpace(root) / (1024.0 * 1024.0));
  105. return freed;
  106. }
  107. Q_INVOKABLE void setCollt(int sh1 ,int eh1,int sh2,int eh2,int sh3,int eh3){
  108. sendData(m_json.CmdParamconf(sh1,eh1,sh2,eh2,sh3,eh3));
  109. }
  110. Q_INVOKABLE void setCollt_min(int sh1 ,int eh1,int sh2,int eh2,int sh3,int eh3){
  111. sendData(m_json.CmdParamconf_min(sh1,eh1,sh2,eh2,sh3,eh3));
  112. }
  113. Q_INVOKABLE void setTempconf(int tpl ,int tph){
  114. sendData(m_json.CmdParamconf_temp(tpl,tph));
  115. }
  116. Q_INVOKABLE void setHt_xy_dis(int xdis ,int ydis){
  117. sendData(m_json.CmdParamconf_xy_dis(xdis,ydis));
  118. }
  119. Q_INVOKABLE void setLightness(int val){
  120. auto qtContext = QJniObject(QNativeInterface::QAndroidApplication::context()); //activity
  121. if (qtContext.isValid()) {
  122. QJniObject jClass("com/yfkj/bzyv1/Backlight");
  123. jClass.callMethod<void>("setScreenLight","(Landroid/content/Context;I)V",qtContext.object(),val);
  124. //jClass.callStaticMethod<void>("turnScreenOff", "()V");
  125. }
  126. #if 0
  127. if(val==-255){
  128. QJniObject::callStaticMethod<void>("GetUsbPermission",
  129. "turnScreenOff",
  130. "()V");
  131. }
  132. #endif
  133. }
  134. Q_INVOKABLE QString getId(){
  135. return param::imei;
  136. }
  137. Q_INVOKABLE QString getIccid(){
  138. return param::iccid;
  139. }
  140. Q_INVOKABLE QString getlat(){
  141. return param::gps_lat;
  142. }
  143. Q_INVOKABLE QString getlng(){
  144. return param::gps_lng;
  145. }
  146. //Android 面板 GNSS:海拔(m)/可视卫星数/已用卫星数,由 main.cpp GPSInfo 写入 param
  147. Q_INVOKABLE QString getElevation(){
  148. return param::gps_elevation;
  149. }
  150. Q_INVOKABLE QString getSatView(){
  151. return param::gps_sat_view;
  152. }
  153. Q_INVOKABLE QString getSatUsed(){
  154. return param::gps_sat_used;
  155. }
  156. Q_INVOKABLE QString get_app_version(){
  157. return APP_VERSION;
  158. }
  159. //相机连接状态:测试页 Frames 打开/关闭/失败时回写,主页状态栏"相机状态"展示用。
  160. //放在 serial 这个常驻 context property 上,跨页面都能响应式读取
  161. Q_PROPERTY(bool cameraConnected READ cameraConnected WRITE setCameraConnected NOTIFY cameraConnectedChanged)
  162. bool cameraConnected() const { return m_cameraConnected; }
  163. void setCameraConnected(bool sta){
  164. if(m_cameraConnected == sta) return;
  165. m_cameraConnected = sta;
  166. emit cameraConnectedChanged(sta);
  167. }
  168. Q_INVOKABLE void makeJsonRpc(const QString &method,const QString &value)
  169. {
  170. sendData(m_json.MakeJsonRPC(method,value));
  171. }
  172. signals:
  173. void dataReceived(const QByteArray &data);
  174. void dataUpload(const QByteArray &data);
  175. void updatestart(QString filename);
  176. void auto_takephoto(bool sw);
  177. void takephotodone();
  178. //收到控制板 record_stop:停止录制并处理视频流(分析/融合/删除录制文件/上传融合图)
  179. void recordStop();
  180. void disconnect_485();
  181. void autotestdone();
  182. void translatedone();
  183. void netMessage(const QByteArray &data);
  184. void autoFocusDone();
  185. void autoFocusStart();
  186. void lwjsonStreamDONE(const QByteArray &data);
  187. void cameraConnectedChanged(bool sta);
  188. void signal_movy(const QString stepcount);
  189. void timeout_mov_stop();
  190. void gpsSuccess();
  191. void ymodemReady(QString mtype);
  192. void ymodemProgress(int val,int tval);
  193. void ymodemFinished(int res);
  194. public slots:
  195. void sendData(const QByteArray &data);
  196. void mqtttoserial(const QByteArray &data);
  197. void getmodemresult(int res);
  198. void startYmodem(const QString path);
  199. void startUpgrade(QString path)
  200. {
  201. if(!m_ymodem) return;
  202. //【防重复触发】主板可能重复上报 "system will update",或服务器/界面重复下发升级指令。
  203. // 升级期间第二次进来会打断正在传输的 ACK/'C' 交互,使主板收到的包头错位 ->
  204. // "Update firmware fail." -> 主板复位。这里用 exchange 做原子判定,重复的只记日志。
  205. if(m_upgrading.exchange(true)){
  206. LOG("升级已在进行中,忽略重复的升级指令:{}", path.toStdString());
  207. return;
  208. }
  209. m_ymodem->start_ymodem(path);
  210. }
  211. Q_INVOKABLE void recoverMcuParam();
  212. private slots:
  213. //void readBoardData();
  214. QString selectSerialPortName();
  215. void feedJsonParser(const QByteArray& data)
  216. {
  217. for (uint8_t b : data) {
  218. lwjsonr_t ret = lwjson_stream_parse(&lwparser, b);
  219. // 只在解析进行中或完成时跟踪字节,避免累积无关数据
  220. if (ret == lwjsonSTREAMINPROG || ret == lwjsonSTREAMDONE) {
  221. jsonBuf.append(static_cast<char>(b));
  222. }
  223. switch (ret){
  224. case lwjsonERRJSON: // 1, 无效的字符
  225. jsonBuf.clear();
  226. break;
  227. case lwjsonSTREAMWAITFIRSTCHAR: // 2, 等待首字符
  228. break;
  229. case lwjsonSTREAMINPROG: // 3, 正在解析中
  230. break;
  231. case lwjsonSTREAMDONE: // 4, 解析已完成
  232. LOG("lwjsonSTREAMDONE:{}",jsonBuf.constData());
  233. emit lwjsonStreamDONE(jsonBuf);
  234. jsonBuf.clear();
  235. lwjson_stream_reset(&lwparser);
  236. break;
  237. case lwjsonERRMEM: // 5, 嵌套的太深("LWJSON_CFG_STREAM_STACK_SIZE")
  238. ERROR("lwjsonERRMEM!");
  239. jsonBuf.clear();
  240. lwjson_stream_reset(&lwparser);
  241. break;
  242. default: // 流式解析时, 其它的返回值, 都不应该出现
  243. ERROR("未知错误:{:d}",static_cast<int>(ret));
  244. break;
  245. }
  246. }
  247. }
  248. private:
  249. //【线程安全】串口线程主循环读它来决定是否暂停解析,升级流程在另一线程里置位,
  250. // 用 atomic 避免编译器把 while 里的读取提到循环外(或读到半写状态)。
  251. std::atomic<bool> m_upgrading{false};
  252. void processJsonData(const QByteArray &jsonData);
  253. void saveMcuParam(const QJsonObject &params);
  254. QTimer m_dat_f;
  255. QTimer* timeout_mov = nullptr;
  256. QSerialPort m_serialPort;
  257. //【崩溃修复】YMODEM* 必须在声明处初始化为 nullptr。
  258. // 原代码只写 `YMODEM *m_ymodem;`,是野指针(未初始化)。
  259. // run() 里 `m_ymodem = new YMODEM(...)` 是在**串口子线程**执行的,
  260. // 而 SerialThread 对象本身是在主线程构造的(main.cpp: `SerialThread serialThread;`),
  261. // 两者存在启动竞态:主线程若在 run() 赋值之前就通过
  262. // startUpgrade()/getYmodem() 走到 `m_ymodem->start_ymodem(...)`,
  263. // 就会解引用野指针 → SIGSEGV(fault addr 0x0)。
  264. YMODEM *m_ymodem = nullptr; // YMODEM对象
  265. SqliteOperator *sqlConfig = nullptr;
  266. mutable QMutex m_writeMutex;
  267. bool m_running;
  268. bool m_cameraConnected = false; //相机连接状态(见 cameraConnected 属性)
  269. //相机连接状态轮询:后台枚举海康相机,数量>0=已连接,=0=未连接
  270. QTimer m_camStaTimer;
  271. std::atomic<bool> m_camEnumBusy{false}; //上一轮枚举未完成时跳过本轮
  272. void pollCameraDevices(); //发起后台枚举,结果回UI线程更新属性
  273. bool data_upload;
  274. int connect_board; //主板串口连接状态
  275. JsonFunc m_json;
  276. QString qst_dirPath;
  277. int int_fileCount;
  278. qint64 int_totalSize;
  279. // 用于存储目录统计结果的结构体
  280. struct DirectoryStats {
  281. qint64 totalSize = 0;
  282. int fileCount = 0;
  283. };
  284. lwjson_stream_parser_t lwparser;
  285. QByteArray jsonBuf;
  286. // 递归收集"一组图片"的归档目录(叶子目录,即时间戳目录)
  287. static void collectArchiveGroups(const QString &rootPath, const QString &directoryPath, QStringList &groups)
  288. {
  289. QDir directory(directoryPath);
  290. if (!directory.exists())
  291. return;
  292. bool hasFile = false;
  293. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  294. foreach (const QFileInfo &fileInfo, fileInfoList) {
  295. if (fileInfo.isDir())
  296. collectArchiveGroups(rootPath, fileInfo.filePath(), groups);
  297. else
  298. hasFile = true;
  299. }
  300. // 根目录本身不算一组(只清理归档子目录)
  301. if (hasFile && directory.absolutePath() != QDir(rootPath).absolutePath())
  302. groups.append(directory.absolutePath());
  303. }
  304. // 删除一组归档目录中的图片(保留 .rawv 录制视频流),空目录一并移除;返回释放的字节数
  305. static qint64 removeGroupFiles(const QString &directoryPath)
  306. {
  307. qint64 freed = 0;
  308. QDir directory(directoryPath);
  309. if (!directory.exists())
  310. return freed;
  311. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  312. foreach (const QFileInfo &fileInfo, fileInfoList) {
  313. if (fileInfo.isDir()) {
  314. freed += removeGroupFiles(fileInfo.filePath());
  315. // 空目录才删除成功,含保留视频流的目录会保留
  316. QDir().rmdir(fileInfo.filePath());
  317. } else if (fileInfo.suffix().compare(QStringLiteral("rawv"), Qt::CaseInsensitive) != 0) {
  318. const qint64 size = fileInfo.size();
  319. if (QFile::remove(fileInfo.filePath()))
  320. freed += size;
  321. }
  322. }
  323. return freed;
  324. }
  325. void deleteAllFilesInDirectory(const QString &directoryPath)
  326. {
  327. QDir directory(directoryPath);
  328. if (!directory.exists()) {
  329. LOG("Directory does not exist.");
  330. return;
  331. }
  332. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  333. foreach (const QFileInfo &fileInfo, fileInfoList) {
  334. if (fileInfo.isDir()) {
  335. // 递归删除子目录中的文件
  336. deleteAllFilesInDirectory(fileInfo.filePath());
  337. } else {
  338. // 删除文件
  339. QFile::remove(fileInfo.filePath());
  340. }
  341. }
  342. analyzeDirectory(directoryPath);
  343. }
  344. // 递归获取目录统计信息
  345. DirectoryStats getDirectoryStats(const QString &directoryPath)
  346. {
  347. QDir directory(directoryPath);
  348. DirectoryStats stats;
  349. if (!directory.exists()) {
  350. LOG("Directory does not exist.");
  351. }
  352. qint64 totalSize = 0;
  353. int fileCount = 0;
  354. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  355. foreach (const QFileInfo &fileInfo, fileInfoList) {
  356. if (fileInfo.isDir()) {
  357. // 递归获取子目录的统计信息
  358. DirectoryStats subStats = getDirectoryStats(fileInfo.filePath());
  359. stats.fileCount += subStats.fileCount;
  360. stats.totalSize += subStats.totalSize;
  361. } else {
  362. stats.fileCount++;
  363. stats.totalSize += fileInfo.size();
  364. }
  365. }
  366. return stats;
  367. qst_dirPath = directoryPath;
  368. int_fileCount = fileCount;
  369. int_totalSize = totalSize;
  370. LOG("Directory:{}",directoryPath.toStdString());
  371. LOG("File count:{}",fileCount);
  372. LOG("Total size:{} bytes",totalSize);
  373. }
  374. // 使用示例
  375. void analyzeDirectory(const QString &directoryPath) {
  376. LOG("Analyzing directory: {}", directoryPath.toStdString());
  377. DirectoryStats stats = getDirectoryStats(directoryPath);
  378. qst_dirPath = directoryPath;
  379. int_fileCount = stats.fileCount;
  380. int_totalSize = stats.totalSize;
  381. LOG("Total files:{}",int_totalSize);
  382. LOG("Total size:{} MB",stats.totalSize / (1024.0 * 1024.0));
  383. }
  384. };
  385. #endif // MSEIAL_H