CMqttClientWorker.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #pragma once
  2. #include "../pch/pch.h"
  3. #include <iostream>
  4. #include <cstdlib>
  5. #include <string>
  6. #include <cstring>
  7. #include <cctype>
  8. #include <thread>
  9. #include <chrono>
  10. #include "mqtt/async_client.h"
  11. class CMqttClientWorker : public virtual mqtt::callback,
  12. public virtual mqtt::iaction_listener
  13. {
  14. private:
  15. //定义一些常量
  16. std::string m_server_address = "mqttserver.lewaimai.com";
  17. std::string m_instanceId = "post-cn-x0r3kjlsy02";
  18. std::string m_topic = "zhipuzi_windows_pos";
  19. std::string m_accessKey = "LTAI4G5oikJPMfhq5PuW26qu";
  20. std::string m_secretKey = "LsIxqepi2o3X0b17FSa7JaANfIMDVY";
  21. std::string m_client_id;
  22. //要保证可靠传输
  23. int MQTT_QOS = 2;
  24. //一直重试
  25. int N_RETRY_ATTEMPTS = 1000000;
  26. //连接阿里云的用户身份,计算出来的
  27. std::string m_UserName;
  28. std::string m_Password;
  29. // Counter for the number of connection retries
  30. int nretry_ = 0;
  31. // The MQTT client
  32. mqtt::async_client* m_async_client;
  33. // Options to use if we need to reconnect
  34. mqtt::connect_options m_connOpts;
  35. bool m_is_mqtt_connected = false;
  36. //工作状态
  37. bool m_is_running = false;
  38. //下面是消息处理相关的
  39. int m_nStopNum = 0;
  40. std::mutex m_nStopNumMutex;
  41. HWND m_hwnd;
  42. public:
  43. CMqttClientWorker();
  44. ~CMqttClientWorker();
  45. static CMqttClientWorker* GetInstance()
  46. {
  47. static CMqttClientWorker instance;
  48. return &instance;
  49. }
  50. void SetHWND(HWND hwnd)
  51. {
  52. m_hwnd = hwnd;
  53. }
  54. void Start();
  55. void Stop();
  56. private:
  57. void Run();
  58. void CalUserInfo();
  59. //处理接收到的MQTT消息推送
  60. void HandleMessage(std::string message);
  61. // This deomonstrates manually reconnecting to the broker by calling
  62. // connect() again. This is a possibility for an application that keeps
  63. // a copy of it's original connect_options, or if the app wants to
  64. // reconnect with different options.
  65. // Another way this can be done manually, if using the same options, is
  66. // to just call the async_client::reconnect() method.
  67. void reconnect();
  68. // 连接、重连、发布、订阅失败回调
  69. void on_failure(const mqtt::token& tok) override;
  70. // 连接、重连、发布、订阅成功回调
  71. void on_success(const mqtt::token& tok) override;
  72. // 第1次连接成功,或者重连成功,都会调用这个函数
  73. void connected(const std::string& cause) override;
  74. // 连接丢失,重新连接
  75. void connection_lost(const std::string& cause) override;
  76. // 接收到了消息,进行处理
  77. void message_arrived(mqtt::const_message_ptr msg) override;
  78. void delivery_complete(mqtt::delivery_token_ptr token) override;
  79. void AddStopNum();
  80. };