I’ve got a little question, I’m trying to build a sensor, the main state is just a simple on/off switch basically but with different words, but there’s like 50 lines of code inside the Value-template. I would like some of these data to be visible as a attribute of the entity. But I’m unable to vind how to reference from a attribute_template back to the original value-template. Ofcourse I’m able to copy/paste the complete code inside the attribute_template, but this kind of defeats the purpose for me as this would mean if I change one thing I need to copy/past it to all the attribute_templates also.
- platform: template
sensors:
start_charge_time:
friendly_name: Start charge time
value_template: >
{% set hours_left = states('sensor.battery_hours_left') | int %}
{% set current_hour = now().hour %}
{% set latest_hour = current_hour + hours_left %}
{% set today_price = states.sensor.nordpool_kwh_nl_eur_3_095_021.attributes.today %}
{% set tomorrow_price = states.sensor.nordpool_kwh_nl_eur_3_095_021.attributes.tomorrow %}
{% set battery_size = states('input_number.battery_capacity') | int %}
{% set target_charge_level = states('input_number.charge_target') | int %}
{% set battery_charge_speed = states('input_number.charge_capacity') | int %}
{% set charge_kwh = (battery_size / 100 * (target_charge_level - states('sensor.battery_level') | float)) %}
{% set charge_time_minutes = ((charge_kwh / battery_charge_speed) * 60) | round(0) %}
{% set charge_time_hours = (charge_time_minutes / 60) | round(0, 'ceil') %}
{% set future_price = today_price[now().hour:] + tomorrow_price %}
{% set inteval_start_tomorrow = 0 %}
{% set interval_start_hour = now().hour + 1 %}
{% set interval_end_tomorrow = 1 %}
{% set interval_end_hour = 23 %}
{% set low_interval_length = charge_time_hours %}
{% set all_price = today_price + tomorrow_price %}
{% set interval_price = all_price[interval_start_hour + 24 * inteval_start_tomorrow : interval_end_hour + 24 * interval_end_tomorrow] %}
{% set last_considered_interval_index = hours_left%}
{% set ns = namespace(current_best_average=1000, current_best_index=-1) %}
{% for price in interval_price[:last_considered_interval_index] %}
{% set current_average = interval_price[loop.index0:loop.index0+low_interval_length] | average %}
{% if current_average < ns.current_best_average %}
{% set ns.current_best_average = current_average %}
{% set ns.current_best_index = loop.index0 %}
{% endif %}
{% endfor %}
{% set start_index = ns.current_best_index %}
{% set best_interval_price = interval_price[start_index:start_index + low_interval_length] %}
{% set best_interval_start_hour = 24 * inteval_start_tomorrow + interval_start_hour + start_index %}
{% set best_interval_price = interval_price[start_index:start_index + low_interval_length] %}
{% set start_charge_datetime = (now() + timedelta(hours=best_interval_start_hour - now().hour)) - timedelta(minutes = now().minute) %}
{% set stop_charge_datetime = start_charge_datetime + timedelta(minutes=charge_time_minutes+10) %}
{% set start_charge_time = start_charge_datetime.strftime('%Y-%m-%dT%H:%M:%S') %}
{% set stop_charge_time = stop_charge_datetime.strftime('%Y-%m-%dT%H:%M:%S') %}
{% if start_charge_datetime - timedelta(minutes=10) <= now() %}
Start
{% else %}
Wait
{% endif %}
attribute_templates:
time: >
{{ start_charge_datetime }}
If you convert your sensor to the current state-based configuration (instead of the legacy method your sensor is currently using) you can use the this variable to access attributes… i.e. {{ this.attributes.charge_time_hours}}
Aaah, sounds good, i’ve got no clue what this means at the moment, or how to accomplish it, but I’ll dive into it!
But for now, this means you create one code inside a sensor and are able to derive the main state and multiple attributes from that single code part right?
The variables you define within one option’s template cannot be referenced in another option’s template. The variable’s scope is limited to the option where it’s defined.
In other words, the variable start_charge_datetime you defined in the value_template option cannot be referenced outside of that option (like you attempted to do in the template for time).
It’s not quite that simple… From what I have tried, it seems that it is currently best practice to use the full template when defining the state. If you try to define attributes then use the this variable in the state template you end up with errors and non-functional sensors. But, you can define attributes and use the this variable to refer to those values when defining other attributes.
Move everything in the value_template, except the last five lines, into the time attribute to compute the charging start time. Then modify the first line in value_template (i.e. state in modern format) to reference the time attribute.
That’ll conform to the documentation’s example which shows a sensor’s state template referencing its own attributes via this.
This indeed would make the start time visible, but I would like to make the steps from within the code visibleAs attributes and show a simple ‘charge’ or ‘wait’ as the main sensor. So I converted the code to the new format, and managed to make it all work and make the start time also visible on the main sensor, referenced from the state to the attribute.
But I’m running into 2 issues with this code, when I try to implement the if/else statement to convert the time to an easy to read format it won’t go, and makes the whole sensor unavailable.
and the last attribute: “stop_charge” won’t calculate. it just show’s a “-”
Could you take a look? I feel like it is a really obvious thing, but I can’t seem to see it…
ow, wait, my problem is exactly what you were describing right? is that the reason why my if/else statement fails?
The funny thing is I’m able to return the state of an attribute back to the main state and display it, but I’m not able to use it with a if/else statement. seems kind of strange to me.
If the value of start_charge is a string containing nothing more than a single hyphen - then the calculation performed in the state option’s if-else will fail. You can’t subtract a timedelta object from a string.
Mmmm, sound logical, but the start_charge attribute returns a datetime component, not only a single hyphen (I think) And these exact calculations work with the old format. Both for the stop_charge calculation and the if/else statement.
Aah, so I think I solved it. I removed the attribute reference and copied the calculations into a separate attribute, so all the calculations are done inside the attributes, and the “state” only reference directly to a attributes.