HA – communication between MQTT and Arduino


MQTT stands for Message Queuing Telemetry Transport.
It’s a lightweight protocol where a small code footprint is needed, and the connection uses a small bandwidth. It is mainly used for “machine-to-machine” communication or IOT (Internet-Of-Things).
It’s an ideal solution to exchange data between Home Assistant and Arduino (ESP32) projects.

We need the following components:

  • An MQTT Broker (Mosquitto broker within HA, works fine ! https://mosquitto.org/ )
    This can be installed/managed from within HA itself.
  • MQTT explorer (a free tool for windows/linux/mac http://mqtt-explorer.com/ )
    To create/modify/view MQTT topics, we will use MQTT Explorer.
  • an Arduino board with network/WiFi (ESP32 is ideal)
    Besides the ESP32 board definition, we also need to install the PubSubClient library.
    (this will be the library we use to communicate with MQTT)

Create an MQTT topic “ESP32/TEST” and “publish” it via MQTT Explorer.
Next, add this topic into your configuration.yaml and reboot HA afterwards.

mqtt:  
  sensor:
    - name: "ESP32_MQTT_TEST"
      state_topic: "esp32/test"
      value_template: "{{ value }}"
      qos: 1

After rebooting HA, you will find a new sensor “ESP32_MQTT_TEST”. (as defined in “name” above)
You can publish data from within HA, to this MQTT topic. (usable within automations …)
(or send data from ESP32 to HA, as you will see a bit further down this article)

service: mqtt.publish
data:
  topic: esp32/test
  payload: The text to publish, of course you can also use other sensor values

The following arduino code is used as an example in the ESP32:
(publishing and subscribing !)

#include <WiFi.h>
#include <PubSubClient.h>

// WiFi
const char *ssid = "XXX"; // Enter your WiFi name
const char *password = "XXX";  // Enter WiFi password

// MQTT Broker
const char *mqtt_broker = "192.168.123.88";
const char *topic = "esp32/test";
const char *mqtt_username = "XXX";
const char *mqtt_password = "XXX";
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
 // Set software serial baud to 115200;
 Serial.begin(115200);
 // connecting to a WiFi network
 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED) {
     delay(500);
     Serial.println("Connecting to WiFi..");
 }
 Serial.println("Connected to the WiFi network");
 //connecting to a mqtt broker
 client.setServer(mqtt_broker, mqtt_port);
 client.setCallback(callback);
 while (!client.connected()) {
     String client_id = "esp32-test-";
     client_id += String(WiFi.macAddress());
     Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
     if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
         Serial.println("HA mqtt broker connected");
     } else {
         Serial.print("failed with state ");
         Serial.print(client.state());
         delay(2000);
     }
 }
 // publish and subscribe
 client.publish(topic, "Bericht vanuit Arduino naar de MQTT broker");
 client.subscribe(topic);
}

void callback(char *topic, byte *payload, unsigned int length) {
 Serial.print("Message arrived in topic: ");
 Serial.println(topic);
 Serial.print("Message:");
 for (int i = 0; i < length; i++) {
     Serial.print((char) payload[i]);
 }
 Serial.println();
 Serial.println("-----------------------");
}

void loop() {
 client.loop();
}

– SSID & password, are your WiFi SSID & according password.
– mqtt_broker, is the IP address (or DNS name), of your broker. (mostly, identical to HA IP address)
– topic, the MQTT topic.
– mqtt_username & mqtt_password, username & password to authenticate with MQTT broker.
– mqtt_port (default = 1883)
client.setserver, you initialise a connection with the MQTT broker.
client.publish, you send a message to the corresponding MQTT topic / broker.
client.subscribe, a subscription for notification to the MQTT topic / broker is made.
client.setcallback, subroutine to be called when receiving an mqtt message. (see “void callback(…)” for arguments)


This entry was posted in Blog, Home Assistant, Tutorials. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *