HAMqtt class

class HAMqtt

This class is a wrapper for the PubSub API. It’s a central point of the library where instances of all device types are stored.

Public Types

enum ConnectionState

Values:

enumerator StateConnecting
enumerator StateConnectionTimeout
enumerator StateConnectionLost
enumerator StateConnectionFailed
enumerator StateDisconnected
enumerator StateConnected
enumerator StateBadProtocol
enumerator StateBadClientId
enumerator StateUnavailable
enumerator StateBadCredentials
enumerator StateUnauthorized

Public Functions

explicit HAMqtt(Client &netClient, HADevice &device, const uint8_t maxDevicesTypesNb = 24)

Creates a new instance of the HAMqtt class. Please note that only one instance of the class can be initialized at the same time.

Parameters
  • netClient – The EthernetClient or WiFiClient that’s going to be used for the network communication.

  • device – An instance of the HADevice class representing your device.

  • maxDevicesTypesNb – The maximum number of device types (sensors, switches, etc.) that you’re going to implement.

~HAMqtt()

Removes singleton of the HAMqtt class.

inline void setDiscoveryPrefix(const char *prefix)

Sets the prefix of the Home Assistant discovery topics. It needs to match the prefix set in the HA admin panel. The default prefix is “homeassistant”.

Parameters

prefix – The discovery topics’ prefix.

inline const char *getDiscoveryPrefix() const

Returns the discovery topics’ prefix.

inline void setDataPrefix(const char *prefix)

Sets prefix of the data topics. It may be useful if you want to pass MQTT traffic through a bridge. The default prefix is “aha”.

Parameters

prefix – The data topics’ prefix.

inline const char *getDataPrefix() const

Returns the data topics’ prefix.

inline HADevice const *getDevice() const

Returns instance of the device assigned to the HAMqtt class. It’s the same object (pointer) that was passed to the HAMqtt constructor.

inline void onMessage(void (*callback)(const char *topic, const uint8_t *payload, uint16_t length))

Registers a new callback method that will be called when the device receives an MQTT message. Please note that the callback is also fired by internal MQTT messages used by the library. You should always verify the topic of the received message.

Parameters

callback – Callback method.

inline void onConnected(void (*callback)())

Registers a new callback method that will be called each time a connection to the MQTT broker is acquired. The callback is also fired after reconnecting to the broker. You can use this method to register topics’ subscriptions.

Parameters

callback – Callback method.

inline void onDisconnected(void (*callback)())

Registers a new callback method that will be called each time the connection to the MQTT broker is lost.

Parameters

callback – Callback method.

inline void onStateChanged(void (*callback)(ConnectionState state))

Registers a new callback method that will be called each time the connection state changes.

Parameters

callback – Callback method.

inline ConnectionState getState() const

Returns the current state of the MQTT connection.

bool begin(const IPAddress serverIp, const uint16_t serverPort = 1883, const char *username = nullptr, const char *password = nullptr)

Sets parameters of the MQTT connection using the IP address and port. The library will try to connect to the broker in first loop cycle. Please note that the library automatically reconnects to the broker if connection is lost.

Parameters
  • serverIp – IP address of the MQTT broker.

  • serverPort – Port of the MQTT broker.

  • username – Username for authentication. It can be nullptr if the anonymous connection needs to be performed.

  • password – Password for authentication. It can be nullptr if the anonymous connection needs to be performed.

bool begin(const IPAddress serverIp, const char *username, const char *password)

Sets parameters of the MQTT connection using the IP address and the default port (1883). The library will try to connect to the broker in first loop cycle. Please note that the library automatically reconnects to the broker if connection is lost.

Parameters
  • serverIp – IP address of the MQTT broker.

  • username – Username for authentication. It can be nullptr if the anonymous connection needs to be performed.

  • password – Password for authentication. It can be nullptr if the anonymous connection needs to be performed.

bool begin(const char *serverHostname, const uint16_t serverPort = 1883, const char *username = nullptr, const char *password = nullptr)

Sets parameters of the MQTT connection using the hostname and port. The library will try to connect to the broker in first loop cycle. Please note that the library automatically reconnects to the broker if connection is lost.

Parameters
  • serverHostname – Hostname of the MQTT broker.

  • serverPort – Port of the MQTT broker.

  • username – Username for authentication. It can be nullptr if the anonymous connection needs to be performed.

  • password – Password for authentication. It can be nullptr if the anonymous connection needs to be performed.

bool begin(const char *serverHostname, const char *username, const char *password)

Sets parameters of the MQTT connection using the hostname and the default port (1883). The library will try to connect to the broker in first loop cycle. Please note that the library automatically reconnects to the broker if connection is lost.

Parameters
  • serverHostname – Hostname of the MQTT broker.

  • username – Username for authentication. It can be nullptr if the anonymous connection needs to be performed.

  • password – Password for authentication. It can be nullptr if the anonymous connection needs to be performed.

bool disconnect()

Closes the MQTT connection.

void loop()

This method should be called periodically inside the main loop of the firmware. It’s safe to call this method in some interval (like 5ms).

bool isConnected() const

Returns true if connection to the MQTT broker is established.

void setKeepAlive(uint16_t keepAlive)

Sets keep alive for the MQTT connection. By default it’s 15 seconds.

Parameters

keepAlive – Number of seconds to keep connection alive.

bool setBufferSize(uint16_t size)

Sets the buffer size for the MQTT connection. By default it’s 256 bytes.

Parameters

size – Size of the buffer.

void addDeviceType(HABaseDeviceType *deviceType)

Adds a new device’s type to the MQTT. Each time the connection with MQTT broker is acquired, the HAMqtt class calls “onMqttConnected” method in all devices’ types instances.

Note

The HAMqtt class doesn’t take ownership of the given pointer.

Parameters

deviceType – Instance of the device’s type (HASwitch, HABinarySensor, etc.).

bool publish(const char *topic, const char *payload, bool retained = false)

Publishes the MQTT message with given topic and payload. Message won’t be published if the connection with the MQTT broker is not established. In this case method returns false.

Parameters
  • topic – The topic to publish.

  • payload – The payload to publish (it may be empty const char).

  • retained – Specifies whether message should be retained.

bool beginPublish(const char *topic, uint16_t payloadLength, bool retained = false)

Begins publishing of a message with the given properties. When this method returns true the payload can be written using HAMqtt::writePayload method.

Parameters
  • topic – Topic of the published message.

  • payloadLength – Length of the payload (bytes) that’s going to be published.

  • retained – Specifies whether the published message should be retained.

void writePayload(const char *data, const uint16_t length)

Writes given string to the TCP stream. Please note that before writing any data the HAMqtt::beginPublish method needs to be called.

Parameters
  • data – The string to publish.

  • length – Length of the data (bytes).

void writePayload(const uint8_t *data, const uint16_t length)

Writes given data to the TCP stream. Please note that before writing any data the HAMqtt::beginPublish method needs to be called.

Parameters
  • data – The data to publish.

  • length – Length of the data (bytes).

void writePayload(const __FlashStringHelper *data)

Writes given progmem data to the TCP stream. Please note that before writing any data the HAMqtt::beginPublish method needs to be called.

Parameters

data – Progmem data to publish.

bool endPublish()

Finishes publishing of a message. After calling this method the message will be processed by the broker.

bool subscribe(const char *topic)

Subscribes to the given topic. Whenever a new message is received the onMqttMessage callback in all devices types is called.

Please note that you need to subscribe topic each time the connection with the broker is acquired.

Parameters

topic – Topic to subscribe.

inline void setLastWill(const char *lastWillTopic, const char *lastWillMessage, bool lastWillRetain)

Enables the last will message that will be produced when the device disconnects from the broker. If you want to change availability of the device in Home Assistant panel please use enableLastWill() method from the HADevice class instead.

Parameters
  • lastWillTopic – The topic to publish.

  • lastWillMessage – The message (payload) to publish.

  • lastWillRetain – Specifies whether the published message should be retained.

void processMessage(const char *topic, const uint8_t *payload, uint16_t length)

Processes MQTT message received from the broker (subscription).

Note

Do not use this method on your own. It’s only for the internal purpose.

Parameters
  • topic – Topic of the message.

  • payload – Content of the message.

  • length – Length of the message.

Public Static Functions

static inline HAMqtt *instance()

Returns existing instance (singleton) of the HAMqtt class. It may be a null pointer if the HAMqtt object was never constructed or it was destroyed.

Private Functions

void connectToServer()

Attempts to connect to the MQTT broker. The method uses properties passed to the “begin” method.

void onConnectedLogic()

This method is called each time the connection with MQTT broker is acquired.

void setState(ConnectionState state)

Sets the state of the MQTT connection.

Private Members

PubSubClient *_mqtt

Instance of the PubSubClient class. It’s initialized in the constructor.

const HADevice &_device

Instance of the HADevice passed to the constructor.

void (*_messageCallback)(const char *topic, const uint8_t *payload, uint16_t length)

The callback method that will be called when an MQTT message is received.

void (*_connectedCallback)()

The callback method that will be called when the MQTT connection is acquired.

void (*_disconnectedCallback)()

The callback method that will be called when the MQTT connection is lost.

void (*_stateChangedCallback)(ConnectionState state)

The callback method that will be called when the MQTT connection state changes.

bool _initialized

Specifies whether the HAMqtt::begin method was ever called.

const char *_discoveryPrefix

Teh discovery prefix that’s used for the configuration messages.

const char *_dataPrefix

The data prefix that’s used for publishing data messages.

const char *_username

The username used for the authentication. It’s set in the HAMqtt::begin method.

const char *_password

The password used for the authentication. It’s set in the HAMqtt::begin method.

uint32_t _lastConnectionAttemptAt

Time of the last connection attemps (milliseconds since boot).

uint8_t _devicesTypesNb

The amount of registered devices types.

uint8_t _maxDevicesTypesNb

The maximum amount of devices types that can be registered.

HABaseDeviceType **_devicesTypes

Pointers of all registered devices types (array of pointers).

const char *_lastWillTopic

The last will topic set by HAMqtt::setLastWill.

const char *_lastWillMessage

The last will message set by HAMqtt::setLastWill.

bool _lastWillRetain

The last will retain set by HAMqtt::setLastWill.

ConnectionState _currentState

The last known state of the MQTT connection.

Private Static Attributes

static const uint16_t ReconnectInterval = 10000

Interval between MQTT reconnects (milliseconds).

static HAMqtt *_instance

Living instance of the HAMqtt class. It can be nullptr.