mqtthandler.h 9.8 KB

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