MQTT Switch : Value template for State Topic payload

Hey y’all,

I’m trying to use a state topic for a mqtt switch to figure out its on/off state. Here’s the switch config I’m using :

- unique_id: Relay
      name: "Relay"
      state_topic: "data/fetch"
      value_template: "{{ value_json.object.RO1_status}}"
      command_topic: "data/down"
      payload_on: '{"devEui":"00134", "confirmed":false, "fPort":6, "data":"#1E7"}'
      payload_off: '{"devEui":"00134", "confirmed":false, "fPort":6, "data":"#1F7"}'
      qos: 0
      retain: true

Below is an example of a payload that I receive on my state topic:

{
    "deduplicationId": "abcde",
    "time": "2025-01-17 23:22:42",
    "deviceInfo": {
        "tenantId": "afbfcfde",
        "tenantName": "xxxxabcde",
        "tags": {}
    },
    "confirmed": false,
    "data": "01234abcde",
    "object": {
        "RO2_status": "OFF",
        "RO1_status": "ON"
    },
    "rxInfo": [
        {
            "uplinkId": 0123401234,
            "rssi": -65,
            "snr": 24,
            "channel": 2,
            "rfChain": 1,
            "metadata": {
                "region_config_id": "01234US",
                "region_common_name": "1234US"
            },
            "crcStatus": "CRC_OK"
        }
    ],
    "txInfo": {
        "frequency": 0123400,
        "modulation": {
            "lora": {
                "bandwidth": 125000,
                "spreadingFactor": 8,
                "codeRate": "CR_1_2"
            }
        }
    }
}

The switch shows up as lightning icons. When I turn on the switch, the lighting “on” icon doesn’t turn green - it just stays black. Same thing for when I turn it “off”. I’m not sure it’s parsing the state value correct (ie. RO`1_status)? The on/off payload command does go through though - the appliance turns on/off.

Any suggestions? Also, can I have the toggle icon instead of the lighting ones?

I assume you’ve altered that response as that JSON is not valid with "uplinkId": 0123401234 — you can’t have leading zeros in integers. Same for frequency.

You need to add:

state_on: 'ON'
state_off: 'OFF'

Read the docs:

The default for these values is payload_on and payload_off when they are defined, which they are in your case. You need to override them. Your value_template is fine.

1 Like

Thanks. Works great now.

Sorry about the invalid content - I was trying to change payload details to hide original info. Had no clue they’d end up incompatible.

1 Like