Here’s an alternative solution:
I created a sensor and assigned it the following value:
[286,244,126]
Here it is in the Developer Tools > States view:
Although the sensor’s value looks like a list, an entity’s state
always contains a string. However, we can convert the string to a list with the from_json
filter. After being converted to a list, we can easily select the desired item from the list. Here is proof that it works:
The templates do not need to end with the int
filter because the result of any template is a string (so the inclusion of a terminating int
is unnecessary in this situation).
Here are the Template Sensors with the compact templates:
sensor:
- platform: template
sensors:
mainpowerl1:
friendly_name: "Main L1 Power"
unit_of_measurement: 'W'
value_template: "{{ (states('sensor.main_power_energy_power') | from_json)[0] }}"
mainpowerl2:
friendly_name: "Main L2 Power"
unit_of_measurement: 'W'
value_template: "{{ (states('sensor.main_power_energy_power') | from_json)[1] }}"
mainpowerl3:
friendly_name: "Main L3 Power"
unit_of_measurement: 'W'
value_template: "{{ (states('sensor.main_power_energy_power') | from_json)[2] }}"
mainpowertotal:
friendly_name: "Main Total Power"
unit_of_measurement: 'W'
value_template: "{{ states('sensor.mainpowerl1')|int + states('sensor.mainpowerl2')|int + states('sensor.mainpowerl3')|int}}"
NOTE
Both the original template (using split
and strip
) and this one (using from_json
) will fail if the sensor’s value is None
or unavailable
. If there’s a possibility that the value can be anything other than the desired format (three comma-delimited integers wrapped in square-brackets) then the template needs to test for this possibility and handle it gracefully.