Help with Lambda to publish a message

Hi there,

I’m using the excellent bodymiscale custom component to capture two weights from my Xiaomi scales but the way the code has been designed, the weight value is not persistent and if ESPHome is upgraded (which happens quite frequently lately), the weight value is lost and the entity returns a value of unknown.

I’m wondering if someone knows Lambda well enough to add a mqtt.publish Action that would publish the read weight to a defined topic with retain enabled as I think that would be a good workaround? Current code I’m using below.

sensor:
  - platform: xiaomi_miscale
    mac_address: '12:34:56:78'
    weight:
      name: "Xiaomi Mi Scale Weight"
      id: weight_miscale
      on_value:
        then:
          - lambda: |-
              if (id(weight_miscale).state >= 67 && id(weight_miscale).state <= 80) {
                return id(weight_user1).publish_state(x);}
              else if (id(weight_miscale).state >= 45 && id(weight_miscale).state <= 65) {
                return id(weight_user2).publish_state(x);}

  - platform: template
    state_class: measurement
    name: Weight Pete
    id: weight_user1
    unit_of_measurement: 'kg'
    icon: mdi:weight-kilogram
    accuracy_decimals: 2
    
  - platform: template
    state_class: measurement
    name: Weight Ali
    id: weight_user2
    unit_of_measurement: 'kg'
    icon: mdi:weight-kilogram
    accuracy_decimals: 2

@xbmcnut did you find a solution?

Nope, but ending up adding the following automation as a workaround.

- alias: 'Publish weight values when scales change'
  trigger:
    platform: state
    entity_id: sensor.weight_pete, sensor.weight_ali
  action:
    service: mqtt.publish
    data_template:
      payload: "{{trigger.to_state.state}}"
      topic: "tele/scales/{{trigger.to_state.object_id}}" 
      retain: true

Take a look at my post from a while ago: A new approach for Xiaomi BLE Temperature sensors with ESPHome, MQTT and pyscript where on the ESPHome/ESP32 device, I construct an MQTT message an publish it. This might give you some hints.

1 Like

Thanks, nice solution. I’ve got the later model that generates impedance as well and pulling the data in via the HACS Passive BLE Monitor integration which was already set up.

Just put together a Node-Red flow to pull in the measurements, split for the person then publish to MQTT (as a single JSON of both weight and impedance) as a retained message.

I then pull the MQTT topics into 2 sensors for each person to pass to the bodymiscale integration to get the other stats. Solves the 2 person issue and the retention issue so you always have the latest data on the Card (one for each person) even through a reload.

TIMTOWTDI

can you share the person publish MQTT code?