Anyone can help me, please? I am trying to make a MQTT sensor which will show me the temperature as state and a “string state” as attribute, but I don’t know how to use that json attribute option.
This is what I have till now:
- name: Computer Ambient Temperature
state_topic: "tele/ZigBee_BridgeV/545C/SENSOR"
unit_of_measurement: "°C"
icon: mdi:thermometer
value_template: >
{% if is_number(value_json['ZbReceived']['Computer_Air_Quality']['EF00/0212'] | multiply(0.1) | float | round(1)) %}
{{ value_json['ZbReceived']['Computer_Air_Quality']['EF00/0212'] | multiply(0.1) | float | round(1) }}
{% else %}
{{ states('sensor.computer_ambient_temperature') }}
{% endif %}
json_attributes_topic: "tele/ZigBee_BridgeV/545C/SENSOR"
json_attributes_template: >
{ "string_state": "
{% set stat = states('sensor.computer_ambient_temperature') %}
{% if stat <= 13 %} {{ 'very low' }}
{% elif stat >= 15 and stat <= 18 %} {{ 'low' }}
{% elif stat >= 20 and stat <= 25 %} {{ 'normal' }}
{% elif stat >= 27 and stat <= 30 %} {{ 'high' }}
{% elif stat >= 32 %} {{ 'very high' }}
{% else %}
{{ state_attr('sensor.computer_ambient_temperature', 'string_state') }}
{% endif %}
| tojson " }
json_attributes_template is meant to extract information directly from the JSON payload received by tele/ZigBee_BridgeV/545C/SENSOR. Refer to the example in the documentation and you’ll see that you’re not using it the way it was meant to be used.
Yes, I know, but there is any way to use as pure template, without extracting the json? Or to convert the template to a json? I don’t know… I just want to achieve something like in my bad code, but to work
I want to add some custom attributes to my mqtt sensor… Attributes which are the result from some conditions, like: mqtt_attribute name “string_state”, mqtt_value " if a =b result should be “1”, if a != b result should be “2”… Something like this, which have nothing to do with the json extraction
Something like “attributes_template” should work, but there is no option like this
I think that the only way to achieve what I want is from the value_template… adding two values then to split them when I add it to lovelace… But this is a little silly way do to it… There is no other way?
The example shows how three attributes are created (with different names from the ones in the payload) and each attribute’s value is computed by a template.
I don’t have the means to easily test it so I am not sure if MQTT Sensor accepts this.state. I assume it does but you’ll know for sure after testing it.
EDIT
Correction. Overlooked to terminate the template with }}before the dictionary’s closing }
json_attributes_template: >
{ "string_state":
{% set stat = states('sensor.computer_ambient_temperature') | float(0) %}
{{ 'very low' if stat <= 13 else
'low' if 15 <= stat <= 18 else
'normal' if 20 <= stat <= 25 else
'high' if 27 <= stat <= 30 else
'very high' if stat >= 32 else
state_attr('sensor.computer_ambient_temperature', 'string_state') }} }