I am trying to set my HUE light bulbs from an mqtt automation trigger. I am sending the payload as JSON and trying to parse the json using the service_template and data_template to set the light entity state and brightness.
I am not using the light component because my purpose is a little more complicated, I have an Android application that is talking with HASS through MQTT and I want to control a dimmer light connected to HASS from the application.
There does not seem to be a way to evaluate the trigger using dev tools, so its a process of elimination by updating the automation and sending the mqtt message using the service, then checking the logs.
If you look at the documentation for automation templating for mqtt, it seems to indicate using trigger.payload_json, but using that throws an error that it cannot be found.
UndefinedError: ‘dict object’ has no attribute ‘payload_json’
Yes, payload_json but not payload.json, small but important difference
Payload give you just the raw payload and payload_json gives you a JSON parsed dictionary of the payload.
Your payload has the keys “topic” and “payload”, that’s why you need two times payload. For your method to work the payload would need to look like this:
Maybe this needs to be escaped or something. I am using the developer tools to post the MQTT message but not escaped. I will try it both ways to see if payload_json shows up.
The problem with this solution is if you want to turn the light off, you cannot also set the brightness, it breaks the automation and throws an error in logs:
Error while executing automation automation.mqtt_dimmer_switch. Invalid data for call_service at pos 3: extra keys not allowed @ data['brightness']
So this needs to be broken into two automations, both reading the same MQTT message. One for turning on or off the lights, the other for setting the brightness but with a conditional. If the state is “on” then set the brightness, if the state is “off” do not attempt to set the brightness with the automation.