mqtthandler.h 11 KB

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