68 lines
1.8 KiB
C++
68 lines
1.8 KiB
C++
#pragma once
|
|
#include <atomic>
|
|
#include <chrono>
|
|
#include <functional>
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include <string>
|
|
#include <thread>
|
|
|
|
#include "logger.h"
|
|
#include "mqtt/async_client.h"
|
|
|
|
class MqttClient : public virtual mqtt::callback
|
|
{
|
|
public:
|
|
using StatusCallback = std::function<void(bool connected)>;
|
|
using MessageCallback = std::function<void(const std::string &topic, const std::string &payload)>;
|
|
|
|
MqttClient(const std::string &id, const std::string &server_ip, int server_port, Logger &logger,
|
|
const std::string &username = "", const std::string &password = "", const std::string &client_id = "",
|
|
bool clean_session = true, int keep_alive = 20, int qos = 1);
|
|
~MqttClient();
|
|
|
|
void start();
|
|
void stop();
|
|
bool is_connected() const;
|
|
|
|
void set_reconnect_policy(int first, int max);
|
|
void set_status_callback(StatusCallback cb);
|
|
void set_message_callback(MessageCallback cb);
|
|
|
|
bool publish(const std::string &topic, const std::string &payload, int qos = -1);
|
|
bool subscribe(const std::string &topic, int qos = -1);
|
|
|
|
private:
|
|
void client_loop();
|
|
bool try_connect();
|
|
void disconnect();
|
|
void connection_lost(const std::string &cause) override;
|
|
void message_arrived(mqtt::const_message_ptr msg) override;
|
|
|
|
private:
|
|
std::string id_;
|
|
std::string server_ip_;
|
|
int server_port_;
|
|
Logger &logger_;
|
|
|
|
std::string username_;
|
|
std::string password_;
|
|
std::string client_id_;
|
|
bool clean_session_;
|
|
int keep_alive_;
|
|
int qos_;
|
|
|
|
std::atomic<bool> running_{false};
|
|
std::atomic<bool> connected_{false};
|
|
std::thread worker_;
|
|
|
|
int reconnect_first_ = 5;
|
|
int reconnect_max_ = 60;
|
|
|
|
std::shared_ptr<mqtt::async_client> client_;
|
|
std::mutex send_mutex_;
|
|
|
|
StatusCallback status_callback_;
|
|
MessageCallback message_callback_;
|
|
};
|