mqtthandler.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. public slots:
  129. void install_app();
  130. void startReupload();
  131. void storage_Picture(bool success,const QString &path);
  132. void storage_Picture_Takephoto(const QString &path);
  133. private slots:
  134. // Your existing slots...
  135. void onConnected();
  136. void onDisconnected();
  137. void onMessageReceived(const QByteArray &message, const QMqttTopicName &topic);
  138. void reConnect();
  139. void playSound();
  140. private:
  141. QMediaPlayer* mediaPlayer;
  142. QAudioOutput* maudioOutput;
  143. QTextCodec *tc; // 编码
  144. QMqttClient *m_client;
  145. OfflineStorage *m_storage;
  146. QUrl url;
  147. JsonFunc mqtt_json;
  148. int m_uploadBatchSize = 1; // 可配置
  149. QHash<quint16, std::function<void(bool)>> m_pendingAcks; // 消息ID -> 回调
  150. QTimer *image_reupload;
  151. Serial_AT serial_4g;
  152. };
  153. class CurlHandler : public QThread
  154. {
  155. Q_OBJECT
  156. public:
  157. CurlHandler(const QString &url, const QString &outputPath)
  158. : url(url), outputPath(outputPath) {
  159. username = "cbd_user";
  160. password = "YFkj@6O2O";
  161. }
  162. void seturl(const QString &nurl)
  163. {
  164. url = nurl;
  165. }
  166. void setfilepath(const QString &npath){
  167. outputPath = npath;
  168. }
  169. void settype(const QString &tp){
  170. update_type = tp;
  171. }
  172. protected:
  173. void run() override {
  174. CURL *curl = curl_easy_init();
  175. QFile localFile(outputPath);
  176. if (localFile.open(QIODevice::WriteOnly)) {
  177. if(curl){
  178. emit downloadStart(update_type);
  179. // 立即发射初始进度信号,确保进度条立即显示
  180. emit sglProgress(0.0, 0.0, 0.0);
  181. curl_easy_setopt(curl, CURLOPT_URL, url.toUtf8().constData());
  182. // 设置用户名和密码
  183. curl_easy_setopt(curl, CURLOPT_USERPWD, (username + ":" + password).toUtf8().constData());
  184. // 设置回调函数,将下载的数据写入本地文件
  185. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
  186. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &localFile);
  187. // 设置进度回调函数
  188. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  189. //curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progressCallback);
  190. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progressCallback);
  191. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, this);
  192. res = curl_easy_perform(curl);
  193. if (res == CURLE_OK) {
  194. LOG("File downloaded and saved.");
  195. emit downloadFinished(true,update_type);
  196. } else {
  197. emit downloadFinished(false,update_type);
  198. qDebug() << "Download failed:" << curl_easy_strerror(res);
  199. }
  200. curl_easy_cleanup(curl);
  201. }
  202. else{
  203. qDebug() << "Failed to open local file for writing.";
  204. }
  205. localFile.close();
  206. curl_global_cleanup();
  207. }else{
  208. qDebug() << "Failed to open local file for writing.";
  209. }
  210. }
  211. public slots:
  212. void uploadFile(const QString &url){
  213. QString username = param::ftp_main_uid;
  214. QString password = param::ftp_main_pwd;
  215. }
  216. signals:
  217. void downloadStart(QString mtype);
  218. void downloadFinished(bool result,QString mtype);
  219. void uploadFinished(bool result);
  220. void sglProgress(double val,double timeLeft,double speed); //进度信号
  221. private:
  222. CURLcode res;
  223. QString update_type;
  224. QString url;
  225. QString outputPath;
  226. QString username;
  227. QString password;
  228. QFile localFile;
  229. static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
  230. size_t totalSize = size * nmemb;
  231. QFile* file = static_cast<QFile*>(userp);
  232. if (file) {
  233. file->write(static_cast<const char*>(contents), totalSize);
  234. }
  235. return totalSize;
  236. }
  237. // 下载进度回调函数
  238. static int progressCallback(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)
  239. {
  240. Q_UNUSED(ultotal);
  241. Q_UNUSED(ulnow);
  242. CurlHandler* curl_handler = static_cast<CurlHandler*>(clientp);
  243. double percent = 0.0;
  244. double speed = 0.0;
  245. double timeLeft = 0.0;
  246. if (dltotal > 0) {
  247. percent = (double)dlnow / (double)dltotal * 100.0;
  248. speed = (double)dlnow / 1024.0;
  249. timeLeft = ((double)dltotal - (double)dlnow) / (speed * 1024.0) * 100.0;
  250. }
  251. if (speed > 0) {
  252. emit curl_handler->sglProgress(percent,timeLeft,speed);
  253. QCoreApplication::processEvents();
  254. }
  255. return 0;
  256. }
  257. };
  258. #endif // MQTTHANDLER_H