MQTT switch using JSON?

Hello,

I am using MQTT lights on JSON Schema for a while now and I like issuing commands and receiving response/status in JSON format eg. {"state": "ON"} / {"state": "OFF"}.

I wonder if it is possible to use JSON format also fot the MQTT switch. For the state I managed to parse it with: value_template: '{{ value_json.state }}'. But I do not have an idea how to issue a command in JSON format trough command_topic…?

For now I use MQTT Lights also for other switches, but it does not seem really the right way to do it, but it works :slight_smile:

thanks

Hmm, I think I figured it out :wink:. It works with defined payload_on/off and state_on/off.
I tried it before but I had problems with quuotation… this is my working config:

switch:
  - platform: mqtt
    name: mc2_light_4
    state_topic: "K5/N0/mc2/lig4"
    command_topic: "K5/N0/mc2/lig4/set"
    value_template: '{{ value_json.state }}'  
    payload_on: '{"state":"ON"}'
    payload_off: '{"state":"OFF"}'
    state_on: "ON"
    state_off: "OFF"
    optimistic: false
    retain: false
    qos: 0
5 Likes

did you get this working, any chance you can show what your HA panel/Card looks like.

G

Hello,

sorry for late reply, I didn’t catch the new message.
Once you have the switch working right (as written above) you can use it in usual ways.

Example of the switch in lovelace (the basic entities view):

ui-lovelace.yaml:
- entities:
    - entity: switch.mc2_light_4  
  show_header_toggle: false
  title: Test Switch
  type: entities    

customize.yaml:
switch.mc2_light_4:
  friendly_name: "Test switch 4"

TestSwitch