Adding ESP8266 devices

Hi, Im really new to Homeassistant. I must admit i am finding it hard to understand how to add devices. I have made a ESP8266 device using a NodeMCU which just turns on and off an LED. The device connects to my network and MQTT server (my homeassistant IP) I have also addivsed mqtt: into my config.

What i am not understanding is how to add this device so I can switch on and off via the homeassistant UI. Below is the tutoral i used. I know once i can do this i will be able to do relays and understand the system.

Below is the code and tutorial I used. I’d really like a hand please.

http://kookye.com/2016/12/12/remotely-control-led-with-nodemcu-through-mqtt-iot-broker/

you need to add it into HA as a switch

from there it’s as simple as adding it into groups and views.

Thanks this is the part i dont understand as you dont add in the IP of the device, i cant see how it would communicate.

It communicates over MQTT. That’s the entire purpose of using MQTT

MQTT is a publish/subscribe type protocol.

Clients, such as your light, subscribe to a topic at the broker. Other clients (such as HA) then publish messages to the broker with that topic. The broker distributes the message to all clients that have subscribed to the topic.

So both ends only communicate with the broker.

So how do i get my device to subscribe to topic? is this something that needs to be in the code of the device?

is this something that needs to be in the code of the device?

Yes. That’s exactly how it works.

Your device needs to subscribe to a topic and based on the data it receives on that topic do a thing. It also should publish it’s state out to MQTT for HA to read the state of the device as well.

99% of the work is done in the code on the device. The other 1% is connecting to the device.

Your ESP8266 device is using MQTT to publish information (e.g. publish “1” when motion is detected and “0” when not motion was detected).
You set that up in the nodemcu interface.

As for HA, you define a corresponding mqtt binary_sensor:

platform: mqtt
state_topic: '/nodemcu02/pir/motion'
name: 'nodemcu02 motion'
payload_on: '1'
payload_off: '0'
device_class: motion

My device is called “nodemcu02” and it publishes “1” in /nodemcu/pir/motion when the motion sensor is triggered.

You need to set up the MQTT connection in HA for this to work:

mqtt:
  broker: 192.168.xxx.xxx
  port: 1883
  client_id: some_name
  keepalive: 60
  username: your_ha_mqtt_user
  password: your_ha_mqtt_password

Sebastian

BTW: Depending on what you want to do with your nodemcu board, have a look at ESPEasy:
https://www.letscontrolit.com/wiki/index.php/ESPEasy

Installing ESPEasy gives you a web interface for the nodemcu where you can set up your MQTT server, the I/O ports and much more.

So this is the code i used. Is the topic in there?

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Define NodeMCU D3 pin connect to LED
#define LED_PIN D3

// Update these with values suitable for your network.
const char* ssid = “your_wifi_hotspot”;
const char* password = “your_wifi_password”;
const char* mqtt_server = “broker.mqtt-dashboard.com”;
//const char* mqtt_server = “iot.eclipse.org”;

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {
delay(100);
// We start by connecting to a WiFi network
Serial.print(“Connecting to “);
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(”.”);
}
randomSeed(micros());
Serial.println("");
Serial.println(“WiFi connected”);
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print(“Command from MQTT broker is : [”);
Serial.print(topic);
int p =(char)payload[0]-‘0’;
// if MQTT comes a 0 turn off LED on D2
if(p==0)
{
digitalWrite(LED_PIN, LOW);
Serial.println(" Turn Off LED! " );
}
// if MQTT comes a 1, turn on LED on pin D2
if(p==1)
{
digitalWrite(LED_PIN, HIGH);
Serial.println(" Turn On LED! " );
}
Serial.println();
} //end callback

void reconnect() {
// Loop until we’re reconnected
while (!client.connected())
{
Serial.print(“Attempting MQTT connection…”);
// Create a random client ID
String clientId = “ESP8266Client-”;
clientId += String(random(0xffff), HEX);
// Attempt to connect
//if you MQTT broker has clientID,username and password
//please change following line to if (client.connect(clientId,userName,passWord))
if (client.connect(clientId.c_str()))
{
Serial.println(“connected”);
//once connected to MQTT broker, subscribe command if any
client.subscribe(“OsoyooCommand”);
} else {
Serial.print(“failed, rc=”);
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 6 seconds before retrying
delay(6000);
}
}
} //end reconnect()

void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
}

void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();

}

You don’t have any publish or subscribe topics in there.

Try the other suggestion with a different firmware that’s easier for you to understand. Otherwise, you need to learn how to write some code that does stuff over MQTT

@flamingm0e Actually in connect() the ESP is subscribing to a topic called “OsoyooCommand”. And in the callback() the ESP is listening for a “1” to turn on the LED and “0” to turn it off.

@cbirchy87 So can you try this config?

In your configuration yaml:

mqtt:
  broker: broker.mqtt-dashboard.com
  port: 1883
  client_id: some_name
  keepalive: 60
  username: your_username
  password: your_password

And also in configuration.yaml:

switch:
  - platform: mqtt 
    command_topic: "OsoyooCommand"
    payload_on: "1"
    payload_off: "0"

Unfortunately your ESP code doesn’t publish the state of the LED back to a topic that HASS can subscribe to, so the Switch has to work in “optimistic” mode, meaning it will flip back and forth each time you press the switch in the HASS frontend and may lose sync with the actual state of the LED if an MQTT command message doesn’t make it to your device. It should work well enough though.

Keep in mind I have no idea how mqtt-dashboard works, for example if it’s public or not and if many devices will be subscribing to that command topic and receiving commands. If that’s the case you may find the led turning on and off unexpectedly as many people publish commands.

Much better would be to set up HASS’s embedded broker by adding the bare mqtt: statement to your configuration.yaml:

mqtt:

Then, in your ESP sketch, the variable “mqtt_server” should be set to your HASS instance’s IP address.

AWESOME! thank you! The code was from the tutorial that was using a broker. I changed this part in code for the IP of my Hass.io.

Thank you!

I would also strongly recommend reading https://www.hivemq.com/mqtt-essentials/. That site contains an essentials series that explains MQTT in very clear terms for someone who has never used it before. I once you grasp the basic concepts is actually very simple to understand, use, and troubleshoot mqtt.

Missed that. I’m used to seeing proper topic strings, and wasn’t looking at an odd ball like that. I would recommend against using that as a topic personally.

Totally agree. The code is a mess, but it could be possible to get it working.

The single most useful, succinct description I’ve encountered on my 2-week journey. Mosqutto is just the middle-man!