Integration with esphome

Hi,

I have been using esphome quite significantly of late. The one thing I miss there is integration with openhab the same way it integrates with home assistant.

What would be the best way to develop such an add-on for openhab. the simplest way I was thinking would be to expose all items on over mqtt.

Since I am quite fond of both esphome and openhab, I was wondering it I could somehow help to integrate them better.

Recommendations and feedback please

Sundeep

Homie is the way to go. https://github.com/homieiot/convention

1 Like

Great news and I hope you do this as it removes a hurdle for anyone that wishes to move from Home Assistant over to openHAB. This is the main reason I have never bothered to look at esphome, as I see it as a form of ‘vendor lock in’, as I prefer to stick to devices which work well in both openHAB and Home Assistant if possible and Tasmota seems to be a better choice for me. I do not want to be locked into Apple products and equally I do not want to be locked into only openHAB or another software even if it is opensource.

Perhaps it would be useful to break down what espHome actually is and how it does this in simple terms? Correct me if I am wrong but it…

  1. Allows you to turn a ESP8266 into a useful finished device with just a few lines of YAML without knowing how to code at all, nor do you need to install an IDE.
  2. You have a backup system that stores the YAML code needed to create a new replacement device along with your HA backup files.
  3. The flashing of the code to the esp8266 is done via a webpage and does not need a 3rd party app to be installed or setup.

Does it use MQTT and just use the Home Assistant Components format? See link below… What part are you looking to implement? Without knowing more details about what esphome is and more about the general underlying concept, I suspect not many people will comment to give you help.

Is this what your looking to do? This allows you to auto discover and use devices which use the standard Home Assistant MQTT format which Tasmota uses this format for its MQTT messages.

HomeAssistant MQTT Components - Bindings | openHAB

Perhaps for some people, but that project has had no code contributions in the past 3 years. Not something I like to see when choosing a direction to take. Also did it ever get added/accepted into Home Assistant? See above as I do not like to be locked into any software brand, so Tasmota to me is more attractive as it works in more software.

Homie works in openHAB
EspHome works in Home Assistant
Tasmota works in both.

Do you already use esphome mqtt with autodiscovery turned on?

# Example Home Assistant configuration.yaml entry
mqtt:
  broker: ...
  discovery: true

This is the way I use my esphome-sensors with openhab. They are getting automatically discovered with all channels via the mqtt-binding.

(For autodiscovery to work, you have to install jsonpath-transformation and jinja-transformation, too. Like I described it here)

Hi Matt,

Thanks for the detailed post, i’ll try and reply to the many points in it :slight_smile:

Correct me if I am wrong but it…

  1. Allows you to turn a ESP8266 into a useful finished device with just a few lines of YAML without knowing how to code at all, nor do you need to install an IDE.
  2. You have a backup system that stores the YAML code needed to create a new replacement device along with your HA backup files.
  3. The flashing of the code to the esp8266 is done via a webpage and does not need a 3rd party app to be installed or setup.
  1. Yes - in just a few lines of YAML you can do a LOT. Earlier, I used to program using the arduino IDE, now use ESPHOME for all but 2-3 of my devices, rest 30 of them are on ESPHOME.
  2. Exactly - the YAML file is the backup itself. If you include other stuff - images, includes then obviously you need those as well.
  3. Yes, and no. I dont use the webpage - I find it cumbersome. I just use a command like
esphome filename.yamp run

It compiles, uploads in a single single command - takes the hassle out of many things. The logger component in esphome is awesome - everything can be logged to MQTT depending on log level set e.g.

Processing displayprototype7 (board: nodemcu-32s; framework: arduino; platform: platformio/espressif32 @ 3.3.2)
------------------------------------------------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/espressif32/nodemcu-32s.html
PLATFORM: Espressif 32 (3.3.2) > NodeMCU-32S
HARDWARE: ESP32 240MHz, 320KB RAM, 4MB Flash
DEBUG: Current (esp-prog) External (esp-prog, iot-bus-jtag, jlink, minimodule, olimex-arm-usb-ocd, olimex-arm-usb-ocd-h, olimex-arm-usb-tiny-h, olimex-jtag-tiny, tumpa)
PACKAGES:
 - framework-arduinoespressif32 3.10006.210326 (1.0.6)
 - tool-esptoolpy 1.30100.210531 (3.1.0)
 - toolchain-xtensa32 2.50200.97 (5.2.0)
LDF: Library Dependency Finder -> https://bit.ly/configure-pio-ldf
LDF Modes: Finder ~ off, Compatibility ~ soft
Found 31 compatible libraries
Scanning dependencies...
Dependency Graph
|-- <AsyncTCP-esphome> 1.2.2
|-- <WiFi> 1.0
|-- <Update> 1.0
|-- <AsyncMqttClient-esphome> 0.8.6
|   |-- <AsyncTCP-esphome> 1.2.2
|-- <SPI> 1.0
|-- <ArduinoJson-esphomelib> 5.13.3
|-- <ESPmDNS> 1.0
Building in release mode
Linking .pioenvs\displayprototype7\firmware.elf
Retrieving maximum program size .pioenvs\displayprototype7\firmware.elf
Checking size .pioenvs\displayprototype7\firmware.elf
Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
RAM:   [=         ]  13.1% (used 43024 bytes from 327680 bytes)
Flash: [=======   ]  70.4% (used 1291394 bytes from 1835008 bytes)
Building .pioenvs\displayprototype7\firmware.bin
esptool.py v3.1
Merged 1 ELF section
======================================================================================================= [SUCCESS] Took 26.87 seconds =======================================================================================================
←[32mINFO Successfully compiled program.←[0m
←[32mINFO Connecting to 192.168.1.76←[0m
←[32mINFO Uploading .esphome/build/displayprototype7\.pioenvs\displayprototype7\firmware.bin (1291504 bytes)←[0m
Uploading: [============================================================] 100% Done...

←[32mINFO Waiting for result...←[0m
←[32mINFO OTA successful←[0m
←[32mINFO Successfully uploaded program.←[0m
←[32mINFO Starting log output from displayprototype7/debug←[0m
←[32mINFO Connected to MQTT broker!←[0m
[13:16:33][I][ota:338]: OTA update finished!
[13:16:37][I][mqtt:214]: MQTT Connected!
[13:16:37][C][sntp:025]: Setting up SNTP...
[13:16:37][C][wifi:357]:   Signal strength: -46 dB ▂▄▆█
[13:16:37][C][wifi:361]:   Channel: 1
[13:16:37][C][wifi:362]:   Subnet: 255.255.255.0
[13:16:37][C][wifi:363]:   Gateway: 192.168.1.1
[13:16:37][C][wifi:364]:   DNS1: 8.8.8.8
[13:16:37][C][wifi:365]:   DNS2: 8.8.4.4
[13:16:37][C][logger:233]: Logger:
[13:16:37][C][logger:234]:   Level: DEBUG
[13:16:37][C][logger:235]:   Log Baud Rate: 115200
[13:16:37][C][logger:236]:   Hardware UART: UART0

[10:11:01][D][text_sensor:067]: 'Moon Rise Time': Sending state '2022-02-09T12:02:00.000+0530'
[10:11:33][D][sensor:113]: 'Sun Elevation': Sending state 34.70377 ° with 1 decimals of accuracy
[10:11:35][D][text_sensor:067]: 'Sun Next Sunrise': Sending state '07:02 AM'
[10:11:58][D][main:4514]: Time trigger fired!
[10:12:33][D][sensor:113]: 'Sun Elevation': Sending state 34.85507 ° with 1 decimals of accuracy
[10:12:35][D][text_sensor:067]: 'Sun Next Sunrise': Sending state '07:02 AM'

Does it use MQTT and just use the Home Assistant Components format? See link below… What part are you looking to implement? Without knowing more details about what esphome is and more about the general underlying concept, I suspect not many people will comment to give you help.

Yes, MQTT and other protocols as well : details at https://esphome.io/index.html#core-components

Getting ESPHome → Openhab to work / auto discover over MQTT is a non-issue. Christian’s reply explains the steps - very simple to implement. I have 2 dozen esp8266/32 connected into openhab that way. Albeit the auto discovered channel names are a pain - so best to explictly define in *.things and *.items

The issue I want to solve is the reverse i…e openhab → ESPHome for non mqtt things / items configured on Openhab.

Let me explain this further with the following home/weather station I recently developed

  1. I have a openweather thing on openhab, and have c 40 items configured in it. Those are the weather components you see on the image above (which is a esp32 device).
  2. I wanted to get those values in ESPHome. I guess the normal way would be to call the rest API for each item. However, its a slow method (regular polling vs push) with lots of overhead on the ESP side.
  3. So I wrote a custom rule to regularly push those value into MQTT, and set a MQTT component on ESPHOME to subscribe. It works, but involves custom coding at both the openhab and esphome side.
  4. What I want to accomplish (if possible) is to expose ALL openhab ITEMS over MQTT for value, status and command (via addon / binding). That way, bi-directional integration between esphome and openhab should be quite painless.

Does that make sense ? Happy to elaborate / discuss further …

The linked repository is to the convention/standard. There is no code. The homie standard (in its various versions) is implemented by several different firmwares.

It is in fact the only “true” standard without any vendor lock-in. Just because openHAB implements the HA discovery standard doesn’t technically make it a standard.

I did some work some time ago (that admittedly didn’t make it much further than the PoC stage) to add homie support to espurna (a tasmota “competitor”) but as I’m not using auto-discovery myself, I couldn’t really justify spending the time on it.

Had a peek at espura, seems like an interesting project. hopefully will try it out soon

See this binding as it sounds similar and may provide some java example code you can re-use.
Remote openHAB - Bindings | openHAB
It takes what is on the event bus and you could turn that into MQTT and publish it in a format you like.

A binding could easily capture the MQTT logs and redirect them into the openhab.log at a debug or trace level. Info level should not be used for logging often so those two levels can be used. However I would personally prefer to just use a command line to watch the MQTT stream and not send it to my openhab.log so I’m not sure if this is something you were wanting to implement or it was just a general like.

That is more clear and more likely to get feedback from others. My opinion is that it should not be called a ESPhome binding in that case, but something generic as there could be other use cases for wanting to do that. An event bus to MQTT binding. Was there other things that could be implemented better or was it just this one aspect?

I should also add that I have concerns if mqtt is fast enough to publish the entire event bus traffic all with a long friendly naming structure.

1 Like

Thanks - reading up on this and also on how to setup a development environment.

Agree - this is more generic binding to expose items over MQTT. Can be used for anything. Maybe an idea on implement the homie standard on this. Anyone will to partner ?

Possibly relevant:

2 Likes

This looks promising, am going to try it over the weekend. If it works - may negate the need for any new binding / add-on. Thanks for passing it on !!!

Read through the documentation, and followed the steps and finally got it working. In the end its actually quite straight forward.

You essentially need only need two steps :-

1. Following rule - the one below is created by the MQTT event bus publish binding, could as easily be written direct.

configuration:
  upd: gMQTTPubStatus
  cmd: gMQTTPubCommand
  broker: mqtt:broker:myMQTTBroker
  topicRoot: openhab
triggers:
  - id: "1"
    configuration:
      groupName: gMQTTPubCommand
    type: core.GroupCommandTrigger
  - id: "2"
    configuration:
      groupName: gMQTTPubStatus
    type: core.GroupStateUpdateTrigger
conditions: []
actions:
  - inputs: {}
    id: "3"
    configuration:
      type: application/javascript
      script: >
        if(typeof(require) === "function") Object.assign(this,
        require('@runtime'));

        var logger = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.rules_tools.MQTT_EB");


        var isState = (event.itemState !== undefined);

        var topic = "openhab/out/" + event.itemName + ((isState) ? "/state" : "/command");

        var msg = ((isState) ? event.itemState : event.itemCommand).toString();


        logger.debug("Topic: " + topic + " Message: " + msg + " Retained: " + isState);

        var mqtt = actions.get("mqtt", "mqtt:broker:myMQTTBroker");

        mqtt.publishMQTT(topic, msg, isState); // retained true for updates
    type: script.ScriptAction

2. Insert Group names against the items you want published. Above example uses gMQTTPubCommand and gMQTTPubStatus.

Thats essentially it.

Queries :

  1. The above rule is written in javascript, how can I port it to a “normal” rule and access the event object ?
  2. How do I get value of the associated thing or channel? I looked at Event Object Attributes — openHAB Helper Libraries documentation , however, am getting undefined for event.channel or event.thingUID
  3. How can I get an array of all defined items , so that their IDs can be used to fetch their status for publishing periodically on MQTT ?

Found a way for this :-

rule "mqttPublishAll2"   
when
    Time cron "0 0/1 * * * ?"
then
	gMQTTPubStatus.allMembers.forEach[obj|
		logInfo("mqttPublishAll2", "Item [" + obj.name + "] is in state [" + obj.state + "]")
	]
end

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.