Sonoff RF Bridge. Strategies for receiving data

Interesting though: when I trigger my python script service from the developer tools my script indeed receives a proper dict tested with some dummy json. Its only from the automation trigger where the template ‘’{{trigger.payload_json}}’ is transferred as string.

Thank you for sharing this. I like the second method a lot. I cleaned up the Python script a bit and thought I’d share with you all:

entities = {
    '5AE488': ['sonoff_remote_btn_1', 'ON', 'false'],
    '5A848C': ['sonoff_remote_btn_2', 'ON', 'false'],
}

payload = data.get('payload')

if payload in entities:
    try:
        topic, state, retain = entities[payload]
    except ValueError:
        topic = 'unknown'
        state = payload
        retain = 'false'
        logger.warning(
            '<rfbridge_demux> Received invalid RF command: {0}'.format(payload)
        )
    
    service_data = {
        'topic': 'home/{0}'.format(topic),
        'payload': '{0}'.format(state),
        'qos': 0, 
        'retain': '{0}'.format(retain),
    }
    hass.services.call('mqtt', 'publish', service_data, False)

# Remove these last lines if you don't want to fill your log everytime your
# bridge catches a signal that you're not working with.
else:
    logger.warning(
        '<rfbridge_demux> Received unregistered RF command: {0}'.format(payload)
    )

One of these days I’m actually going to get round to changing to use this Python script rather than ‘strategy 1’ which I use now.

Is it possible to have the Python script write unknown codes to file of my choosing rather than the HA log?

Didn’t you ask this same question about 3 weeks ago? I answered it in post #114, showing how to modify the python_script to use the File Notification sensor you’ve already created to store unknown codes to a file.

1 Like

Embarrassingly, almost.
I asked how to log only if a boolean was on but you also provided a way to write to a file.
Doubly embarrassingly I even have the amended script ready to use in my python_scripts folder for when I make the change.

Sorry, and thanks.

I’m using the original script in node red. What does this one do different? I tried pasting this one and got a bunch of errors in node red.

It’s really not that different from the original one, except that it will log events with payloads that are not registered in entities dictionary. Are those the errors you’re seeing?

The script I shared is just a bit cleaner and “pythonic”, but at the end of the day it’ll do the same.

@ashscott
@AhmadK

Hi Guys,

THIS IS A WARNING MESSAGE for anyone wanting to play with ESPHome on RF Bridge.

I was tempted by you. I spent two days reconfiguring my RF Bridges:
First, I used Demux script with my Tasmota based bridge - it works great thanks for this thread…

but later…

I was tempted to run ESPHome on my second RF Bridge - I wanted better response and range as suggested.

  1. I did hardware hack to RF Bridge (it’s easy - the most difficult task is to solder a wire to tiny leg no. 10 of the chip (Hint: I managed to do properly is by covering/securing the other legs with duct-tape)
  2. I flashed device with ESPHome 1.14.3 with single door sensor (sending on/off signals so two binary sensors are needed in ESPHome YAML for the single sensor). Worked brilliantly and much faster than TASMOTA.
  3. I managed to teach the ESPHome to send/transmit quite complicated RF signal for my HomeCinema Screen - required RAW code dump from the other bridge (the one with Tasmota and Portish firmeware), but EPSHome RF Bridge worked like charm!
  4. I managed to do single(!) clean-and-nice automation that will translate every sensor defined in ESP Home to related MQTT signal - without any need for change to automation if you add or remove some sensors from ESPHome. (I can share it you want)

Then… I added all my door/window sensors and RF buttons/remotes (24 binary sensors in total) and… landed into the problem:


This is ESPHome issue. Home Assistant disconnects repeatably from RF Bridge making it unusable. It happens when you have around 10 sensors defined (or more) - the sensors exposed by ESP Home are blinking from unavailable to available, the log is full of “connect” and “disconnect” events on both sides.

Warning: This issue definitely repeatable if you define many sensors (~10+) in ESPHome on Sonoff RF Bridge.

Summarizing, for now, I stay with Tasmota flashed Bridge (with Portish firmware) and Demux solution. it’s great anyway. I’m going to monitor the status of bug/fix on EPSHome page in the meantime.

5 Likes

thanks for the warning.
my ESPHome node disconnects quite often but I thought it’s a connectivity issue. need to check it using another esphome device to make more definitive conclusion.

This is definitely not due to connectivity issues, but ESPHome API issues. The ESP device stays online (accessible from another computer via ESPPortal), but it HA connects and disconnects immediately. Then HA re-tries connection again after some period of time and again connecting and disconnecting immediately.

I guess… just after connection large number of binary_sensors on ESP side is trying to send their current state to HA via API and some breaking “conflict” emerges causing HA to disconnect. It can be seen in HA log that it sees corrupted API responses. I can see if the number of sensors is lower (below 10) the problem disappears. It looks like multi-thread synchronization problem or something (random), which is more likely to happen if larger number threads are concurrently running (bigger probability of conflict if many competing resources are doing their job)

Anyway… I’ll stay for some time with Tasmota and Demux strategy. I’ll give aother try to ESPHome version when fix is provided.

I received a Sonoff RF Bridge yesterday, flashed it and began playing around with a couple of buttons. I ended up writing a little Appdaemon script to handle automatically creating all the sensors and updating them. I came across this topic which covers similar approaches so I figured if anyone here is using Appdaemon, this may be a viable approach for you too.

It’s set up to allow for momentary buttons and other generic binary_sensors like motion sensors and contact sensors. It currently doesn’t retain the states of those sensors, but that would be an easy feature to add.
Anyway, it’s available here : https://github.com/rando-calrissian/rf2mqtt

1 Like

with what?

Latest Tasmota.

Important bit it is :wink:

Finally, I found time to change to use this and so far so good.
Except, I get an error every time I receive an unknown code if my logging boolean is turned on…

ERROR

Error executing script: '__import__'
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/python_script/__init__.py", line 196, in execute
    exec(compiled.code, restricted_globals)
  File "rfbridge_demux.py", line 58, in <module>
KeyError: '__import__'

Line 58 is:

service_data = {'message':'{} - {}'.format(datetime.datetime.now().strftime("%d %b, %X"), p)}

PYTHON SCRIPT

if p is not None:
  if p in d.keys():
    service_data = {'topic':'433/{}'.format(d[p][0]), 'payload':'{}'.format(d[p][1]), 'qos':0, 'retain':'{}'.format(d[p][2])}
    hass.services.call('mqtt', 'publish', service_data, False)
  else:
    x = hass.states.get('input_boolean.log_unknown_rf_codes')
    if x is not None and x.state == "on":
      # logger.warning('<rfbridge_demux> Received unknown RF command: {}'.format(p))
      service_data = {'message':'{} - {}'.format(datetime.datetime.now().strftime("%d %b, %X"), p)}
      hass.services.call('notify', 'log_unknown_rf_codes', service_data, False)

Never mind, I changed it to publish the unknown code and then have an automation act on that.
That way I can easily also create a persistent notification too.

Well, I say never mind but it would be interesting to know why it didn’t work…

I believe strftime() is unavailable in python_script.

See this thread post:

Tomato-tomahto but I prefer checking for the existence of a key rather than falling to an exception for handling the “unknowns”. I dunno but that could be why node red doesn’t like it…

If I have 2 rf bridge how must mod the config?
the first : tele/sonoff_rf/RESULT
second: tele/sonoff_rf2/RESULT

You need to have an automation like this (I have 5 rf bridges):

- alias: 'rfbridge_demultiplexer'
  trigger:
  - platform: mqtt
    topic: tele/Garage_RF_Bridge/RESULT
  - platform: mqtt
    topic: tele/RF_bridge_west/RESULT
  - platform: mqtt
    topic: tele/RF_bridge_east/RESULT
  - platform: mqtt
    topic: tele/RF_bridge_stable/RESULT
  - platform: mqtt
    topic: tele/RF_bridge_1st_floor/RESULT
  action:
  - service: python_script.rfbridge_demux
    data_template:
      payload: '{{trigger.payload_json.RfReceived.Data}}'