Global variable workarounds - multiple sensor values based on the same intermediate calculation

Hi, i’m slowly getting the hang of things - building my first custom sensor templates + dashboard. Enjoying learning and getting closer to what I want. This is about the Electricity flow to and from my house.

There are 6 values I want available for my dashboard. Three that come directly from the sma solar panel integration, (renamed because I find their naming confusing): grid2home, home2grid, solarproduction, and 3 that are calculated: homeconsumption Overproduction and el_flow

the three calculated values all use the same intermediate calculation, which I would normally want to do with global variables

Do I…

  1. create 3 sensors, each repeating a large chunk of code from the others?
  2. create ‘intermediate sensors’ that calculate intermediate values, and call these sensor values instead of repeating code?
  3. create 1 sensor with 5 attributes (would that help me in not repeating the chunks of code?)

Here’s what I have now, as you can se

el_flow:
      friendly_name: Electricity Net Outward Flow
      unit_of_measurement: "W"
      value_template: >- 
        {% set solarproduction = states('sensor.sb5_0_1av_41_706_pv_power')|int %}
        {% set grid2home = states('sensor.sb5_0_1av_41_706_metering_power_absorbed')|int %}
        {% set home2grid = states('sensor.sb5_0_1av_41_706_metering_power_supplied')|int %}
        {% if grid2home > 0 %} #UnderProduction
          {% set Overproduction = 0 %}
          {% set ElFlow = 0 - grid2home %}
          {% set HomeConsumption = 0 - solarproduction- grid2home %}
        {% else %} #OverProduction
          {% set Overproduction = 1 %}
          {% set HomeConsumption = solarproduction - home2grid %}
          {% set ElFlow = home2grid %}
        {% endif %}
        {{ElFlow}}

Consider using a Jinja macro to factor out the intermediate calculations.

Or, a trigger-based sensor with an action block where you calculate the intermediate values as top-level variables and put the ultimate calculations in attributes (and/or the state).

A traditional template sensor where the intermediate values are attributes is probably not the way to go. I think you risk the intermediate values being stale with that approach.

1 Like

How about using namespace? would that be a good alternative to a global variable?