Saturday, December 16, 2023

Home Assistant 101: Adding MQTT Devices

 


This is a companion article for the Home Assistant 101 video that discusses how to integrate MQTT devices into Home Assistant.

If you are not familiar with MQTT and how it works, it is strongly suggested that you view the following video first:  MQTT 101: Integrate your DIY Devices into Home Assistant.  This video provides information on how MQTT works, how it can be added to your own DIY electronic projects and highlights of how those devices can be integrated into Home Assistant.

This article and related video go into a bit more detail on the Home Assistant integration side.  It includes multiple examples and provides a starting reference for manually integrating MQTT devices that do not have a native Home Assistant integration.

YAML and Home Assistant Configuration Files


Unfortunately, at least as of the time of this publication, integrating MQTT devices into Home Assistant requires that you write these in YAML if the device does not have a native integration.  If you are already familiar with YAML and how Home Assistant configuration files work, you may want to just skip this section.

YAML (YAML Aint' Markup Language) is the language Home Assistant uses for its configuration files.  While this isn't intended to be a YAML tutorial... you can find plenty of YAML tutorials online... I will mention a few things to be aware of when working with YAML in Home Assistant.

First, all top level integrations or domains (thing like switches, sensors and lights) can only appear once across all your configuration files.  The only exception is if you are using Home Assistant packages... and frankly if you are using packages, you don't need this YAML primer!

By default, unless you've split out your configuration file (again, if you've done this, you probably don't need this info), you will find these top level domains in your main configuration.yaml file.  Each top level domain will have its own "section" with all entities of that type underneath:

Example:

light:
  - name: Family Room
    ...
    
  - name: Kitchen
    ...

sensor:
  - name: Bedroom Temperature
    ...
    
  - name: Basement Humidity
    ...
    
switch:
  - name: Entry Hall
    ...
    
  - name: Guest Bedroom
    ...

Note that any of these entity types that were auto-discovered by Home Assistant or added through another integration will not appear here (so don't expect to find all your lights, sensors, switches and other entity types here).  These sections are only for entities that you are manually defining... which is what we will be doing for MQTT entities.  It is possible that you may not even have one or more of these integrations listed.  

All that is well and good, but a change made to Home Assistant in 2022 moved MQTT to a top level platform.  That means when working with MQTT entities, you first begin with MQTT at the top, then each type of domain under that:

mqtt:
  light:
    - name: Family room
      ...
    - name: Kitchen
      ...
  sensor:
    - name: Bedroom Temperature
      ...
    - name: Basement Humidity
      ...
  switch:
    - name: Entry Hall
      ...
    - name: Guest Bedroom
      ...

The mqtt: tag should only appear once and like top-level domains, each of these (e.g. light, sensor, switch) only appear once under the MQTT header.  Individual MQTT entities appear under the appropriate section.

Theoretically according to the documentation, you can repeat the domains under MQTT:

mqtt:
  light:
    - name: Family room
  sensor:
    - name: Bedroom Temperature
  light:
    - name: Kitchen
  sensor:
    - name: Basement Humidity
  switch:
    - name: Entry Hall
    - Guest Bedroom

Personally, I think this not only makes your configuration file longer, but more difficult to follow and locate a given entity.  But you may have your own reasons for organizing your MQTT entities in this manner.  So in my case, you will see all entities of a given type under a single domain tag.

In addition, if you see an example YAML file (like most of mine), you may see all the various integration types like light, sensor, switch and even automation and script in one file (this is known as a package), including a section of MQTT entities.  When moving this to your Home Assistant configuration, you should split out each type (light, switch, etc.) and move into the proper location in your own configuration, making any other changes needed, like name, etc.

One other important note about YAML:  It is very strict on indentation.  As a general rule, when indentation is required, it is two spaces.  This is not the same as a <tab>.  Depending on your editor, using the <tab> key is different than entering two spaces and it will cause an error when trying to validate you YAML.  Always be sure that you are using spaces and not the <tab> key for indentation (or make sure your editor inserts spaces when using the <tab>).  You could also pick up tabs when copying/pasting code from another source.  If possible, try to always copy the "raw" code from places like Github when possible to avoid copying over tab characters.

OK... that's going to do it for the brief YAML primer.  Again, check online resources if you want to learn more about YAML.

Determine the Device's MQTT Topics and Payloads


Again, this is not an article about MQTT or how it works.  If you are unfamiliar with MQTT, I recommending watching this video for a primer on MQTT and an overview of how it works with Home Assistant:  MQTT 101: Integrate your DIY Devices into Home Assistant.

To integrate the MQTT device into Home Assistant you will need to know the MQTT topics and expected payloads for those devices.  This will generally be provided by the device's or code repository's documentation.  

Example MQTT Documentation

Note that you do not necessarily need to integrate all topics offered.  For example, a power-monitoring smart plug may publish volts, amps and watts.  You may just want one (or none) of these values in Home Assistant.  You can just skip creating MQTT entities in Home Assistant for any that you do not want. Do note that for most brokers, capitalization matters:  /Load, /load and /LOAD are three different topics.

MQTT Explorer

If you are going to be working with MQTT entities, it can be very handy to have a utility to see topics and values actually being published to the MQTT broker.  I highly recommend a free utility called MQTT Explorer.  Versions are available for Windows, Mac and Linux.

MQTT Explorer - Click to enlarge

MQTT Explorer will allow you to log into your MQTT broker and see all the topics and payloads.  You can even publish and MQTT message directly.  This can be an invaluable tool when troubleshooting MQTT issues, especially where documentation may be missing or payloads are delivered in a different format than expected.  It can also be used to clear out "stuck" retained topics.

Determine the Type of Home Assistant Entity to Create


Once you have the MQTT topic(s) and the type of payload it is sending (e.g. raw value, JSON, etc... more on this below), you are ready to start creating the appropriate YAML entities.  First you need to determine the "type" of entity.  Currently at time of publication, Home Assistant supports the following types of MQTT entities: 
Some types of MQTT topics/payloads can be integrated into more than one type of Home Assistant entity.  For example, an MQTT topic that published a simple text value could be integrated into Home Assistant as either a sensor or text.  This will depend upon how you wish to use it and the different option for each type of MQTT integration.  Similarly, a basic light (without brightness, color and other settings) could be integrated as either a light or a switch.

For this particular article, I'm going to focus on just three types of entities to get you started: sensors, switches and lights.  And I won't even be covering all the available options for those here.  To know more about any particular MQTT entity type (and the optional available, click on the link above for the official Home Assistant documentation, or do a search for "Home Assistant MQTT <entity_type>".

A Basic Home Assistant MQTT Sensor


To begin, let's start with a simple, basic MQTT sensor.  This sensor will simply show the contents of a payload.  As always, we need to know the MQTT topic and expected payloads.  From the device's documentation, which is a multi-function matrix, we see the following MQTT topics:


If we want to create a sensor that simply contains the current mode of the device:

mqtt:
  sensor:
    - name: Matrix Mode
      topic: "stat/matrix/mode"

That's it!  Under the MQTT root integration/header (see above), we add a sensor section if it doesn't already exist.  Then we give the sensor an entity name, in this case the entity will be called sensor.matrix_mode and contain the payload of the MQTT topic.


Now we can display this on a dashboard just like any other sensor:


Also note that just like normal sensors, we could add additional attributes and properties, like friendly name, icon, etc. to our sensor definition above:

mqtt:
  sensor:
    - name: Matrix Mode
      state_topic: "stat/matrix/mode"
      friendly_name: Matrix Display State
      icon: mdi:dots-square  

But for a basic sensor, only a name and topic are required.  Any time a new MQTT message is published on the topic by the device, the sensor (and dashboard display) will update automatically.  Note that here we are using 'state_topic', meaning we are reading or getting the data from the device.  Later we'll use 'command_topic' when we want to send data back to the clock.

Similarly, you could add basic sensors for the other values shown in the documentation above in the same manner:

    - name: Matrix Brightness
      state_topic: "stat/matrix/brightness"
      friendly_name: Matrix Brightness Level
      icon: mdi:brightness-4

    - name: Matrix Temperature
      state_topic: "stat/matrix/temperature
      friendly_name: Matrix Temperature
      unit_of_measure: "°F"
      icon: mdi:thermometer

Since these are sensors, you can only retrieve/display the values.  If you want to control the values (in other words, publish a message back to the device if the device's MQTT supports it), then we need to create a different type of entity such as a switch or number entity that allows us to change the value... and publish that value back to MQTT.  An example of this will follow.  But first, we need to address payloads that aren't 'simple' where a single value is published as the payload for a given topic as shown in the examples above. Often, a payload may contain multiple values, such as in a payload that arrives in JSON.

Dealing with JSON Payloads (or other serialized formats)


Often, a device will publish multiple values under a single topic by using JSON for the payload.  For example, here is a real topic and payload from a Tasmota device:

MQTT Topic:  tele/washer/STATE

Payload:
{
  "Time": "2023-12-04T22:28:19",
  "Uptime": "68T05:59:11",
  "Heap": 15,
  "SleepMode": "Dynamic",
  "Sleep": 50,
  "LoadAvg": 19,
  "POWER": "ON",
  "Wifi": {
    "AP": 1,
    "SSId": "C2H6O",
    "BSSId": "74:83:C2:BD:F2:3A",
    "Channel": 6,
    "RSSI": 94,
    "LinkCount": 1,
    "Downtime": "0T00:00:07"
  }
}

(Note: Tasmota devices can now be natively integrated into Home Assistant via the Tasmota integration.... see note below)

JSON is a data structure that use key:value pairs and is often used with MQTT to send multiple values in a single payload.  So, how do you get the value(s) you want from this payload into one or more sensors in Home Assistant?

Luckily we can use a value template and function to pull particular values out of the JSON payload:

    - name: Smart Plug Load Average
      state_topic: "tele/washer/STATE"
      value_template: "{{value_json.LoadAvg}}"

A template is a piece of code that is surrounded by a pair of double curly-braces ( {{... }} ).  Then within the template we use value_json. followed by the key we will to extract the value from.  In this case, it is going to extract the value for the LoadAvg key in the JSON payload... and the value of the sensor will be 19.

Now, occasionally the JSON will use nested properties... a property that has more than one of its own properties.  You can see that above with the "Wifi" property... which has a number of individual objects/properties under it.  Here's another example:

MQTT Topic: tele/washer/SENSOR
Payload:
{
  "Time": "2023-12-03T18:40:14",
  "ENERGY": {
    "TotalStartTime": "2019-09-25T02:06:00",
    "Total": 73.424,
    "Yesterday": 0.042,
    "Today": 0.166,
    "Period": 1,
    "Power": 282,
    "Voltage": 119,
    "Current": 2.056
   }
   "TempUnit": "F"
  }

In this case, all the energy-related values are sub-grouped under the "ENERGY" key.  How do you do this in YAML?

    - name: Smart Plug Watts
      state_topic: "tele/washer/SENSOR"
      value_template: "{{value_json.['ENERGY'].Power}}"
      unit_of_measure: W

In this case, in the value template, you simply first list the key that has the subkey that you want ( ['ENERGY'] ), the a dot and the key you want (Power).  In the above payload example, this sensor would have the value of 282.  Unit of measure is optional, but name, state_topic and value_template are required.  So putting this all together from the top, we'll create four sensors from our energy-monitoring smart plug (load average from one MQTT topic and watts, volts and amps from another):

mqtt:
  sensor:
    - name: Smart Plug Load Average
      state_topic: "tele/washer/STATE"
      value_template: "{{value_json.LoadAvg}}"

    - name: Smart Plug Watts
      state_topic: "tele/washer/SENSOR"
      value_template: "{{value_json.['ENERGY'].Power}}"
      unit_of_measure: W
   
    - name: Smart Plug Volts
      state_topic: "tele/washer/SENSOR"
      value_template: "{{value_json.['ENERGY'].Voltage}}"
      unit_of_measure: V

    - name: Smart Plug Amps
      state_topic: "tele/washer/SENSOR"
      value_template: "{{value_json.['ENERGY'].Current}}"
      unit_of_measure: A

You now have four separate sensor entities in Home Assistant that can be used just like any other sensor for automations, scripts or to display on a dashboard.  So, sensors are great for getting and using data from the MQTT device.  But want if you want to send commands to the MQTT device to control or change it?  That's the next topic.

Note: The value_json function also supports bracketed notation, so the following are equivalent:

"{{ value_json['ENERGY'].Voltage }}"
"{{ value_json['ENERGY]['Voltage'] }}"


Other Payload Formats

While JSON is probably the most common format for MQTT payloads beyond simple values, there are others you may run across.  XML is another common format or it could even be something like a list of semi-colon delimited values.  In these cases, you just have to use the template and functions to parse out the value of interest.  In Home Assistant, the templating language is currently Jinja2 and there are some Home Assistant extensions as well.  To learn more, please see the following documents:


A Note About Tasmota Devices

While the above examples show integrating a Tasmota device into Home Assistant (and not too far in the past this was how it had to be done), you can now install the Tasmota integration and Tasmota devices will be automatically integrated into Home Assistant.  MQTT is still used in the background and must be configured both in Home Assistant and on the Tasmota device, but you no longer have to manually create the YAML for integration.  See the official Tasmota documentation for more details.

I'm simply using Tasmota as an example of MQTT topics and payloads... and you can still integrate those devices the old YAML way like this if you wish.

MQTT Command Topics


While sensors are great for collecting data published by MQTT devices, they don't allow us to control that device.  For control, we need an entity that can pubish an MQTT command that is subscribed to by the device.  Once again, we need to know the topics and valid payloads.



Note that for some devices, the state topic and the command topics are very similar, the only difference using cmnd/ for the command topics and stat/ for the state topics.  Other devices may use the same MQTT topic for both state and power.  But with this information, we can now create Home Assistant entities to both show the current state and actually control the device.  I'll start with a simple switch entity.

A Home Assistant MQTT Switch


Basic Home Assistant Switch shown in an Entities Card

Switches serve two main purposes.  First, they show the current state of the device (normally 'on' or 'off').  But they also allow control of that device by toggling the slider in the display.  How are these created in Home Assistant YAML?

mqtt:
  switch: 

Once again, we start with the mqtt: base integration and add a switch: section.  Remember that unless you are using packages, the mqtt: should only appear once.  If you've already created it for something like sensors, don't add mqtt: again.  Instead just add a switch: section underneath the existing.  You then add all your MQTT switches under this switch section.

    - name: Bar Side Lights
      command_topic: "cmnd/barlights/POWER"
      state_topic: "stat/barlights/POWER"

That's all that's really required for an MQTT switch.  And technically the state_topic is optional if the device uses the same topic for both the command and state.  However most devices will have a separate topic for these two values to prevent ghosting as a results of retained flags (see the video MQTT 101: Integrate your DIY Devices into Home Assistant to learn more about retained flags and how improper use can cause your lights or devices to randomly turn on or off on their own).

But this basic definition makes some assumptions that may not work for your device.  For one, it assumes the payloads for both the command and state are "OFF" and "ON".  So in many cases, like the second (made-up) example above for my game sign, you may need to include a payload for the command topic.  And you may also need to include the payload for the state topic if it isn't "ON" or "OFF" or is different from the command payload. Personally I like to include the topics even if they are the defaults, just as a little extra documentation in my code.  So a more 'normal' MQTT switch definition might look like this:

    - name: Game Sign
      command_topic: "cmnd/gamesign/POWER"
      state_topic: "stat/gamesign/POWER"
      payload_on: "1"
      payload_off: "0"
      state_payload_on: "ON"
      state_payload_off: "OFF"
      retain: false

Since this particular fictional example uses "1" and "0" as the command payloads for turning the device off and on, you have to specify those commands in the payload_on: and payload_off: lines.  And since the payloads for state are different from the command payloads, you also have to list the on/off values for the state_payload_on: and state_payload_off:.  Whenever the value for the payload received on the state_topic: matches the state_payload_on: value, the switch will have an "on" state in Home Assistant and "off" when the value matches the state_payload_off:.  If the topic/payload doesn't exist or the value is something other than the values for the state payloads, then the switch will have an 'unknown' state in Home Assistant.

Similarly, when you toggle the switch in Home Assistant, Home Assistant will publish an MQTT message on the command_topic: with either the payload_on: or payload_off: value depending on the new state of the Home Assistant switch.

There are many additional properties available and you may want to also include an availability topic that lets you know whether the device in online or not.  You can also use a value template for extracting the state value from something like a JSON payload, similar to how this is shown under sensors above.  See the documentation on Home Assistant MQTT Switches for a complete list and description of the various options and settings.

The final property in the above example is the retain: flag.  This indicates whether the command topic published should be retained or not.  As a general rule, command topics should not be retained and if you omit this property, it defaults to false, so the line as shown above is not really needed.  It is shown only if you have an unusual situation where you do need to retain the command topic payload.  Use true with caution as it can lead to ghosting issues as described above.  See the above video as well for more info on the retained flag.

A Home Assistant MQTT Light


The final type of MQTT entity I'm going to cover is an MQTT light.


MQTT lights are very similar to switches when it comes to command and state topics for power.  However, a number of additional command and state topics for things like brightness, color and even effects are available with MQTT lights if your device, such as a smart RGB light bulb or dimmer switch support them (and makes the appropriate MQTT topics available).  Furthermore, some of these topics/functions may or may not be available depending upon the type of MQTT schema being used by the device:


But let's start with a basic example of a light that supports a brightness setting (this could be either a smart bulb or something like a wall dimmer that controls a light):

mqtt:
  light:

Again, we start with our mqtt: and a light: section in our configuration, adding them only if they don't already exist.  All defined MQTT lights will be listed under light: 

    - name: "basement"
      command_topic: "cmnd/bmstlight/POWER"
      state_topic: "stat/bsmtlight/RESULT"
      state_value_template: "{{ value_json.POWER }}"
      brightness_command_topic: "cmnd/bsmtlight/Dimmer"
      brightness_state_topic: "stat/bsmtlight/RESULT"
      brightness_value_template: "{{ value_json.Dimmer }}"
      payload_on: "ON"
      payload_off: "OFF"

OK... let's break this down.  The light entity has a command topic and state topic for sending commands and receiving the current state, just like a switch entity.  Note that for this example, the state is being received as part of a JSON payload, so the value is extracted via the state_value_template: and value_json. just like the sensor JSON examples above.

But this MQTT device also supports controlling and reporting the state of a brightness setting.  So there is an brightness_command_topic: for sending a value to the device to set the brightness and a brightness_state_topic: for receiving the current brightness setting from the device.  To change the brightness of the device, you simply publish an appropriate value to the brightness command topic and that change is reflected back in the brightness state topic.

This is advantageous because you don't need to create separate sensor entities and separate entities like number to set and control the brightness of the light.  It is all part of the light entity and controls for brightness are included with the light entity in Home Assistant.

In addition there are many other available command and state topics for controlling and receiving the state of lights, such as color, color temperature, effect, etc. if the device supports them and uses a supported MQTT schema:

rgb_command_topic:
rgb_state_topic:

color_temp_command_topic:
color_temp_state_topic:

effect_command_topic:
effect_state_topic:


There are many, many more including support for RGBW and RGBWW lights, dealing with colors in HS or XY values instead of RGB, etc.  And most of the command and state topics also support value_templates: for extracting the data or formatting the payloads appropriately. Again, any of these that are added to the MQTT light will be available as part of the light entity in Home Assistant so they do not need to be created as separate MQTT entities (but they could be if you really need or want to).

See the Home Assistant MQTT Light documentation for a complete list of available properties and supported options.

A Complete Example 


So, let's put all this together and show the complete integration of a fictitious dimmer that controls overhead lights and also has power monitoring.  For those familiar with Tasmota, you'll note that I'm using standard Tasmota topics here, but you can now natively integrate Tasmota devices into Home Assistant (see the note on Tasmota above).  So this is just an example to bring it all together.

Note:  Please do not try to copy/paste this directly into your own Home Assistant YAML.  Not only will there likely be differences in things like topics, copying and pasting from places like this blog will mess up formatting like indentation, which as mentioned, YAML is very particular about!  Instead use this as a guide for integrating your own devices.

mqtt: 
  sensor:
  # ---------------------------------------
  # Kitchen overhead dimmer power and temp
  # ---------------------------------------
    - name: "Kitchen Main SW1 Power"
      state_topic: "tele/kitchohdim/SENSOR"
      value_template: "{{value_json['ENERGY'].Power }}"
      unit_of_measurement: "W"
      icon: mdi:flash-circle

    - name: "Kitchen Main SW1 Temp"
      state_topic: "tele/kitchohdim/SENSOR"
      value_template: "{{value_json['ANALOG'].Temperature }}"
      unit_of_measurement : "°F"
      icon: mdi:thermometer

  light:
     # ----------------------------------
     # Kitchen Overhead Lights Dimmer
     # -----------------------------------
    - name: "Kitchen Main Dimmer"
      state_topic: "stat/kitchohdim/RESULT"
      state_value_template: "{{ value_json.POWER }}"
      command_topic: "cmnd/kitchohdim/POWER"
      availability_topic: "tele/kitchohdim/LWT"
      brightness_state_topic: "stat/kitchohdim/RESULT"
      brightness_command_topic: "cmnd/kitchohdim/Dimmer"
      brightness_scale: 100
      brightness_value_template: "{{ value_json.Dimmer }}"
      payload_on: "ON"
      payload_off: "OFF"
      payload_available: "Online"
      payload_not_available: "Offline"    
      retain: false

The above creates three new entities in Home Assistant:


In this case, two sensors and a light.  These can be used just like any other entity.


And I've only covered the basics of three types of MQTT entities here... sensors, switches and lights.  Check out the list above for all the other types of MQTT entities available and each of their various integration options.

Using MQTT Devices in Automations


While the primary purpose of this article was to cover how to integrate MQTT devices into Home Assistant, it is worth mentioning the basics on how you can use MQTT entities in automations, both as a trigger and as an action to publish MQTT payloads back to the devices (e.g. to control those devices).

MQTT as an Automation Trigger

Naturally if you've created an entity in Home Assistant such as a sensor or switch, you can use the state of that entity as a trigger.  But you can also use an MQTT topic directly as an automation trigger without even creating the Home Assistant entity.  Any time the payload for the specified MQTT topic changes, the trigger can be evaluated for launching the automation.  This can be done both in the UI editor and via YAML:

No Payload Specified

MQTT Automation Trigger in the UI Editor
YAML equivalent:

trigger:
  platform: mqtt
  topic: "stat/matrix/brightness"

In this example, anytime the payload value is published and different from the prior value on the "stat/matrix/brightness" topic, the automation will fire.  You can add whatever actions are appropriate, such as setting an input_number to the current brightness value. 

When a payload value is not specified as part of the trigger, you can retrieve the current value of the payload with a special templated value: 

"{{ trigger.payload }}"

So, as an example of setting an input number to the brightness value when the MQTT topic changes, your automation might look like this:

automation:
  - alias: Matrix Brightness Changed
    trigger: 
      platform: mqtt
      topic: "stat/matrix/brightness"
    action:
      - service: input_number.set_value
        target:
          entity_id: input_number.matrix_brightness
        data:
          value: "{{ trigger.payload }}"

Any time a new brightness payload is published, the input number will automatically update to the new brightness value and this can be shown on a dashboard:


Note that the above only updates the input number/slider to the current value.  Changing the slider to a different number does not change the brightness of the matrix.  That requires publishing an MQTT message back to the clock and is covered below.  Also note that using trigger variables currently requires entry directly in YAML.... this may change in later Home Assistant releases.


Specific Payload Listed


YAML equivalent:

trigger:
  platform: mqtt
  topic: "stat/matrix/mode"
  payload: "Clock"

In this case, the trigger also contains a payload.  The automation will only fire when a new payload is received on the MQTT topic that exactly matches the payload in the trigger (Clock in the example).  If any other payload is received, the automation will not run.

Using MQTT in Service Calls (Publishing MQTT topics)


To publish an MQTT message (normally to change or control an MQTT device), we can use a service call in the action section of an automation or script.  As always, you need to know the correct topic and the expected format/values of the payload from the documentation:


Once you have that information, you can create an automation action or script to publish an MQTT message to the device:


Publishing an MQTT message in the UI Editor

YAML Equivalent:

action:
  service: mqtt.publish
  data:
    topic: "cmnd/matrix/brightness:
    payload: "{{ states('input_number.matrix_brightness') }}"

Note that you can publish a fixed value or you can use a template (as shown in these examples), but you cannot do both.  If you enter both in the UI editor, the fixed value is used and the template is ignored.

The above is an example of how the slider shown above can control the matrix brightness in addition to just showing the state.  For the complete automation, you just use a state change of the slider as a trigger to publish an MQTT message with the new brightness.

automation:
  - alias: Matrix Brightness Changed
    trigger: 
      platform: state
      entity_id: input_number.matrix_brightness
    action:
      - service: mqtt.publish
        data:
          topic: "cmnd/matrix/brightness
          payload: >
            "{{ states('input_number.matrix_brightness') }}"

Whenever the slider value changes, an MQTT message will be published on the appropriate topic with the current value of the brightness slider as the payload.  By using these two automations in conjunction, it assures the slider and actual brightness of the matrix are always in sync, regardless of how the brightness value is changed.

Final Thoughts and More Information


This article is only scratching the surface of how MQTT devices can be integrated and used in Home Assistant.  But hopefully you can use this article to get a basic understanding of how to begin integrating MQTT devices into Home Assistant.  And with the basic knowledge, be able to interpret the standard Home Assistant documentation on the various types of MQTT device integrations.

If you are developing devices that use MQTT in languages like Arduino/C++, Python, etc. look for another article and video coming soon that will show you how to implement MQTT discovery in Home Assistant, negating the need for you or other users of your devices to manually create all the MQTT integrations in YAML as described in this article.

Links


And here are a few additional resources that might get you started with MQTT if you are new to it or still struggling to understand it.

Home Assistant 101: Manually Integrating MQTT Devices (YouTube companion video to this article).

As always, if you have questions or thoughts, please feel free to those those down in the comments.  And thanks for reading!

If you'd like to support future content on this blog and the related YouTube channel, or just say thanks for something that helped you out, you can say thanks by buying me a one-off cup of coffee at:


2 comments:

  1. I tried using this tutorial to add in a Wink Relay that has been converted to MQTT
    Here is the yaml:
    mqtt:
    light:
    - name: "Kitchen Light"
    unique_id: kitchen_Light
    state_topic: "KitchenRelay/relays/0/state"
    command_topic: "KitchenRelay/relays/0"
    payload_on: "ON"
    payload_off: "OFF"
    retain: false
    - name: "Diningroom Light"
    unique_id: diningroom_Light
    state_topic: "KitchenRelay/relays/1/state"
    command_topic: "KitchenRelay/relays/1"
    payload_on: "ON"
    payload_off: "OFF"
    retain: false
    sensor:
    - name: "Kitchen Temperature"
    unique_id: kitchen_tenp
    state_topic: "KitchenRelay/sensors/temperature"
    value_template: '{{(float(value) * 9 / 5 + 32) | round(1)}}'
    unit_of_measurement: "°F"
    - name: "Kitchen Humidity"
    unique_id: kitchen_hum
    state_topic: "KitchenRelay/sensors/humidity"
    It appears in Node-Red and under Entities but not in Devices. From Entities I can control the light I see the two sensors but not in Devices.
    I was hoping you might see something I did wrong.

    ReplyDelete
    Replies
    1. It's a little hard to read the YAML since the formatting/indentation isn't there, but I don't see any device key listed under each of the entities. Each entity would need a device key with at least two nested keys of identifiers and name. These need to match for all the entities that are part of a device. You might take a look at my video on MQTT Discovery where I cover the device part. Although this is done on the Arduino side with JSON, you could create it on the Home Assistant side in your YAML: https://youtu.be/VHiCtZqllU8

      Delete

To help eliminate spam and to keep all conversations civil, submitted comments are moderated. Therefore your post may not show up immediately. Please be patient as most reviews are completed within a few hours.