66 lines
1.6 KiB
C++
66 lines
1.6 KiB
C++
/**
|
|
* @file mqttClient.hpp
|
|
* @author Gustice
|
|
* @brief Wrapper class for TCP/IP based MQTT APIs
|
|
*
|
|
* @copyright Copyright (c) 2024
|
|
*/
|
|
#pragma once
|
|
|
|
#include "esp_event.h"
|
|
#include "esp_system.h"
|
|
#include "mqtt_client.h"
|
|
#include <functional>
|
|
#include <string>
|
|
#include <string_view>
|
|
|
|
/**
|
|
* @brief MqttClient wrapper (Singleton)
|
|
*/
|
|
class MqttClient {
|
|
public:
|
|
/// @brief Init and mount file system
|
|
/// @param broker URI to web MQTT broker server
|
|
static MqttClient &init(std::string broker, std::string prefix);
|
|
void addSubscription(std::string topic, std::function<void(std::string)> call);
|
|
void publish(std::string topic, std::string data);
|
|
void start();
|
|
bool isRunning() { return _state != State::Init; }
|
|
|
|
/// @brief Get instance, ensure initialization
|
|
/// @param broker URI to web MQTT broker server
|
|
/// @returnb
|
|
static MqttClient &getInstance();
|
|
|
|
// Disable move and assignment
|
|
MqttClient(MqttClient &other) = delete;
|
|
void operator=(const MqttClient &) = delete;
|
|
|
|
// protected:
|
|
MqttClient(std::string broker, std::string pefix);
|
|
~MqttClient();
|
|
|
|
private:
|
|
enum class State {
|
|
Init,
|
|
Started,
|
|
Disconnected,
|
|
Connected
|
|
};
|
|
struct Subscription {
|
|
std::string topic;
|
|
std::function<void(std::string)> callback;
|
|
bool active{};
|
|
int id{};
|
|
};
|
|
|
|
std::string _broker;
|
|
std::string _prefix;
|
|
State _state{};
|
|
static MqttClient *_instance;
|
|
esp_mqtt_client_handle_t _client;
|
|
std::vector<Subscription> _subscriptions;
|
|
|
|
static void eventHandler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data);
|
|
};
|