I want to create template logic to use the nordpool electricity price integration like a “volume” on a stereo so I can optimize the heating in the house to let it run exact x cheapest hours of the day.
The sensor gives me cost / hour / day and I can get it into an array like
{% set np = state_attr('sensor.nordpool_kwh_se4_sek_2_10_025','today')%}
np: {{np}}
sorted: {{np|sort}}
With the output
np: [0.9, 0.87, 0.89, 0.9, 0.91, 0.92, 0.95, 1.01, 1.08, 1.14, 1.14, 1.15, 1.13, 1.09, 1.11, 1.16, 1.22, 1.29, 1.33, 1.2, 1.11, 1.1, 1.05, 0.94]
sorted: [0.87, 0.89, 0.9, 0.9, 0.91, 0.92, 0.94, 0.95, 1.01, 1.05, 1.08, 1.09, 1.1, 1.11, 1.11, 1.13, 1.14, 1.14, 1.15, 1.16, 1.2, 1.22, 1.29, 1.33]
But I need to add the hours in the array and join the sorted “volume” of the hour in this array.
I can genereate the output that I am looking for in PowerShell, but I am lacking the array template ninja skills do do it in HA.
This is how it looks in PowerShell that I am trying to achieve in HA/Template, see the array in the end.
$spotPrice = @(
0.9, 0.87, 0.89, 0.9, 0.91, 0.92, 0.95, 1.01, 1.08, 1.14, 1.14, 1.15, 1.13, 1.09, 1.11, 1.16, 1.22, 1.29, 1.33, 1.2, 1.11, 1.1, 1.05, 0.94
)
$h=0
$psObj = @()
foreach($price in $spotPrice){
$psObj +=[PSCustomObject]@{
Hour = $h
Price = $price
}
++$h
}
$psObj2 = @()
$i = 24
foreach($line in ($psObj | Sort-Object Price -Descending)){
$psObj2 +=[PSCustomObject]@{
Hour = $line.hour
Price = $line.price
PriceHourVolume = $i
}
--$i
}
<# Value based "volume" of each hour
Hour Price PriceHourVolume
---- ----- ---------------
18 1.33 24
17 1.29 23
16 1.22 22
19 1.2 21
15 1.16 20
11 1.15 19
10 1.14 18
9 1.14 17
12 1.13 16
14 1.11 15
20 1.11 14
21 1.1 13
13 1.09 12
8 1.08 11
22 1.05 10
7 1.01 9
6 0.95 8
23 0.94 7
5 0.92 6
4 0.91 5
0 0.9 4
3 0.9 3
2 0.89 2
1 0.87 1
#>
I have done some similar stuff before that i have posted on my gist, but I want to take to the next level.
ferroamp - charge or discharge battery sensor with home assistant and nordpool (github.com)