mqtthandler.h 10 KB

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