mserial.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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 <QVideoFrame>
  15. #include <mysql.h>
  16. #include <m_loger.h>
  17. #include "lwjson/lwjson.h"
  18. #include "ymodem.h"
  19. class SerialThread: public QThread
  20. {
  21. Q_OBJECT
  22. public:
  23. // 数据缓存区
  24. QByteArray dataBuf;
  25. YMODEM* getYmodem(); // 声明 getter
  26. explicit SerialThread(QObject *parent = nullptr);
  27. ~SerialThread();
  28. void setSerialPortSettings(const QString &portName, QSerialPort::BaudRate baudRate,
  29. QSerialPort::DataBits dataBits, QSerialPort::Parity parity,
  30. QSerialPort::StopBits stopBits, QSerialPort::FlowControl flowControl);
  31. void init();
  32. void run() override;
  33. void stop();
  34. void SetLedState(bool sw){
  35. sendData(m_json.setLedState(sw));
  36. }
  37. Q_INVOKABLE void reboot(){
  38. sendData(m_json.CmdReboot());
  39. }
  40. QSerialPort& getSerialPort() {
  41. return m_serialPort;
  42. }
  43. Q_INVOKABLE void readBoardData();
  44. Q_INVOKABLE void uploadData_Mqtt(){
  45. m_dat_f.setInterval(0);
  46. };
  47. Q_INVOKABLE void update_dat_f_main(QString freq); //更新数据上传间隔
  48. Q_INVOKABLE void sendCmd(QString cmd_type,bool sw,QString setup,QString speed);
  49. Q_INVOKABLE QStringList pathinfo(){
  50. QStringList pf_pic;
  51. pf_pic.append(qst_dirPath);
  52. pf_pic.append(QString::number(int_fileCount));
  53. pf_pic.append(QString::number(int_totalSize/1048576));
  54. return pf_pic;
  55. }
  56. Q_INVOKABLE void readPathinfo(){
  57. analyzeDirectory(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
  58. }
  59. Q_INVOKABLE void removepic(){
  60. deleteAllFilesInDirectory(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
  61. }
  62. Q_INVOKABLE void setCollt(int sh1 ,int eh1,int sh2,int eh2,int sh3,int eh3){
  63. sendData(m_json.CmdParamconf(sh1,eh1,sh2,eh2,sh3,eh3));
  64. }
  65. Q_INVOKABLE void setCollt_min(int sh1 ,int eh1,int sh2,int eh2,int sh3,int eh3){
  66. sendData(m_json.CmdParamconf_min(sh1,eh1,sh2,eh2,sh3,eh3));
  67. }
  68. Q_INVOKABLE void setTempconf(int tpl ,int tph){
  69. sendData(m_json.CmdParamconf_temp(tpl,tph));
  70. }
  71. Q_INVOKABLE void setHt_xy_dis(int xdis ,int ydis){
  72. sendData(m_json.CmdParamconf_xy_dis(xdis,ydis));
  73. }
  74. Q_INVOKABLE void setLightness(int val){
  75. auto qtContext = QJniObject(QNativeInterface::QAndroidApplication::context()); //activity
  76. if (qtContext.isValid()) {
  77. QJniObject jClass("com/yfkj/cb/Q6iot/Backlight");
  78. jClass.callMethod<void>("setScreenLight","(Landroid/content/Context;I)V",qtContext.object(),val);
  79. //jClass.callStaticMethod<void>("turnScreenOff", "()V");
  80. }
  81. #if 0
  82. if(val==-255){
  83. QJniObject::callStaticMethod<void>("GetUsbPermission",
  84. "turnScreenOff",
  85. "()V");
  86. }
  87. #endif
  88. }
  89. Q_INVOKABLE QString getId(){
  90. return param::imei;
  91. }
  92. Q_INVOKABLE QString getIccid(){
  93. return param::iccid;
  94. }
  95. Q_INVOKABLE QString getlat(){
  96. return param::gps_lat;
  97. }
  98. Q_INVOKABLE QString getlng(){
  99. return param::gps_lng;
  100. }
  101. Q_INVOKABLE QString get_app_version(){
  102. return APP_VERSION;
  103. }
  104. Q_INVOKABLE void makeJsonRpc(const QString &method,const QString &value)
  105. {
  106. sendData(m_json.MakeJsonRPC(method,value));
  107. }
  108. signals:
  109. void dataReceived(const QByteArray &data);
  110. void dataUpload(const QByteArray &data);
  111. void updatestart(QString filename);
  112. void auto_takephoto(bool sw);
  113. void takephotodone();
  114. void disconnect_485();
  115. void autotestdone();
  116. void translatedone();
  117. void netMessage(const QByteArray &data);
  118. void autoFocusDone();
  119. void autoFocusStart();
  120. void lwjsonStreamDONE(const QByteArray &data);
  121. void signal_movy(const QString stepcount);
  122. void timeout_mov_stop();
  123. void gpsSuccess();
  124. void ymodemReady(QString mtype);
  125. void ymodemProgress(int val,int tval);
  126. void ymodemFinished(int res);
  127. public slots:
  128. void sendData(const QByteArray &data);
  129. void mqtttoserial(const QByteArray &data);
  130. void getmodemresult(int res);
  131. void startYmodem(const QString path);
  132. void startUpgrade(QString path)
  133. {
  134. if(m_ymodem){
  135. m_upgrading = true;
  136. m_ymodem->start_ymodem(path);
  137. }
  138. }
  139. Q_INVOKABLE void recoverMcuParam();
  140. private slots:
  141. //void readBoardData();
  142. QString selectSerialPortName();
  143. void feedJsonParser(const QByteArray& data)
  144. {
  145. for (uint8_t b : data) {
  146. lwjsonr_t ret = lwjson_stream_parse(&lwparser, b);
  147. // 只在解析进行中或完成时跟踪字节,避免累积无关数据
  148. if (ret == lwjsonSTREAMINPROG || ret == lwjsonSTREAMDONE) {
  149. jsonBuf.append(static_cast<char>(b));
  150. }
  151. switch (ret){
  152. case lwjsonERRJSON: // 1, 无效的字符
  153. jsonBuf.clear();
  154. //关键:解析器出错后必须复位内部状态,否则停在中途状态导致后续帧永远无法解析完成(偶发收不到数据的根因)
  155. lwjson_stream_reset(&lwparser);
  156. break;
  157. case lwjsonSTREAMWAITFIRSTCHAR: // 2, 等待首字符
  158. break;
  159. case lwjsonSTREAMINPROG: // 3, 正在解析中
  160. break;
  161. case lwjsonSTREAMDONE: // 4, 解析已完成
  162. LOG("lwjsonSTREAMDONE:{}",jsonBuf.constData());
  163. emit lwjsonStreamDONE(jsonBuf);
  164. jsonBuf.clear();
  165. lwjson_stream_reset(&lwparser);
  166. break;
  167. case lwjsonERRMEM: // 5, 嵌套的太深("LWJSON_CFG_STREAM_STACK_SIZE")
  168. ERROR("lwjsonERRMEM!");
  169. jsonBuf.clear();
  170. lwjson_stream_reset(&lwparser);
  171. break;
  172. default: // 流式解析时, 其它的返回值, 都不应该出现
  173. ERROR("未知错误:{:d}",static_cast<int>(ret));
  174. jsonBuf.clear();
  175. lwjson_stream_reset(&lwparser);
  176. break;
  177. }
  178. }
  179. }
  180. private:
  181. bool m_upgrading = false;
  182. void processJsonData(const QByteArray &jsonData);
  183. void saveMcuParam(const QJsonObject &params);
  184. QTimer m_dat_f;
  185. QTimer* timeout_mov = nullptr;
  186. QSerialPort m_serialPort;
  187. YMODEM *m_ymodem; // YMODEM对象
  188. SqliteOperator *sqlConfig;
  189. mutable QMutex m_writeMutex;
  190. bool m_running;
  191. bool data_upload;
  192. int connect_board; //主板串口连接状态
  193. JsonFunc m_json;
  194. QString qst_dirPath;
  195. int int_fileCount;
  196. qint64 int_totalSize;
  197. // 用于存储目录统计结果的结构体
  198. struct DirectoryStats {
  199. qint64 totalSize = 0;
  200. int fileCount = 0;
  201. };
  202. lwjson_stream_parser_t lwparser;
  203. QByteArray jsonBuf;
  204. qint64 m_lastRxMs = 0; //最近一次收到串口字节的时间戳
  205. qint64 m_lastReopenMs = 0; //最近一次重开串口的时间戳(防抖用)
  206. static constexpr qint64 FRAME_TIMEOUT_MS = 5000; //半包超时:jsonBuf卡在解析中超过该时间则强制复位
  207. static constexpr qint64 REOPEN_MIN_INTERVAL_MS = 5000; //两次重开串口的最小间隔(防抖)
  208. void reopenSerialPort(); //串口异常时重开(清除tty内核缓冲,等效于软重启APP的串口部分)
  209. void deleteAllFilesInDirectory(const QString &directoryPath)
  210. {
  211. QDir directory(directoryPath);
  212. if (!directory.exists()) {
  213. qDebug() << "Directory does not exist.";
  214. return;
  215. }
  216. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  217. foreach (const QFileInfo &fileInfo, fileInfoList) {
  218. if (fileInfo.isDir()) {
  219. // 递归删除子目录中的文件
  220. deleteAllFilesInDirectory(fileInfo.filePath());
  221. } else {
  222. // 删除文件
  223. QFile::remove(fileInfo.filePath());
  224. }
  225. }
  226. analyzeDirectory(directoryPath);
  227. }
  228. // 递归获取目录统计信息
  229. DirectoryStats getDirectoryStats(const QString &directoryPath)
  230. {
  231. QDir directory(directoryPath);
  232. DirectoryStats stats;
  233. if (!directory.exists()) {
  234. qDebug() << "Directory does not exist.";
  235. }
  236. qint64 totalSize = 0;
  237. int fileCount = 0;
  238. QFileInfoList fileInfoList = directory.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
  239. foreach (const QFileInfo &fileInfo, fileInfoList) {
  240. if (fileInfo.isDir()) {
  241. // 递归获取子目录的统计信息
  242. DirectoryStats subStats = getDirectoryStats(fileInfo.filePath());
  243. stats.fileCount += subStats.fileCount;
  244. stats.totalSize += subStats.totalSize;
  245. } else {
  246. stats.fileCount++;
  247. stats.totalSize += fileInfo.size();
  248. }
  249. }
  250. return stats;
  251. qst_dirPath = directoryPath;
  252. int_fileCount = fileCount;
  253. int_totalSize = totalSize;
  254. LOG("Directory:{}",directoryPath.toStdString());
  255. LOG("File count:{}",fileCount);
  256. LOG("Total size:{} bytes",totalSize);
  257. }
  258. // 使用示例
  259. void analyzeDirectory(const QString &directoryPath) {
  260. qDebug() << "Analyzing directory:" << directoryPath;
  261. DirectoryStats stats = getDirectoryStats(directoryPath);
  262. qst_dirPath = directoryPath;
  263. int_fileCount = stats.fileCount;
  264. int_totalSize = stats.totalSize;
  265. LOG("Total files:{}",int_totalSize);
  266. LOG("Total size:{} MB",stats.totalSize / (1024.0 * 1024.0));
  267. }
  268. };
  269. #endif // MSEIAL_H