Dimmer and ESP8266 with MQTT connecting to Home Assistant.

Dimmer and ESP8266 with MQTT connecting to Home Assistant.
By RobotDyn Support
More from this author

Dimmer and ESP8266 with MQTT connecting to Home Assistant.

In this tutorial, you'll learn what you need to know to get started dimming power with MQTT and Home Assistant.

1. Preparing your Arduino IDE

Copy and paste the code below into your Arduino IDE, make sure to select ESP8266 as your board, and the correct COM port is selected. Fill in the information for your WiFi credentials (your WiFi network must be on the same network as the Raspberry Pi), your user name and password for Home Assistant, and the IP address of the MQTT/HA.

You’ll also need to install two additional libraries to have everything ready for your ESP8266:

 

/******************************************************************************
Example_Dimmer1L_ESP8266_HA.ino
Example for controlling a dimmer using an MQTT HA slider
by: RobotDyn

This sketch connects the ESP8266 to a MQTT broker and subcribes to the topic
dimmer/power. When the slider is pressed, the client will change a dimming level from 0 to 99.
******************************************************************************/
#include <RBDdimmer.h>
#define outputPin  4 
#define zerocross  5 // for boards with CHANGEBLE input pins

dimmerLamp dimmer(outputPin, zerocross); //initialase port for dimmer for ESP8266


#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// WiFi Network Credentials
const char *ssid =  "_____";   // name of your WiFi network
const char *password =  "_____"; // password of the WiFi network

// Home Assistant Credentials. Optional if HA MQTT have user.
const char *HA_USER = "_____";
const char *HA_PASS = "_____";

// MQTT Network
IPAddress broker(xxx,xxx,xxx,xxx); // IP address of your MQTT broker eg.
const char *ID = "Example_Dimmer";  // Name of our device, must be unique!!!
const char *TOPIC = "dimmer/power";  // Topic to subcribe to
char *STATE_TOPIC = "dimmer/power/state";  // Topic to publish the light state to

char msg[50];

WiFiClient wclient;

PubSubClient client(wclient); // Setup MQTT client

// Handle incomming messages from the broker
void callback(char* topic, byte* payload, unsigned int length) {
  String response;
  int power_L;  
  
  for (int i = 0; i < length; i++) {
    response += (char)payload[i];
  }
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  Serial.println(response);
  power_L=response.toInt();
      dimmer.setPower(power_L);
      delay(50);
      snprintf (msg, 50, "%ld", dimmer.getPower());
      client.publish(STATE_TOPIC, msg);
      Serial.print("State ");
      Serial.println(msg);

  
}

// Connect to WiFi network
void setup_wifi() {
  Serial.print("\nConnecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) { // Wait for connection
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

// Reconnect to client
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if(client.connect(ID,HA_USER,HA_PASS)) {
      client.subscribe(TOPIC);
      Serial.println("connected");
      Serial.print("Subcribed to: ");
      Serial.println(TOPIC);
      Serial.println('\n');
    } else {
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  dimmer.begin(NORMAL_MODE, ON); //Initialize the dimmer
  Serial.begin(115200); // Start serial communication at 115200 baud
 
  delay(100);
  setup_wifi(); // Connect to network
  client.setServer(broker, 1883);
  client.setCallback(callback);// Initialize the callback routine
}

void loop() {
  if (!client.connected())  // Reconnect if connection is lost
  {
    reconnect();
  }
  client.loop();
}

 

Once the code has been uploaded, open the terminal window to make sure that the light is successfully connected to WiFi, and has connected to the MQTT network. This is helpful to check if the ESP has established a successful connection to your router and to the Mosquitto broker. You can also see the messages the ESP is receiving and publishing.

 

2. Preparing your Home Assistant and MQTT broker

Even though the server is running in the background, Home Assistant doesn't know what topics the MQTT clients are subscribing to and publishing too. To fix that, we'll need to get Home Assistant to subscribe to those same topics, which is done by adding the components to the configuration file. Go back to the configurator tab and open the configuration.YAML file again.

The device we'll add is the "light" component, just like when we added the MQTT component, it doesn't matter where we add the "light" to the configuration file, but to keep things organized, we'll add the following lines below the MQTT initialization.

light:    
  - platform: mqtt
    name: "Example_Dimmer"
    state_topic: "dimmer/power/state"
    command_topic: "dimmer/power"
    on_command_type: brightness
    payload_on:                    "99"
    payload_off:                   "1"
    brightness_state_topic: "dimmer/power/state"
    brightness_command_topic: "dimmer/power"
    brightness_scale:              99
    qos:                           1
    retain:                        true
    optimistic:                    false

The "light" uses the MQTT platform and has a name called "Example_Dimmer".

Once the dimmer ("light") components have been added, we'll need to save the configuration file again, check that the configuration is valid, and restart the server. Once the server has been restarted click Overview from the left menu bar. From there you should see your light and switch components, if not you may need to troubleshoot.

If you're able to see your components, clicking on the slide switch of the light or the lightning bolt symbol of the switch will turn the Dimmer. You'll also see that from Home Assistant, the light bulb symbol of the light is also turned on. Home Assistant is able to know what the state is of the MQTT light by using the state_topic both in the configuration file as well as publishing the topic from the Arduino sketch. If we had removed the state_topic from the "light", we would be able to control the light, but we wouldn't be able to see from Home Assistant if the work is dimmer or not.

*** If you get to have the flicking of the light when level less 5% and over 95%, change brightness_scale: 95. Maybe the AC power frequency is not stable.

 

December 1, 2021
Comments