relatively new to ha and playing around with automations. Did get to work quite a lot of things but stuck on a simple Task for nearly 3 hours now…
Easy because I am only trying to concat Strings and a sensor value for the paload of an MQTT Message. Checked it in Template checker where that results in ‘{text: “Bezug 297 W”, “rainbow”: false, “duration”: 10, “color”:“#fc031c”, “icon”: 58276}’ what seem relatively good to me.
For future reference, here’s how to use a script variable to define a complex value (i.e. a dictionary with five keys). I recently used this method for publishing MQTT payloads to control a fan.
following those examples I started rewriting some of my automations because … errrm… it was / still is a big amount of ‘spaghetti-code’.
I wanted to get things to work an not knowing how to write it correctly I ended up generating really long automation blocks with a lot of nested if / else and conditions always repeating the same actions simply changing some values to send (in this whole block the action is always sending mqtt message, only payload changes).
Following your example I wanted to strip down the whole Block to building the dictionary based on some changing parameters without repeating code but was not able to get it working.
What I would want do do ist somethin like this (obviously not working like that nor the 12 other ways I tried)
- id: 'mqtt_tibber_price'
alias: MQTT tibber price
description: ''
trigger:
- platform: time_pattern
minutes: '1'
condition: []
action:
- variables:
"{% set price_lvl = { state_attr('sensor.electricity_price_XXXXX', 'price_level') } %}"
"{% if price_lvl == 'VERY_CHEAP' %}"
"{% set color = '#33a000' %}"
"{% set icon = 57917 %}"
"{% elif price_lvl == 'NORMAL' || price_lvl == 'CHEAP' %}"
"{% set color = '#f6ff00' %}"
"{% set icon = 57585 %}"
"{% elif price_lvl == 'EXPENSIVE' || price_lvl == 'VERY_EXPENSIVE' %}"
"{% set color = '#fc031c' %}"
"{% set icon = 57921 %}"
"{% else %}"
"{% set color = '#fc031c' %}"
"{% set icon = 9184 %}"
"{% endif %}"
msg:
text: "{{ states('sensor.electricity_price_XXXXX')|float(0) }} €"
rainbow: false
duration: 10
color: "{{ color }}"
icon: "{{ icon }}"
- service: mqtt.publish
metadata: {}
data:
qos: '2'
retain: false
topic: awtrix_xxxxxx/custom/tibber
payload: '{{ msg | to_json }}'
So as you can see the variable is like any other part of Home Assistant YAML.
icon is the variable name - but then you put the Jinja underneath it (indented) that outputs the actual value of the variable.