| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- #pragma once
- #include "../pch/pch.h"
- #include <iostream>
- #include <cstdlib>
- #include <string>
- #include <cstring>
- #include <cctype>
- #include <thread>
- #include <chrono>
- #include "mqtt/async_client.h"
- class CMqttClientWorker : public virtual mqtt::callback,
- public virtual mqtt::iaction_listener
- {
- private:
- //定义一些常量
- std::string m_server_address = "mqttserver.lewaimai.com";
- std::string m_instanceId = "post-cn-x0r3kjlsy02";
- std::string m_topic = "zhipuzi_windows_pos";
- std::string m_accessKey = "LTAI4G5oikJPMfhq5PuW26qu";
- std::string m_secretKey = "LsIxqepi2o3X0b17FSa7JaANfIMDVY";
- std::string m_client_id;
- //要保证可靠传输
- int MQTT_QOS = 2;
- //一直重试
- int N_RETRY_ATTEMPTS = 1000000;
- //连接阿里云的用户身份,计算出来的
- std::string m_UserName;
- std::string m_Password;
- // Counter for the number of connection retries
- int nretry_ = 0;
- // The MQTT client
- mqtt::async_client* m_async_client;
- // Options to use if we need to reconnect
- mqtt::connect_options m_connOpts;
- bool m_is_mqtt_connected = false;
- //工作状态
- bool m_is_running = false;
- //下面是消息处理相关的
- int m_nStopNum = 0;
- std::mutex m_nStopNumMutex;
- HWND m_hwnd;
- public:
- CMqttClientWorker();
- ~CMqttClientWorker();
- static CMqttClientWorker* GetInstance()
- {
- static CMqttClientWorker instance;
- return &instance;
- }
- void SetHWND(HWND hwnd)
- {
- m_hwnd = hwnd;
- }
- void Start();
- void Stop();
- private:
- void Run();
- void CalUserInfo();
- //处理接收到的MQTT消息推送
- void HandleMessage(std::string message);
- // This deomonstrates manually reconnecting to the broker by calling
- // connect() again. This is a possibility for an application that keeps
- // a copy of it's original connect_options, or if the app wants to
- // reconnect with different options.
- // Another way this can be done manually, if using the same options, is
- // to just call the async_client::reconnect() method.
- void reconnect();
- // 连接、重连、发布、订阅失败回调
- void on_failure(const mqtt::token& tok) override;
- // 连接、重连、发布、订阅成功回调
- void on_success(const mqtt::token& tok) override;
- // 第1次连接成功,或者重连成功,都会调用这个函数
- void connected(const std::string& cause) override;
- // 连接丢失,重新连接
- void connection_lost(const std::string& cause) override;
- // 接收到了消息,进行处理
- void message_arrived(mqtt::const_message_ptr msg) override;
- void delivery_complete(mqtt::delivery_token_ptr token) override;
- void AddStopNum();
- };
|