mqtthandler.h 9.8 KB

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