Process a MQTT string only if start with a specific character

Hello,
i have an esp32 with tasmota sending mqtt data to home assistant.
Home assisstant receive 2 type or strings:

10:08:40.337 MQT: tele/BatteryMonitor/RESULT = {"SSerialReceived":":R51=1,\n:r51=1,27,3000,2000,0,0,0,100,0,0,3040,100,100,100,0,0,1,\r\n"}
10:08:40.716 MQT: tele/BatteryMonitor/RESULT = {"SSerialReceived":":R50=1,\n:r50=1,243,2532,1450,77914,272348,302933,166440,129,0,99,0,334,2518,\r\n"}

I only need the R50 string and the 51 only gives me problems when home assistant process it.
This is the configuration i use to handle the mqtt (ther are other 4 sensors after this one)

  - trigger:
      - platform: mqtt
        topic: tele/BatteryMonitor/RESULT
        encoding: ""
    sensor:
      - name: BatteryMonitor-Temperatura
        unit_of_measurement: "°C"
        state: "{{ (trigger.payload.split(',')[9] | float-100) }}"

How can i configure it to only tank in consideration the R50 string and not the R51?

If the received payload doesn’t contain the string R51 then the template extracts the desired value. If the payload does contain the string, the template reports the sensor’s existing value (this.state).

  - trigger:
      - platform: mqtt
        topic: tele/BatteryMonitor/RESULT
        encoding: ""
    sensor:
      - name: BatteryMonitor-Temperatura
        unit_of_measurement: "°C"
        state: >
          {{ trigger.payload.split(',')[9] | float(0) - 100
            if 'R51' not in trigger.payload else this.state }}
1 Like

Tank you, this did not quite work because i’ve now seen that the string sometimes contain both r50 and r51.

{"SerialReceived":":R50=2,\n:r50=2,224,2531,4040,153115,390102,837886,183181,130,0,0,0,293,0,\r\n:R51=2,\n:r51=2,27,3000,2000,0,0,0,100,0,0,3040,100,100,100,0,0,1,\r\n"}

I’ve modified your code and now it’s working, it just bugs out sometimed (maybe ther is something that changes in the string that i don’t know)
This is the updated code if someone needs it

  - trigger:
      - platform: mqtt
        topic: tele/BatteryMonitor/RESULT
    sensor:
      - name: BatteryMonitor-Temperatura
        unit_of_measurement: "°C"
        state: >
          {{ (trigger.payload.split(',')[9] | float-100)
            if 'R50' in trigger.payload else this.state}}

Now, another quick quyestion. if i have this string

{"SerialReceived":":R50=2,\n:r50=2,224,2531,4040,153115,390102,837886,183181,130,0,0,0,293,0,\r\

can i force Home assistant to only read from n:r50= to 183181 or it must read until the \r?

That’s a very different situation from the two examples you originally provided where it was either R50 or R51 but not both. It’s understandable that the template I had suggested wouldn’t work for that situation.

May I ask why you aren’t using the Tasmota integration to receive data from the device?