Configuring: light:- platform: mqtt

Hi guys!

I’m trying to configure my light via MQTT.
If have command topic: “/h_room_sw-2/cmd”
To turn light On I’ve to send “GPIO,5,1” payload
To turn light Off I’ve to send “GPIO,5,0” payload

State I can get through “/h_room_sw-2/R1/State” topic.
And when light is On I get “1” and “0” when light is off.

I made the following configuration:

light:
  - platform: mqtt
    name: "hall_light_add"
    command_topic: "/h_room_sw-2/cmd"
    state_topic: "/h_room_sw-2/R1/State"
    state_value_template: "{{'GPIO,5,1' if value == 1 else 'GPIO,5,0'}}"
    payload_on: 'GPIO,5,1'
    payload_off: 'GPIO,5,0'
    qos: 0
    optimistic: false

And can succesfully turn light on, but in few seconds controll turns to off, but in state topic I can see the “1”.

I tried different configuration, but did not understand, how to get right state of the control.

Hope for help!

Valera

The received payload is probably a numeric string, not an integer, so change the test in your template from this:

if value == 1

to this:

if value == '1'

As an alternative, you can simplify the template to this:

    state_value_template: "GPIO,5,{{value}}"

Yes, you are right. Problem with type. This config:

if value == '1'

works fine. But in some reason -

 state_value_template: "GPIO,5,{{value}}"

doesn’t work.

Thanks for help.

Valera

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic is resolved. This helps other users find answers to similar questions. For more information, refer to guideline 21 in the FAQ.

That’s odd because it worked for me. Here’s how I tested it:

I created this MQTT Light:

light:
  - platform: mqtt
    name: "test_light"
    command_topic: "test/cmd"
    state_topic: "test/state"
    state_value_template: "GPIO,5,{{value}}"
    payload_on: 'GPIO,5,1'
    payload_off: 'GPIO,5,0'

and then used MQTT Explorer to publish a value of 1 to the topic test/state. As a result, light.test_light was changed from unknown to on.

Not sure why it didn’t work for you but at least you have another way to solve it (by simply adding quotes to the '1' value in the template).

Interesting thing, now the second way works fine too. May be I made some mistake in configuration that time. It’s looks better, so I will use this configuration.

Thank you again!!!

1 Like