Template variable error: ‘state’ is undefined when rendering ‘{% if value_json is defined and value_json[‘buffered’] == “no” and value_json[‘device’] == “NMCTCB806Z” %} {{ value_json[‘values’][‘edischarge1_tot’] | int / 10 }} {% else %} {{ state.state }} {% endif %}’
This is the configuration.yaml section:
- name: Pietro - Discharged (Total)
state_topic: energy/growatt
value_template: >
{% if value_json is defined and value_json['buffered'] == "no" and value_json['device'] == "NVCPB04031" %}
{{ value_json['values']['edischarge1_tot'] | int / 10 }}
{% else %}
{{ state.state }}
{% endif %}
unique_id: pietro_discharged_total
device_class: energy
unit_of_measurement: "kWh"
icon: mdi:solar-power
- name: Enrica - Discharged (Total)
state_topic: energy/growatt
value_template: >
{% if value_json is defined and value_json['buffered'] == "no" and value_json['device'] == "NMCTCB806Z" %}
{{ value_json['values']['edischarge1_tot'] | int / 10 }}
{% else %}
{{ state.state }}
{% endif %}
unique_id: enrica_discharged_total
device_class: energy
unit_of_measurement: "kWh"
icon: mdi:solar-power
The concept is that the mqtt service gives me the values of 2 different inverters with the same label. So I created 2 sensors that save the data if they have the right “device” value inside, otherwise the previous value must remain. State.state should theoretically return the value of before.
The sentors work correctly, but sometimes give this error and I don’t know why.
If that doesn’t work, then you can’t do what you want with that setup and you should move to template sensors with an MQTT trigger. Seems like that’s what you should be using anyways because your topic appears to be an event stream of information.
EDIT: Just keep in mind that these will be unknown until they get the first piece of data. From that point forward they will always have data. Even after restart/reboot.
After you point it out to me it’s so obvious!
Thanks so much for the tip!
I’ve never seen the construct with the triggers you gave me! I will study it and then try to apply it.
However it also works as I did.
Yeah, I’m not sure if this is available in MQTT entities though, so you may get the same error. I know 100% that this is available in template entities.