mqtthandler.h 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. #ifndef MQTTHANDLER_H
  2. #define MQTTHANDLER_H
  3. #include <QObject>
  4. #include <QtMqtt/QMqttClient>
  5. #include <QtMqtt/QMqttSubscription>
  6. #include <QTextCodec>
  7. #include <QThread>
  8. #include <QTimer>
  9. #include <QTextToSpeechEngine>
  10. #include <QtMultimedia/QMediaPlayer>
  11. #include <QAudioOutput>
  12. #include <curl/curl.h>
  13. #include <QDir>
  14. #include <QFileInfo>
  15. #include <QStandardPaths>
  16. #include <m_json.h>
  17. #include <m_loger.h>
  18. #include <main.h>
  19. #include <QtConcurrent/QtConcurrent>
  20. #include <QFutureWatcher>
  21. #include <mserial.h>
  22. #include <app_sq_save.h>
  23. #include <QNetworkInformation>
  24. class NetworkInfoHelper : public QObject {
  25. Q_OBJECT
  26. Q_PROPERTY(QNetworkInformation::Reachability reachability READ reachability NOTIFY reachabilityChanged)
  27. Q_PROPERTY(QNetworkInformation::TransportMedium transportMedium READ transportMedium NOTIFY transportMediumChanged)
  28. Q_PROPERTY(bool isBehindCaptivePortal READ isBehindCaptivePortal NOTIFY isBehindCaptivePortalChanged)
  29. Q_PROPERTY(bool isMetered READ isMetered NOTIFY isMeteredChanged)
  30. public:
  31. explicit NetworkInfoHelper(QObject *parent = nullptr);
  32. QNetworkInformation::Reachability reachability() const;
  33. QNetworkInformation::TransportMedium transportMedium() const;
  34. bool isBehindCaptivePortal() const;
  35. bool isMetered() const;
  36. signals:
  37. void reachabilityChanged(QNetworkInformation::Reachability newReachability);
  38. void transportMediumChanged(QNetworkInformation::TransportMedium current);
  39. void isBehindCaptivePortalChanged(bool state);
  40. void isMeteredChanged(bool isMetered);
  41. private:
  42. QNetworkInformation *m_networkInfo = nullptr;
  43. QNetworkInformation::Reachability m_initialReachability = QNetworkInformation::Reachability::Unknown;
  44. QNetworkInformation::TransportMedium m_initialTransportMedium = QNetworkInformation::TransportMedium::Unknown;
  45. bool m_initialIsBehindCaptivePortal = false;
  46. bool m_initialIsMetered = false;
  47. };
  48. class MqttHandler : public QThread
  49. {
  50. Q_OBJECT
  51. public:
  52. QByteArray m_client_dataBuf; //数据缓存区
  53. int m_client_rxByte = 0; //接收字节数
  54. explicit MqttHandler(QObject *parent = nullptr);
  55. ~MqttHandler();
  56. void run() override {
  57. exec();
  58. }
  59. Q_INVOKABLE void connectToBroker();
  60. Q_INVOKABLE void disconnectFromBroker();
  61. Q_INVOKABLE void publish_m(const QByteArray &message);
  62. Q_INVOKABLE void subscribe_m(const QString &m_topic);
  63. Q_INVOKABLE void unsubscribe_m(const QString &m_topic);
  64. Q_INVOKABLE bool checkLink(){
  65. if(m_client->state()==QMqttClient::Disconnected){
  66. return false;
  67. }else{
  68. return true;
  69. }
  70. }
  71. Q_INVOKABLE QStringList netMessage()
  72. {
  73. QStringList net_list;
  74. net_list.append(QString::number(param::net_alive));
  75. net_list.append(param::net_name);
  76. net_list.append(param::net_description);
  77. net_list.append(param::net_mac);
  78. net_list.append(param::net_ipv4);
  79. net_list.append(param::ftp_main_ip);
  80. net_list.append(QString::number(param::dat_f_main));
  81. net_list.append(QString::number(param::datupload_remain/1000));
  82. return net_list;
  83. }
  84. Q_INVOKABLE void sendUpdateApp(){
  85. emit appdownload();
  86. }
  87. Q_INVOKABLE void sendUpdatesBoard(){
  88. emit updateStm32(); //下载rbl文件
  89. emit dataReceived(mqtt_json.CmdUpdate()); //发送升级指令
  90. }
  91. Q_INVOKABLE QString cache_json_num(){
  92. return QString::number(m_storage->JsonEntries_saved());
  93. }
  94. Q_INVOKABLE QString cache_image_num(){
  95. return QString::number(m_storage->ImageEntries_saved());
  96. }
  97. Q_INVOKABLE QString cache_Json_Maxnum(){
  98. return QString::number(m_storage->maxJsonEntries());
  99. }
  100. Q_INVOKABLE QString cache_image_Maxnum(){
  101. return QString::number(m_storage->maxImageEntries());
  102. }
  103. Q_INVOKABLE int cache_image_enable(){
  104. return m_storage->imageCacheEnabled();
  105. }
  106. Q_INVOKABLE int cache_Json_enable(){
  107. return m_storage->jsonCacheEnabled();
  108. }
  109. // 提供接口(如果需要从 QML 调整配置)
  110. OfflineStorage* storage() { return m_storage; }
  111. signals:
  112. void connected();
  113. void disconnected();
  114. void mqttclient_readSuccess(int recByte);
  115. void dataReceived(const QByteArray &message);
  116. void messageSub(const QByteArray &message);
  117. void messagePub(const QByteArray &message);
  118. void autotakephoto(bool stat);
  119. void appdownload(); //apk文件下载信号
  120. void updateStm32(); //rbl文件下载信号
  121. void configChange();
  122. void mediaplay();
  123. void sysReboot();
  124. void appInstall();
  125. void signal_reupload_image(const QString &path);
  126. void signal_imei_change(const QString &new_imei);
  127. void signal_upload_log(const QString &path);
  128. void signal_set_camera_exposure(int exposureTime);
  129. void signal_open_camera(); //远程校准/相机开启指令:跳转相机界面并打开相机
  130. public slots:
  131. void install_app();
  132. void startReupload();
  133. void storage_Picture(bool success,const QString &path);
  134. void storage_Picture_Takephoto(const QString &path);
  135. private slots:
  136. // Your existing slots...
  137. void onConnected();
  138. void onDisconnected();
  139. void onMessageReceived(const QByteArray &message, const QMqttTopicName &topic);
  140. void reConnect();
  141. void playSound();
  142. private:
  143. QMediaPlayer* mediaPlayer;
  144. QAudioOutput* maudioOutput;
  145. QTextCodec *tc; // 编码
  146. QMqttClient *m_client;
  147. OfflineStorage *m_storage;
  148. QUrl url;
  149. JsonFunc mqtt_json;
  150. bool m_rebootPending = false; //系统重启指令受理标志,防止3秒等待期内重复触发
  151. int m_uploadBatchSize = 1; // 可配置
  152. QHash<quint16, std::function<void(bool)>> m_pendingAcks; // 消息ID -> 回调
  153. QTimer *image_reupload;
  154. };
  155. class CurlHandler : public QThread
  156. {
  157. Q_OBJECT
  158. public:
  159. CurlHandler(const QString &url, const QString &outputPath)
  160. : url(url), outputPath(outputPath) {
  161. username = "cbd_user";
  162. password = "YFkj@6O2O";
  163. }
  164. void seturl(const QString &nurl)
  165. {
  166. url = nurl;
  167. }
  168. void setfilepath(const QString &npath){
  169. outputPath = npath;
  170. }
  171. void settype(const QString &tp){
  172. update_type = tp;
  173. }
  174. protected:
  175. void run() override {
  176. CURL *curl = curl_easy_init();
  177. QFile localFile(outputPath);
  178. if (localFile.open(QIODevice::WriteOnly)) {
  179. if(curl){
  180. emit downloadStart(update_type);
  181. // 立即发射初始进度信号,确保进度条立即显示
  182. emit sglProgress(0.0, 0.0, 0.0);
  183. curl_easy_setopt(curl, CURLOPT_URL, url.toUtf8().constData());
  184. // 设置用户名和密码
  185. curl_easy_setopt(curl, CURLOPT_USERPWD, (username + ":" + password).toUtf8().constData());
  186. // 设置回调函数,将下载的数据写入本地文件
  187. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
  188. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &localFile);
  189. // 设置进度回调函数
  190. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  191. //curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progressCallback);
  192. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progressCallback);
  193. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, this);
  194. res = curl_easy_perform(curl);
  195. if (res == CURLE_OK) {
  196. LOG("File downloaded and saved.");
  197. emit downloadFinished(true,update_type);
  198. } else {
  199. emit downloadFinished(false,update_type);
  200. qDebug() << "Download failed:" << curl_easy_strerror(res);
  201. }
  202. curl_easy_cleanup(curl);
  203. }
  204. else{
  205. qDebug() << "Failed to open local file for writing.";
  206. }
  207. localFile.close();
  208. curl_global_cleanup();
  209. }else{
  210. qDebug() << "Failed to open local file for writing.";
  211. }
  212. }
  213. public slots:
  214. void uploadFile(const QString &url){
  215. QString username = param::ftp_main_uid;
  216. QString password = param::ftp_main_pwd;
  217. }
  218. signals:
  219. void downloadStart(QString mtype);
  220. void downloadFinished(bool result,QString mtype);
  221. void uploadFinished(bool result);
  222. void sglProgress(double val,double timeLeft,double speed); //进度信号
  223. private:
  224. CURLcode res;
  225. QString update_type;
  226. QString url;
  227. QString outputPath;
  228. QString username;
  229. QString password;
  230. QFile localFile;
  231. static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
  232. size_t totalSize = size * nmemb;
  233. QFile* file = static_cast<QFile*>(userp);
  234. if (file) {
  235. file->write(static_cast<const char*>(contents), totalSize);
  236. }
  237. return totalSize;
  238. }
  239. // 下载进度回调函数
  240. static int progressCallback(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)
  241. {
  242. Q_UNUSED(ultotal);
  243. Q_UNUSED(ulnow);
  244. CurlHandler* curl_handler = static_cast<CurlHandler*>(clientp);
  245. double percent = 0.0;
  246. double speed = 0.0;
  247. double timeLeft = 0.0;
  248. if (dltotal > 0) {
  249. percent = (double)dlnow / (double)dltotal * 100.0;
  250. speed = (double)dlnow / 1024.0;
  251. timeLeft = ((double)dltotal - (double)dlnow) / (speed * 1024.0) * 100.0;
  252. }
  253. if (speed > 0) {
  254. emit curl_handler->sglProgress(percent,timeLeft,speed);
  255. QCoreApplication::processEvents();
  256. }
  257. return 0;
  258. }
  259. };
  260. #endif // MQTTHANDLER_H