#templates-archived

1 messages · Page 154 of 1

inner mesa
#

Anyway, I hope you have all the pieces that you need. It works for me.

lyric socket
#

I absolutely do and can't thank you and @silent seal enough for helping to figure this out!

inner mesa
#

better:

#
from zoneinfo import ZoneInfo
from datetime import datetime, timezone
import sys
import json

output = {
    "datetime": str(datetime.now().astimezone(ZoneInfo(sys.argv[1]))).split('.')[0],
    "timezone": sys.argv[1]
}
print(json.dumps(output))
#
sensor:
- platform: command_line
  name: Other Timezone
  command: >-
    python3 tzconvert.py "{{ state_attr('sensor.robs_iphone_13_geocoded_location', 'Time Zone') }}"
  value_template: "{{ value_json.datetime }}"
  json_attributes:
    - timezone
#
  • now includes the date and the timezone
lyric socket
#

Altered it a bit to match the needs more:

from datetime import datetime
import sys
import pytz
import json

output = {
    "datetime": datetime.now(pytz.timezone(sys.argv[1])).strftime('%a %b %d, %I:%M'),
    "timezone": sys.argv[1]
}
print(json.dumps(output))
inland peak
#

Hello everyone, could someone please help me figure out a way to send data from a presence sensor into a device tracker?
Basically, through "ESPresense" I've got a presence sensor that outputs either a room name or the words "not_home". Now, I want to use this to track people, but that function only accepts device trackers, which means my sensor won't show up in the dropdown menu.
Now, I figure a simple template could create a binary sensor, to act as a device tracker, which would read "away" when the sensor value is "not_home" and "home" when the sensor value is a room name.
Problem is, I have no idea how to make such a template.

lyric socket
#
- platform: template # Matthew Home
  sensors:
    <entity name wanted>:
      friendly_name: <friendly name>
      value_template: "{% if is_state('<mqtt_room sensor>', '<room>') %}Home{% else %}Away{% endif %}"
#
- platform: mqtt_room # "Mt_BC"
  name: "<mqtt_room sensor>"
  device_id: <device ID from mqtt/espresence>
  state_topic: espresense/rooms
  timeout: 20 # change if you like to suite needs
  away_timeout: 270 #change this too asa needed
#

Two fold process, need to make a sensor to collect from MQTT broker the ESPresece, then template that to read as you need. I use mine just to know if someone is parked in the garage though, so may need to tweek slightly as needed for the rooms part of it

#

(I use a sensors.yaml, so if you dont you will need to add the sensor: heading to those)

inland peak
#

So, way above my skill level.

#

Thank you very much

#

The first one goes in the templates.yaml, correct?

lyric socket
#

Depends how you have your config.yaml set up. I have mine broken out a bit so for me it is sensors.yaml and my config.yaml has sensor: !include sensors.yaml

inland peak
#

same way here

inland peak
#

it keps spitting invalid slug error messages

lyric socket
#

copy paste exactly what you have filled out

inland peak
#

will do, but how do you add those code boxes in discord?

inland peak
#

'''sensors:
<entity_name_wanted>: device_tracker.galaxy_watch_4
friendly_name: galaxy_watch_4
value_template: "{% if is_state('sensor.galaxy_watch_4', 'not_home') %}Away{% else %}Home{% endif %}" '''

lyric socket
#

change this
<entity_name_wanted>
to what you want the entity name to be

#

its backtic btw. usually upper right of the keyboard with ~

inland peak
#
    entity_name_wanted: device_tracker.galaxy_watch_4
    friendly_name: galaxy_watch_4
    value_template: "{% if is_state('sensor.galaxy_watch_4', 'not_home') %}Away{% else %}Home{% endif %}"```
#

like this?

lyric socket
#

Yup. feel free to actually put the name you want there

inland peak
#

replace entity name wanted, with an actual name?

lyric socket
#
- platform: template # Matthew Home
  sensors:
    matthew_home:
      friendly_name: Matthew Home
      value_template: "{% if is_state('sensor.mt_bc', 'garage') %}Home{% else %}Away{% endif %}"
#

that's my dirty config. creates an entity named sensor.matthew_home

inland peak
#
    device_tracker.galaxy_watch_4:
      friendly_name: Galaxy Watch 4
      value_template: "{% if is_state('sensor.galaxy_watch_4', 'not_home') %}Away{% else %}Home{% endif %}"```
#

like this?

lyric socket
#
- platform: template # Galaxy Watch
  sensors:
    galaxy_watch_4:
      friendly_name: Galaxy Watch 4 Presence
      value_template: "{% if is_state('sensor.galaxy_watch_4', 'not_home') %}Away{% else %}Home{% endif %}"
inland peak
#

wait, this template gives a sensor? As in a "sensor.whatever" entity?

lyric socket
#

correct. ESP presense cant be made into a device tracker, at least not yet. Reason is, it doesnt actually track anything. What it is doing is saying what a device (watch in this case) is connected to.

silent barnBOT
#

@lyric socket Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.

inland peak
#

I already have an espresense sensor, in my entities

#

I am looking for a way to make a device_tracker.whatever entity and have it so that values from the espresense sensor get copied to that device_tracker entity

lyric socket
#

and why does it have to be a device tracker?

inland peak
#

because I want to track when a person is home or not and the dropdown menu for that will not list or accept anything other than a device_tracker

lyric socket
#

mhm.
and what are you tracking them for? an automation? or just a lovelace card to say who is or is not home?

inland peak
#

both

#

I don't want some automations running when the relevant person isn't home

#

and a lovelace card can show me at a glance who is or isn't home.

lyric socket
#

perfect, then those two chunks of code will get you there.
What you need to do is alter your mindset a bit. Is a device tracker/person entity a lot easy to deal with, by far yes. Best way for that is to have everyone in the house downlaod the HA app on their phone. However, if you are like me and have someone that doesnt want the app, then you got to find new ways to do things.

For me I have a BlueCharm beacon on the persons vehicle (or in your case keys/watch/phone) and when the ESP reports to HA as it being in the garage then I template it to say Home otherwise it says Away. now for an automation that would look something like:
https://pastebin.com/MXS963gR

inland peak
#

This can be done with just a template. Running a whole automation, just for that, is wasteful

#

I already have ESPresense beacons allover the place, looing for bluetooth devices

#

it works and provides good data

#

I'd be done, if it wasn't for this one stupid inability to use the sensor in the person device tracker

#

Thanks for the effort, though.

#

I'll keep asking around.

#

I actually had a very similar template, up until a month ago, but I deleted it when it stopped being relevant for its original task.

marble jackal
#

If I have a dict with multiple keys and corresponding values, can I somehow replace just one value and leave the rest as is?
I can recreate it using the current values, but I was wondering if there is an easier way

silent seal
#

Did you try {% set variable.key = new_value %} already?

#

I don’t know if that will work, but it’s worth a try.

inner mesa
#

You can't modify data structures like that, but you can use |replace('foo', 'bar') or other filter if you just want to modify a string

violet oasis
#

this does not seem to work
{% if value == true %} mdi:bell

marble jackal
marble jackal
silent barnBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

marble jackal
#

You can refer to the value of the sensor itself:

icon_template: >
  {{ 'mdi:bell' if is_state('switch.cam1_notify',  'on' ) else 'mdi:bell-off' }}

Or

icon_template: >
  {{ iif(is_state('switch.cam1_notify',  'on'), 'mdi:bell', 'mdi:bell-off') }}
inner mesa
#

or you just need to see what the command actually returns and test value against that

sonic nimbus
#

Hello, how can I put condition like numeric_state above, below?

#

for example: conditions: "{{state('sensor.aqua_ariston_current_temperature') < 40}}"

#

{{ states('sensor.aqua_ariston_current_temperature') | int > 76}} I think this is ok

wispy spire
#

I am trying to create a script that adjusts HVAC temperature according to the mode. I had this working in my old build but cannot get it working in the new setup. I get "Message malformed: extra keys not allowed @ data['service']" in HASS even though every YAML validator I try says its fine. Any help would be appreciated! Code: https://www.codepile.net/pile/kXWVa0dv

inner mesa
#

I don't think the problem is in that code

wise sluice
#

i have a template sensor determining when our shower is in use. where do i define the icon for the sensor? current sensor is setup like this in config.yaml
- platform: template sensors: master_bath_shower_occupied: friendly_name: "Master Bath Shower occupied" value_template: "{{ (states('sensor.temperature_master_bath_humidity')|int - states('sensor.average_humidity_master_bath')|int) > states('input_number.master_bath_humidity_threshold')|int }}"

wise sluice
#

i was trying this, but got an error that a dictionary value was expected:
- platform: template sensors: master_bath_shower_occupied: friendly_name: "Master Bath Shower occupied" value_template: "{{ (states('sensor.temperature_master_bath_humidity')|int - states('sensor.average_humidity_master_bath')|int) > states('input_number.master_bath_humidity_threshold')|int }}" icon: > {% if states("sensor.master_bath_shower_occupied") == "false" %} mdi:account-cancel {% else %} mdi:account-check {% endif %}

inner mesa
#

You have to follow the docs

wise sluice
#

i'm trying. but failing haha

#

ah i didn't see that "icon_template" in the docs. thank you

#

was looking at 'icon' under configuration variables

inner mesa
#

That's from the new format. You're using the legacy format there

wise sluice
#

the sensor is in legacy format you mean? or the icon

inner mesa
#

The sensor

wise sluice
#

oh! should i be doing
template:

  • sensor:
    etc etc
inner mesa
#

If you want

wise sluice
#

ok. i got icon_template working but if i want a static icon i don't seem to be able to define it under this sensor. it just keeps rejecting it. or does it only work with templates?

inner mesa
#

It's just a string. Should be fine

wise sluice
#

ah ok great. got it now. thank you!

tawny coral
#

Can anyone see where my indentation issue is or whatever it may be? am i doing the entire action part wrong?
https://bpa.st/5W7A

inner mesa
#

You're misunderstanding how templates work there

#

You can't use templates to surround a set of actions like that. You should look at choose: for that

tawny coral
#

alright, i'll check out choose. thank you

tawny coral
#

Does this look better? https://bpa.st/K3NA I'm assuming this will run the tts.google_translate_say only between 7 and 20. but always send the discord message

mighty ledge
#

that'll do it

tepid onyx
mighty ledge
#

that reference has no impact on your script

#

it's a single script, you aren't running a script in your script

tepid onyx
#

I tried changing service: - service: script.pass_kodi_content_to_other_device to - service: script.turn on but no love

mighty ledge
#

did you even look at the post I made in response? It seems like your'e trying to use your other method, which will not work

#

you can't pass metadata, so you have to use a single script

#

or a intermediary object that holds the information

tepid onyx
#

yep i tried moving around the kodi.call_method

#

no i'm not using an automation at all

mighty ledge
#

that has nothing to do with it, you need to determine the timing before trying to fix it

#

moving things around isn't goign to give you any information

#

look at your script trace, and look at the event times and determine the order

tepid onyx
#

ok let me go back again and try. Sorry I'm just not seeing it. that being said i've learn't a fuckload from your shorthand jinja and yaml. I didn't know you could do shit like this

mighty ledge
#

If you can prove that the event is firing before the wait for trigger (which I think it is), we'll have to make an automation that fires a custom event that passes the file, with a slight delay.

#

otherwise, it doesn't make sense that it's not triggering, because there's nothing different between the triggers in your automation that you were using before

tepid onyx
#

yes that's the conclusion i came to. But if I use an automation then am I back to the original issue of not being able to pass the a variable to it. Bear with me whilst I test

mighty ledge
real terrace
#

I have a vibration sensor on my dryer that doesn’t ALWAYS pick up but is mostly consistent for now. I want to take its state, change it to 1/0 instead of True/False, then do a “max value” over the last 10 or so minutes in a sensor. I need some snippet of code to see how you take this true false and make it an INT. Or a smarter way to find out if this sensor hasn’t detected vibration for X minutes.

inner mesa
#

Sounds like you just to use for: in the trigger

chilly ferry
#

you can use the type count and then either compare to 0 or greater than 0

#

I re-read your comment and if you wanna know when your sensor didn't detect vibration for X minutes, better use type ratio I guess

blazing burrow
#

why do these two templates render differently?

{{ strptime('Sun 2022-03-20 16:29:49 GMT', '%a %Y-%m-%d %H:%M:%S %Z') | relative_time }}
{{ strptime('Mon 2022-03-21 17:36:23 GMT', '%a %Y-%m-%d %H:%M:%S %Z') | relative_time }}

gives

18 hours
2022-03-21 17:36:23-07:00

in the tester

inner mesa
#

relative_time only works for times in the past

#

There's probably an error in your log

blazing burrow
#

well that is a time in the past for me

#

17:36:23-07:00 would be 10:36 which was ~25min ago now

#

and I don't see an error in the log about this either

inner mesa
#

maybe it's not doing timezones right. If I change the hour to 10, it properly returns the delta string, but if I use 11, it goes back to displaying the time

#

10:36 being almost an hour ago in my TZ

mighty ledge
inner mesa
#

pfft

mighty ledge
#

it seems relative_time attempts to add a TZ to unTZ'd datetimes

#

that's the discrepency

#

so it adds whatever your timezone offset is to your non-tz'd datetime and it ends up being in the future

#

the one in the past is wrong too

#

that says '1 day'

#

it's just that 24 hours is a pretty big window of error that happens to work in your favor

blazing burrow
#

I guess I'm not understanding... I use this template in an "uptime" sensor:

sensor:
  - platform: command_line
    name: Living Room Monitor Uptime
    command: "ssh -o StrictHostKeyChecking=accept-new -i /config/.ssh/id_rsa pi@192.168.1.220 'systemctl show monitor.service --property=ActiveEnterTimestamp --value'"
    value_template: >-
      Up {{ strptime(value, '%a %Y-%m-%d %H:%M:%S %Z') | relative_time }}
#

and this works fine for what I need

#

gives me an actual relative time

mighty ledge
#

but it's not a correct relative time

blazing burrow
#

it's... all relative lol

#

if I restart the service, the relative time changes to be accurate

mighty ledge
#

right, but it's going to be off by the offset of UTC to whatever TZ you're in

#

strptime does not attach a timezone to your datetime object

#

so it's 'unaware' of what TZ it's in

#

relative_time tries to fix that by adding your local tz to it

blazing burrow
#

even though the string has GMT in it?

mighty ledge
#

that's how strptime works

#

this is a python nuance

blazing burrow
#

problem is I adapted that sensor for a different service on a different host, and the adapted one doesn't work

#

so one gives me a relative time

#

and the other gives a timestmp

mighty ledge
#

no, both give you a relative time to a wrong time, one gives you a timestamp because it thinks it's in the future and it doesn't compute time in the future

#

put this in your template editor, maybe it'll help you understand that you can't avoid this

#
{% set dt = strptime('Sun 2022-03-20 16:29:49 GMT', '%a %Y-%m-%d %H:%M:%S %Z') %}
{{ dt.tzinfo }}
{% set dt = strptime('Mon 2022-03-21 17:36:23 GMT', '%a %Y-%m-%d %H:%M:%S %Z') %}
{{ dt.tzinfo }}

{{ now().tzinfo }}
blazing burrow
#

ok... so what should I do to work around this?

mighty ledge
#

None, None, Your TZ

blazing burrow
#

?

#

that string with GMT is what that ssh call returns back as value for my sensor

mighty ledge
#

I'm not sure how you can work around this

blazing burrow
mighty ledge
#

did you paste the info into your template editor?

#

you'll k now what I mean if you did

#

unfortunately, you need a way to attach utc tz to a datetime

blazing burrow
#

ah I see

#

sorry, on mobile and didn't paste right atm when you sent it

inner mesa
#

Seems like it should log a warning or error based on invalid input

mighty ledge
#

The input is valid

#

This is a byproduct of how datetimes work. It’s most certainly a bug in our relative time code

#

We just need a new filter that’s like as_local but as_utc

inner mesa
#

relative_time just returns the input when given a future time

mighty ledge
#

Yes, but that’s how it’s designed

inner mesa
#

Seems no different from other such cases with input that it doesn't handle

blazing burrow
#

so the issue is that because of missing timezones, yesterday is in the past while today is in the future?

#

or whatever

#

my first timestamp is in the past but the second one is in the future

mighty ledge
#

It adds local time to your local time, that’s the problem

#

Because you first local time is timezone-less

#

If you don’t know code, it’s pointless to try to understand

#

It’s a gap in the functionality

#

All you need to know, is that both of your relative times are wrong

blazing burrow
#

well I do know code... I just didn't realize this bug existed

#

as is the nature of many bugs

#

I'm a python programmer

#

just don't deal with timestamps much

mighty ledge
#

Then read up on strptime in the datetime library

#

There’s many stack overflow pages that cover strptime and it’s inability to assign a tz to the object

blazing burrow
#

what I don't understand is that even with NO timezone, both of those strings are in the past

#

one works with relative_time (even if it may be innacurate), and one doesn't

mighty ledge
#

Because it’s assigning your tz to the datetime object and it offsets itself by the utc to your tz offset

blazing burrow
mighty ledge
#

Google: datetime aware vs naive

#

You strptime only produces naive

#

Relative time makes it aware to your tz without changing the time that’s set in it

blazing burrow
#

ok

blazing burrow
#

ok well i figured out why some worked and some didn't

#

the ones that worked return Tue 2022-03-15 14:18:59 PDT

#

which, even though the time zone is not factored in by strptime, is still the correct TIME

#

the host that was returning as GMT had the time zone set wrong on the device

#

it now reports Mon 2022-03-21 10:36:23 PDT

#

which is in the past, and works with my template

#

that "full page" screenshot did something weird with my sidebar but that's fine lol

tepid onyx
quiet pond
#

I am getting an error when trying to use this template to convert a sensor from C to F.

    sensors:
      - name: "Basement Temp"
        unit_of_measurement: "°F"
        state:
          value_template: {% set t = states('sensor.dining_temp_temperature') | float %}
            {{((t)*9/5)+32}}```
#

2022-03-21 21:29:48 ERROR (MainThread) [homeassistant.components.template] while scanning for the next token
found character '%' that cannot start any token

#

I changed it to:

    sensors:
      - name: "Basement Temp"
        unit_of_measurement: "°F"
        value_template: "{% set t = states('sensor.dining_temp_temperature') | float %}
            {{((t)*9/5)+32}}"```
and now get:
Invalid config for [template]: expected dictionary for dictionary value @ data['sensors']. Got [OrderedDict([('name', 'Basement Temp'), ('unit_of_measurement', '°F'), ('value_template', "{% set t = states('sensor.dining_temp_temperature') | float %} {{((t)*9/5)+32}}")])]. (See /config/configuration.yaml, line 35).
#
    sensors:
      - name: "Basement Temp"
        unit_of_measurement: "°F"
        state:
          value_template: "{% set t = states('sensor.dining_temp_temperature') | float %}{{((t)*9/5)+32}}"```
also same error as above
#

the template dev tool shows it working fine so I dont understand

tepid onyx
#

change state: to template:

#

value_template:

#

dng phone

#

no that's not right disregard

#

you need to add %} at the end

#

value_template: "{% set t = states('sensor.dining_temp_temperature') | float %}{{((t)*9/5)+32}} %}"

#

sorry

tepid onyx
#

value_template: >
{% set t = states('sensor.dining_temp_temperature') | float %}
{{((t)*9/5)+32}}

#

bah

loud otter
#

HI can someone please explain me how subtraction works in timestamp template? For example in the following case:

{%- if states.vacuum.rockrobo.last_changed -%} {{ (as_timestamp(now()) - as_timestamp(states.vacuum.rockrobo.last_changed)) > 60*10 }} {%- else -%} false {%- endif -%}

what 60*10 means?

marble jackal
#

timestamp are in seconds. It looks like the template checks if if there has been a state change more then 10 minutes ago (60 seconds * 10)

#

You couls also use {{ (now() - states.vacuum.rockrobo.last_changed).seconds > 60*10 }}

#

no need to convert it to timestamps

loud otter
#

ty

astral turtle
#

Hi,
I have a sensor that I want to show in lovelace divided by 1000. Pls suggest what is the right way to do it.
The example below is not correct, but guess it should be something simmilar.

type: entities
entities:

  • {{ (states('sensor.valetudo_robot_1_floor_current_statistics_area') | divide (1000) ) }}

Thanks!

mighty ledge
astral turtle
#

"/" dkesn't work also

marble jackal
#

States are strings, you can't calculate with strings. You need to convert it to a number first

mighty ledge
# astral turtle "/" dkesn't work also
{{ states('sensor.valetudo_robot_1_floor_current_statistics_area') | float / 1000 }}

but that yaml is suspect. It seems like you're trying to do this in lovelace, which is not possible. You have to make a template sensor.

marble jackal
rigid chasm
#

hate to ask but am doing anyway. i am trying to get this to work with my dryer i get this message : Template warning: 'float' got invalid input 'unknown' when rendering template '{% if states("sensor.dryer_power")|float == 0 %} mdi:tumble-dryer-off {% else %} mdi:tumble-dryer {% endif %}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1

thorny snow
#

i have a question, i have a code to monitor my solar panels.

  • platform: rest
    name: Zonnepanelendagelijks
    unit_of_measurement: kWh
    resource: http://10.10.11.69/pvi?rName=YieldStatus
    value_template: "{{ value_json['yieldDaily'] }}"
    device_class: energy
    state_class: total_increasing #measurement
#

When i measure this i get a numer like this 8,6930552 kWh
what do i need to add to my code to only have the last two decimals

#

im new to home assistant so i really don't know

marble jackal
marble jackal
thorny snow
#

good question i would like to keep 8,6

#

and the last 930552 not

marble jackal
#

Sure you want to keep 8.6, as this would round to 8.7

thorny snow
#

yeah or maybe 8,69

#

but i don't need to know the last numbers xD

marble jackal
#

You could use {{ value_json[yieldDaily] | round(1) }}

#

The 1 is the number of decimals you want to round it to. So | round(1) will give 8.7 and | round (2) will return 8.69

thorny snow
#

wow

#

you are such a hero

#

i tried this code and it works!

#

was googling for like an hour

#

don't know if can ask you this to but also read someting else its a state and gives me the state false

#

but i would like to see turned on or off

#

can i put in someting like false = off

marble jackal
#

You can do something like {{ 'on' if a == b else 'off' }} or even {{ iif(a == b, 'on', 'off') }}

thorny snow
#

and where should i put this code

#

something like this?

marble jackal
#

Well depends on what you want to achieve

thorny snow
#

{{ value_json[yieldDaily] | 'on' if a == b else 'off' }}

#

how do you put code in a box like you do in this chat

#

and workmode is like 1 or 0

marble jackal
#

no a == b was just an example for a test which can result in either false or true

silent barnBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).

thorny snow
#

value_template: "{{ value_json['workMode'] | 'on' if false == else 'off' }}"

#

someting like that?

marble jackal
#

No {{ 'on' if value_json['workMode'] else 'off' }}

#

Or {{ iif(value_json['workMode'], 'on', 'off') }}

thorny snow
#

and how does it know what is on or off

#

i want to know how it works

#

sorry for being such a noob

marble jackal
#

I don't know what workMode returns, but according to your earlier posts I assumed it returned true or false

thorny snow
#

yeah thats correct

#
  - platform: rest
    name: Zonnepanelendagelijks
    unit_of_measurement: kWh
    resource: http://10.10.11.69/pvi?rName=YieldStatus
    value_template: "{{ 'on' if value_json['workMode'] else 'off' }}"
    device_class: energy
    state_class: total_increasing #measurement
#

thats how i should put it in right

marble jackal
#

But it it returns 0 or 1 you need {{ 'on' if value_json['workMode'] == 1 else 'off' }} or {{ iif(value_json['workMode'] == 1, 'on', 'off') }}

marble jackal
#

I'm off to bed, but if you have more questions somebody else can maybe answer them later on

thorny snow
#

Thank you so much for your help man!

#

i really do appreciate this!

neat ermine
#

HI, I'm trying to build a template sensor with some IFs encapluslated or with If .. AND if ... AND ... if

#

is this possible ?

silent seal
#

Yes, either you want

{% if thingy and other_thingy and yet_another_thingy %}
{{ output }}
{% end if %}

or…

{% if thingy %}
{{ output }}
{% elseif other_thingy %}
{{ other_output }}

{% end if %}
#

Take your pick, indentation highly recommended.

neat ermine
#

great . wil try .. my objective is to build a Voice_alert_allowed .. having some conditions like after9Am before 10PM on workdays

#

so not to have the conditions repeated in several automations , it would jsut check the template

silent seal
#

That’s a good idea. Make sure to use the Developer Tools to try it out as you go. And check the pins for links to various helpful docs.

neat ermine
#

Hi @silent seal it's gicing a TemplateSyntacError: tag name expected

#

'''{% ((((as_timestamp(strptime((states('input_datetime.end_voice')), "%H:%M:%S"))) - as_timestamp( strptime( now().strftime("%H:%M"), "%H:%M") )) /60) | int > 0) and (((as_timestamp(strptime((states('input_datetime.start_voice')), "%H:%M:%S"))) - as_timestamp( strptime( now().strftime("%H:%M"), "%H:%M") )) /60) | int < 0 %} {{ true }} {% end if %}

silent seal
#

Make sure to check the documentation for the correct format. The examples above are multi line templates. And if you’re outputting a value rather than a variable you won’t need to wrap it in {{ }}

silent barnBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).

neat ermine
silent seal
#

Well, there’s a lot of optimisation that could be done in your template. Let me find a laptop

#

First of all, make sure you are using a multiline template in the .yaml file.

neat ermine
#

i'm trying out in the template deve

silent seal
#
{% if now() > today_at(states('input_datetime.end_voice')) and now() < today_at(states('input_datetime.end_voice'))  %}
    true
{% end if %}
#

That's some guesswork, I'm hoping your xyz_voice helpers are time only.

neat ermine
#

not really - i need to use the is_timestamp

silent seal
#

Why?

neat ermine
#

it's a input number

silent seal
#

But in your template you had input_datetime, those are not numbers

#

I'm comparing datetimes above, there's a very similar example in the docs...

buoyant pine
#

There's no need to force returning True btw. You can just do something like

{{ x > y }}
``` which will return True or False
silent seal
#

Yes, that's a very good point.

neat ermine
#

..don't know what i'm doing wrong

#

error : UndefinedError: 'input_datetime' is undefined

#

'''
{{ now() > today_at(input_datetime.start_voice) and now() < today_at(input_datetime.end_voice) }}
'''

silent seal
#

Well my example is pseudocode, not intended to be perfect. It's intended to be put into developer tools and adjusted.

#

I updated the example to have states('input_datetime.xyz_voice') 😉

#

A backtick is `

neat ermine
#

great

#

now working

#
{{  now() > today_at( states('input_datetime.start_voice')) and now() < today_at( states('input_datetime.end_voice'))  }}
silent seal
#

Much simpler, good work

neat ermine
#

.. can it be like
{{ ( thingy and thingy ) or (thingy and thingy ) }}

#

?

#

I've diferent imput select for weekends

silent seal
#

Yes, it can. But, I wouldn't do different inputs. I'd use automations to update your inputs to match the day

#

Then they can handle holidays, you taking a day off work, etc.

neat ermine
#

good point - i'm already using a workday template for my country holidays

silent seal
#

I do that with my alarm clock. It updates every day

neat ermine
#

but I'm also using a workday offset , as sunday is weekend but kids go to bed as a workday

#

and on fridays they can be up until later

silent seal
#

You can update the end_time at say midday, and the start_time at midnight

neat ermine
#

ok . but if the automations manages the input_time, i would loose the ability to change it on frontend ..

#

were you thinking in any performance tradeoff ?

silent seal
#

Why would you lose the ability to change it?

#

Personally I find one variable that is set easier to debug than a series of conditions which depend on a variety of other conditions.

neat ermine
#

agreed , that's why i'm bulding this voice_alerts_allowed - to not repeat the code

hard topaz
#

i've got a fairly easy 101 question that I haven't had to do in years so I completely forgot, but how do I customize a binary sensor? I've got a shelly with an input switch for my garage door. ON means closed, OFF means open.. how do I change the output to reflect that?

neat ermine
fierce hornet
#

I'm trying to create a sensor that shows all the current people home. I've found something online that works and I want to modify it, unfortunately my template skills are non-existent.
When all the people are home this template outputs 1, 2, 3, 4, 5 right now. I would love that it displays 1, 2, 3, 4 and 5. So the last , is always replaced by an and. Would someone be able to help me with this?

#
{{ person | selectattr('state','eq','on')  | map(attribute='attributes.friendly_name') | list | join(', ') }} ```
silent seal
#
{% set person = expand('input_boolean.1aanwezig', 'input_boolean.2aanwezig', 'input_boolean.3aanwezig', 'input_boolean.4aanwezig', 'input_boolean.5aanwezig') | selectattr('state','eq','on')  | map(attribute='attributes.friendly_name') %}
{% set last_person = person | last %}
{{ person | reject(last_person) | list | join(', ') }} and {{ last_person }}  

That might do it, untested and probably not an efficient approach though

fierce hornet
#

Thanks! But like you expected: TypeError: 'generator' object is not reversible

silent seal
#

Yeah, I thought that might be the case. If you pop back tomorrow you might catch someone better than myself at these things. I've been writing too much liquid (which is the Ruby version of Jinja) so my head is definitely in the wrong space

fierce hornet
#

No problem! Thank you for the effort😁

silent seal
#

(Tomorrow isn't that long away for context, it's 11pm here!)

fierce hornet
#

Already tomorrow here

#

Just 3 minutes past 12

silent seal
#

Well there you go, just need someone more helpful than me to appear and you're all set! 😛

fierce hornet
#

I will, thanks again 🙂

floral shuttle
#

check the demo template in dev tools, and do something like: {% for light in expand('group.all_lights_only') |selectattr('state','eq','on') -%} {%- if loop.first %}The {% elif loop.last %} and the {% else %}, the {% endif -%} {{ light.name | lower }} {%- endfor %}. or with person: {% for person in states.person|selectattr('state','eq','home') %} {%- if loop.first %}{% elif loop.last %} and {% else %}, {% endif -%} {{ person.name }} {%- endfor %} are home. play a bit with the output you'd like, maybe add a Phrase for the are/is, based on count

fallen karma
#

Hi all! Does anyone know why using a template in a service-call is not working when used with browser_mod/auto-entities? https://pastebin.com/RcmHfPmW

#

..well. It probably is a way to make it work, but it needs to be coded differently at least. Anyone know why and how?

fossil venture
#

Glance cards do not support templates.

floral shuttle
#

use config.entity?

floral shuttle
#
   notify.mobile_app_{{ recipient }}```
fallen karma
fallen karma
# floral shuttle use config.entity?

config.entity will still need to be string-manipulated and thus the same issue arises with the use of template...but if it's the glance-card's fault, I will solve it easily...just haven't considered it before @fossil venture meantioned it

fierce hornet
fallen karma
#

it believes the service is '{% set recipient.....'

neat ermine
#

@silent seal maybe you could help on your suggested solution .. I'm not moving forward 😦

 action:
  - service: input_datetime.set_datetime
    target:
      entity_id: input_datetime.start_voice
    data:
      time: "{% if is_state(\"binary_sensor.workday_sensor\" , 'on' %} 09:30:00 {% else %} 09:00:00 {% endif %}"
silent seal
#

Why not use the choose action instead?

neat ermine
#

🙂 .. you are good 🙂 .. will try that

floral shuttle
# fallen karma it believes the service is '{% set recipient.....'

I am sorry, I only looked at the template, not the card config. you have to use the options the card provides. None of the stock HA cards will allow for that templating. So, you need to do as Tom suggested, use a custom card that does provide or allow templating in services.

#

maybe this helps: filter: include: - group: group.github_repos_in_use options: tap_action: action: more-info hold_action: | { 'action': 'url', "url_path": "{{state_attr(config.entity,'url')}}" } which is filled by the auto-entities card

fallen karma
# floral shuttle I am sorry, I only looked at the template, not the card config. you have to use ...

well...I use custom:auto-entities...according to examples given by @charred dagger and others I found online, it should allow customization. Also regarding the templating, just adding a simple button-card to lovelace with the template I pasted, will work fine...as stated, the template works just fine in developer, in script and automations...just not in this nested card-setup I have going on here

#

that somehow makes me believe that using broweser_mod popup and nested cards has something to do with it...but I am too inexperienced to know and my three days of searching for solutions has gotten me nowhere 😦

floral shuttle
#

as said, you should take it to #frontend-archived because all of the issues you mention are FE related. the template is not very challenging 😉 your card config is. Start with the smallest bit, and work your way up to the bigger picture

fallen karma
neat ermine
fierce hornet
#
  {%- if loop.first %}{% elif loop.last %} and {% else %}, {% endif -%}
  {{ person.name }}
{%- endfor %}```
#

(1 to 5 are actually peoples names but removed them for discord)

floral shuttle
#

using this loop, wont allow you to 'sort'. But I guess you could enter the names in a sorted order in the expand() listing 😉

fierce hornet
#

Did that but it doesn't have any effect 😦

#

Using the other method I'm able to use sort(reverse = true) for reverse alphabetical order. Isn't there something possible like that with this?

#

Still, a custom order would be the best but no idea how to tacle that

silent seal
#

Are the input_booleans in the order you want the people in?

fierce hornet
#

There isn't really an order right now because I replaced all the real names with 1 to 5

#

So yes & no

silent seal
#

But if you put them in the "right" order in your expand, does it work?

fierce hornet
#

Nope

silent seal
#

Well, darn it. Then you'll likely have to build the array manually.

#

And just checking, this doesn't help?

{% for person in expand('input_boolean.1aanwezig', 'input_boolean.2aanwezig', 'input_boolean.3aanwezig', 'input_boolean.4aanwezig', 'input_boolean.5aanwezig') | sort(reverse=true, attribute=="name") | selectattr('state','eq','on') %}
  {%- if loop.first %}{% elif loop.last %} and {% else %}, {% endif -%}
  {{ person.name }}
{%- endfor %}
fierce hornet
#

TemplateSyntaxError: invalid syntax for function call expression

#

Doesn't seem like it. Tried something similar but got errors also

silent seal
#

Oh, interesting. You might have to do a

{% set people = expand('input_boolean.1aanwezig', 'input_boolean.2aanwezig', 'input_boolean.3aanwezig', 'input_boolean.4aanwezig', 'input_boolean.5aanwezig') | sort(reverse=true, attribute=="name") | selectattr('state','eq','on') %}
{% for person in people %}
...
#

I had a == in there 🤦‍♀️

#
{% for person in expand('input_boolean.1aanwezig', 'input_boolean.2aanwezig', 'input_boolean.3aanwezig', 'input_boolean.4aanwezig', 'input_boolean.5aanwezig')  | sort(reverse=true, attribute="name") | selectattr('state','eq','on') %}
{%- if loop.first %}{% elif loop.last %} and {% else %}, {% endif -%}
  {{ person.name }}
{%- endfor %}
fierce hornet
#

I see, woops

#

It seems to be working!

silent seal
#

Yay!

fierce hornet
#

Thanks a lot 🙂

silent seal
#

No problem, sorry for all the failed attempts 🙂

fierce hornet
#

Not a problem! I have something that works now

#

I will probably try a custom order in the future, but for now it's bedtime here, 2am

#

Thanks again 😁

silent seal
#

1am for me, I should also sleep! 😂

#

Otherwise my bedroom will get cold, because past me programmed HA to assume I'm in bed by 1:30am as a sort of punishment if I'm not 🤪

fierce hornet
#

That would be quite helpful for me too. always late...

#

Goodnight!

floral shuttle
#

morning... 😉 jut letting you know that the '{% for person in expand('group.all_inside_lights')' format does already order alphabetically, and adding 'sort(reverse=true, attribute="name")' does its job just fine. If it doesnt do that for listed items, you could throw them in a group and expand the group.

#

another way for the listing, without the loop: {% set lights_on = expand('group.all_inside_lights') |selectattr('state','eq','on')|map(attribute='name')|list %} {% if lights_on|length == 0 %} No lights on. Sleep well.. {% elif lights_on|length == 1 %} The {{lights_on[0]}} light is on. {% elif lights_on|length == 2 %} The {{lights_on[0]}} and {{lights_on[1]}} lights are on. {% else %} The {{lights_on[:-1]|join(', ')}}, and {{lights_on[-1]}} lights are on. {% endif %}

silent vector
#

How do I make sure this template is evaluating all 3 entities? The developer tool says it's only listening to weather.home

"{{ (state_attr('weather.home','temperature')) | float(0) < 50 or (state_attr('weather.pirateweather','temperature')) | float(0) < 50 or (state_attr('weather.west_chester','temperature')) | float(0) < 50 }}"  
marble jackal
#

Is the first part (with weather.home) already true? It doesn't evaluate the rest of the template then, so it won't know the entities involved. If the first part is false it will move to the next part

silent vector
#

Yes it is

#

I figured that but I wanted to be sure.

marble jackal
#

It is the other way around when you use and. It will stop when a part is false and continue to the next part when it is true

silent vector
bitter atlas
#

I have an json rest array where there are multiple keys labeled the same and I am trying to pull all of the same select number of same named keys into the attribute of a rest sensor. I hope that doesn't sound confusing, anyone got any idea how? it would be like title[0], name[0], title[1], name[1], title[2], name[2] and i'm trying to keep them together in order

#

derp, think I skipped right over one of the examples in the doc that shows how it's done

stuck remnant
#
description: ''
trigger:
  - platform: template
    value_template: >-
      {{ (  now() - states('sensor.thegoat420_lastactive') |
      as_datetime).total_seconds() >= 10 }}
condition: []
action:
  - service: switch.toggle
#

what did I do wrong

#

sensor.thegoat420_lastactive 2022-03-23T14:16:12+00:00
this is how it looks like in DT, and some nice fellow wrote this template for me so that it would trigger after 10seconds of inactivity
for reference, the sensor is a last active sensor for windows detecting when a user made an input.

#

im basically trying to trigger a fan after pc goes 10sec idle

mighty ledge
#

it will trigger once per minute at most.

#

so it will vary between 10 seconds and 1 minute, depending on when the state changed

stuck remnant
#

why, and also how do you know?

mighty ledge
#

because that template will only update when sensor.thegoat420_lastactive updates, and on each minute because the template is using now()

stuck remnant
#

ooh

#

that makes sense and also goes with what the experience was, thank you

mighty ledge
#

np

bitter atlas
#

ok i am confused as heck now, I thought I figured it out but the rest sensor only pulls the first matching attributes I list. I have a json that comes in like this https://www.codepile.net/pile/GBKOmaBo and I am only trying to fetch 3 items title, releasDate and network but I want all of them and to list them as attributes in order in a sensor. cannot for the life of figure out how to even start if the sensor only pulls one set

mighty ledge
#

you're using a rest sensor?

bitter atlas
#

yea

bitter stag
mighty ledge
#

you're going to want to store the entire result in an attribute

bitter atlas
#

I have resource defines and the attributes, for the value template i just put ok cause i don't want it dumped in the state field

#

how do you do that?

#

cause if i list anything in the attributes it seems to only pull the first matching set

mighty ledge
#

well, actually, you'll have to create a rest sensor for each item because the first main item is a list

bitter atlas
#

oh i was so afraid you were gonan say that

#

where is the json_attributes_template when you need it!

#

that dosen't even seem logical to even try and do, talking about a dynamic list that could be very short or very long

mighty ledge
#

Yep, probably should start looking at custom integrations that handle this

#

can you change the device that's outputting it?

bitter atlas
#

no

mighty ledge
#

{'items': ... }

#

is all you'd need

#

python script then

bitter atlas
#

that codepaste i linked above is all i have to work with

bitter stag
#

10x

floral shuttle
#

this makes a list of entity_ids: {% set hue_group = 'light.alarm' %} {% set ns = namespace(lights=[]) %} {%- for s in states.light if s.attributes.friendly_name in state_attr(hue_group,'lights') %} {% set ns.lights = ns.lights + [s.entity_id] %} {%- endfor %} {{ns.lights}} and I was trying to do that without namespace, but with a |selectattr('friendly_name','search' ,names) where names would be the 'state_attr(hue_group,'lights')|list'

#

that yields an empty list though..

#

what am I missing?

inner mesa
#

Is 'friendly_name' the name of a light?

#

That's what you're testing

floral shuttle
#

yes, because the hue integration light group has a names list as attribute, and not entity_id.

inner mesa
#

Not a list of entity_ids?

charred dagger
#

The first one works, the second doesn't?

#

And I assume {% set names = state_attr(hue_group, 'lights') %}?

#

Did you try selectattr('friendly_name', 'in', names)?

floral shuttle
#

yes, yes, and let me try

floral shuttle
#
{% set hue_group = 'light.alarm' %}
{% set names = state_attr(hue_group,'lights') %}
{{states.light|selectattr('friendly_name','in',names )
|map(attribute='entity_id')|list}}```  is []
#

if I try 'search', is says TypeError: unhashable type: 'set'

#

{{names}} returns {'Bedside table', 'Dining corner', 'World map', 'Silver cabinet', 'Kist', 'Flash alert', 'Corridor cabinet', 'Frontdoor', 'Kayon'} and thats why I first tested it with {% set names = state_attr(hue_group,'lights')|list %} which makes that a list

floral shuttle
# inner mesa Not a list of entity_ids?

no thats the one thing the Hue api does not return, and the Hue integration brings the api into HA, 1 on 1, no manipulations allowed..... so we need to do that with templates in HA.

#

duh, I was focussing on the wrong error....: {% set hue_group = 'light.alarm' %} {% set names = state_attr(hue_group,'lights')|join('|') %} {{states.light|selectattr('name','match',names) |map(attribute='entity_id')|list}} does it. I need 'name' not 'friendly_name'

#

isnt that odd, needing 2 different attributes in the 2 templates for the same selection?

#

btw Thomas, making a list and using 'in' works also: {% set hue_group = 'light.alarm' %} {% set names = state_attr(hue_group,'lights')|list %} {{states.light|selectattr('name','in',names) |map(attribute='entity_id')|list}}

#

reason for all of this was Id like to create scene on the fly for that light group, without listing all the snapshop_entities verbosely. Seems to be allowed: - service: scene.create data: scene_id: before_flash_alert <<: &flash_entities snapshot_entities: > {% set hue_group = 'light.alarm' %} {% set names = state_attr(hue_group,'lights')|join('|') %} {{states.light|selectattr('name','match',names) |map(attribute='entity_id')|list}}

visual matrix
#

anyone have an idea on how to get the number of days of the current ´bimonthly period’ ?

#

I am able to get the current month but bimonthly makes it a little more difficult

inner mesa
marble jackal
visual matrix
#

It normally start January so January and February, etc

#

I thought about finding the bimonthly periods (1-6 periods) but after that?

#

And my bimonthly bill start somehow the 8 of the first month and finishes the 7 of the second month

marble jackal
#

Okay, now I know it is about a bill that explains it

marble jackal
visual matrix
#

Yeah and bill is generated the 8

#

So it starts every 8th day

#

I would use that as an offset

marble jackal
#

But that doesn't make a difference for the number of days though

visual matrix
#

Hold on I’m at work and here I’ll explain in a min why it’s needed

marble jackal
#

You needed the number of days in the bimonthly period right, if it starts on the 1st of the month or on the 8th that will be exactly the same

visual matrix
#

Periods are bimonthly but my provider count the number of days in that period for the offpeak rate, ex: the first 40 kwh are off peak but the way they do it is they count ex: 62 days x 40kwh, you get 2542 kWh at off peak then the remaining amount is at a peak rate

#

Does it make sense? I wrote that super quick

marble jackal
#

Yes, but again, the start date in the month is not relevant, unless is higher than 28 maybe

#

But I know a way, but I'm on mobile now, so if nobody else answers within an hour or so, I will provide something

visual matrix
#

I guess they count the days between the 8 day of the first and the 7th of the second month

#

Thanks so much, any help is appreciated

#

I’m just thinking of a logic way of doing it

frank gale
#
{% for i in range(0,7) %}
{% set t = now() + timedelta(days=i)  %} 
{{ t }} 
{% endfor %}

This template returns for me:

#
2022-03-23 19:16:00.001771+01:00 
2022-03-24 19:16:00.001934+01:00 
2022-03-25 19:16:00.002068+01:00 
2022-03-26 19:16:00.002167+01:00 
2022-03-27 19:16:00.002260+02:00 
2022-03-28 19:16:00.002352+02:00 
2022-03-29 19:16:00.002442+02:00
#

Why is the time zone until Saturday +01:00 and from Sunday goes to +02:00 ?

#

ok I didn't know that this sunday will be summer time 😛

mighty ledge
marble jackal
# visual matrix I’m just thinking of a logic way of doing it

This should do it:

{% set m = now().month if now().day >= 8 else now().month - 1 %}
{% set m = 12 if m == 0  else m %}
{% set previous = (now().replace(month = m, day=1) - timedelta(days=1)).day %}
{% set current = 31 if m == 12 else (now().replace(month = m+1, day=1) - timedelta(days=1)).day %}
{% set next = 31 if m in [11, 12] else (now().replace(month = m+2, day=1) - timedelta(days=1)).day %}
{{ current + next if m is odd else previous + current }}
visual matrix
#

Logging into my comptuter to check this thanks 🙏

#

Computer*

marble jackal
#

why not?

mighty ledge
#

you need to add a year when it crosses 12

#

unless assuming its 12, 34, 56, 78, etc

marble jackal
#

But it doesn't, that's why I check if the month is 12.

#

(and 11 for the next month)

#

Small edit, as the check is not needed for previous

#

it will not use m+1 if m == 12 and it will also not use m+1 if m in [ 11, 12 ]

mighty ledge
#

well, I see why I don't think it will work, you're not doing it the way to actually get the correct number of days in the month

#

you're assuming they are all 31

marble jackal
#

no, I assume it is 31 when it is december

mighty ledge
#

ah, just a wierd way of doing it

marble jackal
#

And I also assume the next month will have 31 days when it is November of December

#

Well, the only month you don't know for sure is February 🙂

visual matrix
#

Smart, I made a sensor, ill check if this works rn, thanks for the time taken

marble jackal
#

But this is the best I can come up with, if you have a better approach I'm happy to be learned a lesson Petro 🙂

visual matrix
#

I love how coding is about being creative

#

Giving me 61 days

#

This should count from february 8 to april 7

#

And it should be 59 if I count right?

marble jackal
#

You said before it started in January, and then 2 months each time

visual matrix
#

Hold on

marble jackal
#

So it is March and April now

visual matrix
#

Oh, would it work the same if it didnt start in november? How do they calculate this

#

last bill was:

marble jackal
#

otherwise you only need to replace odd with even in the last line

visual matrix
#

December 8 to Feb 7

#

So it would start december?

marble jackal
#

ah, then do that

#

replace odd with even

visual matrix
#

doing it rn thanks

#

honestly, you are saving me a few hours, days of web scraping for this haha, I owe you a beer

marble jackal
#

no problem!

visual matrix
#

works perfect, I get 59 as counted

analog crag
#

Hey guys! I have a template sensor running which resets itself after a reboot and then go back to the correct number. Issue is this is screwing up the values of my utility sensors. In this case its a gas meter and my gas usage is going from e.g. 0.3 kWh per hour to 2300 kWh Any idea how to keep the numbers after reboot?

marble jackal
#

add an availabilty_template to check if the source sensor is available to avoid this

silent barnBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

marble jackal
#

states('sensor.gasverbrauch') | float this part will default to 0 just after reboot

#
  - platform: template
    sensors:
      gasverbrauch_kwh:
        friendly_name: "Gasverbrauch"
        unit_of_measurement: 'kWh'
        device_class: "energy"
        value_template: "{{ (2302 + states('sensor.gasverbrauch') | float *0.01 * 11.323 * 0.9444) | float | round (2) }}"
        attribute_templates:
           state_class: total_increasing`
        availability_template: "{{ states('sensor.gasverbrauch') | is_number }}"
marble jackal
#

this will do, btw, no need to cast a float to a float again

#

and if you would not have used the legacy template sensor format, you could have added the state_class without using attributes_template

analog crag
marble jackal
#

float stand for floating point number, which is basically a number with decimals

#

int stands for integer, which is a number without decimals

#

but the last line in my yaml code will make sure your template sensor is unavailable when the source sensor doesn't have a number as it's state

#

So basically when it's unavailable or not working for another reason

analog crag
analog crag
marble jackal
#

no, but states are always strings (so text) and you can't calculate with text. So you first have to convert it to a number, that is what | float does

marble jackal
#

and the result of your calculation is already a number, so no need to convert it to a number again

analog crag
#

Basically what you wrote before means i can remove the second | float?

marble jackal
#

yes, correct

analog crag
#

Ok cool! Thanks a lot! Also: It worked 🙂 Thank you again! I´m really happy now!

mighty ledge
#

something like

#
{% set n = today_at().date() %}
{% set t = n.replace(day=8) %}
{% set ns = namespace(dates = [ t.replace(year=n.year - 1, month=12), t.replace(year=n.year + 1, month=2) ]) %}
{% for m in range(2, 14, 2) %}
  {% set ns.dates = ns.dates + [ t.replace(month=m) ] %}
{% endfor %}
{% set end = ns.dates | sort | select('>=', n) | first %}
{% set start = ns.dates | sort | select('<=', n) | reverse | first %}
#

then you can get the cycle, days left, or days in

#
cylce:  {{ (end - start).days }}
days in: {{ (n - start).days }}
days left: {{ (end - n).days }}
marble jackal
#

Let me try to figure out what you are doing here 🙂

#

Ah, I get it! Nice!

mighty ledge
#

there's a ton of different ways to do this

#

it would be way easier/nicer if we could create dates and if jinja allowed single line for loops like python

marble jackal
#

Still a lot to learn.. I still get confused by range. The 14 part in this case. It's probably because count starts at 0

#

And I tested it, 13 would also have worked 🙂

mighty ledge
#

range(start, end, increment)

marble jackal
#

Yes, but range(0,3) | list results in [0, 1, 2] and my brain expects [0, 1, 2, 3]

marble jackal
silent seal
#

Ah yes, start, number to include, rather than start and end

marble jackal
#

range(6,7) | list results in [ 6 ], and range(6,6) | list in []. So start is as I would expect, while end is not

visual matrix
#

This is nice!

manic onyx
#

hi everyone. I want to make a template to close my garage door if left open past midnight. It work, but my trigger is time 00:00 and condition that garage door is open.
I worry that if for whatever reason HA is not available at midnight, when it comes back online (say 00:05), it will not trigger the automation.
What is best way to setup an automation so it triggers any time between say midnight and 5am?

inner mesa
#

That just sounds like an automation, not a template

#

Anyway, add a trigger for homeassistant.start and a condition for the time being after midnight

manic onyx
#

thanks @inner mesa . Was asking in a template as there is no trigger for between 2 times, like there is for condition. But will re-ask in automation, as there may be a time when we come home after midnight and forget to close the garage.

glad onyx
#

I'm a little confused here... I need a template so that a light turns off if a door was closed, but only if it's been open for at least 1 min. How do I do this? The template is the condition for the automation I have, which is complete, except for I need a template.

inner mesa
tawny coral
#

https://bpa.st/EE3Q My automation seems to have stopped working when i removed the "choice" part. The error i'm getting is "Template variable warning: 'dict object' has no attribute 'state' when rendering '{{ value_json.state }}'". I'm unable to run it through dev tools -> templates since it has a trigger. I can't really find anything to do with vlue_json.state, any ideas?

fossil venture
#

Are you sure it is that automation that is causing the error?

fallen karma
#

Hi all. Stilo struggling with getting a template to work for a service call from a nested card, but think I am getting closer. In a standard unnested card, I can use service: >{% varmanupulation %}{{ result }}, but in nested card this template is not evaluated. I have however gotten progress using the [[[ var myVar = blah.bleh; return notify.${myVar}; ]]]

Using the first example with curly brackets, I can split my variable string (device_tracker.phone) with string.split(".")[1] to return only (phone)...how do I do this when using [[[ string.MANIPULATE ]]]

Might be a stupid question this, but would really appreciate a nudge here..curly brackets version is YAML code...and [[[ is javascript?

olive escarp
#

I have error and warning message in the logs for my template sensor. I dont know how I can solve this.

silent barnBOT
olive escarp
#

If someone can help it is much appreciated

tawny coral
#

Okay nevermind i guess. It's not that one. It was due to my zigbee dongle disconnecting....

fossil venture
marble jackal
#

And what does this sensor display? I have a similar sensor for my washing machien, and it displays 0:29:00. You can not convert that to a timestamp

#

If the same applies to your sensor, you can use:

{% set h, m, s = (states('sensor.wasmachine_remain_time')).split(':') %}
{% set min = m ~ ' minuut' if m == '1' else m ~ ' minuten'  %}
{{ (h ~ ' uur en ' if h != '0') ~ min }}
olive escarp
#

Template warning: 'timestamp_custom' got invalid input 'None' when rendering template '{{ as_timestamp(states('sensor.oneplus_arno_next_alarm')) | timestamp_custom('%-H:%M' ,false) }}' but no default was specified. Currently 'timestamp_custom' will return 'None', however this template will fail to render in Home Assistant core 2022.1

marble jackal
#

That is not related to the code you posted above

olive escarp
#

the time stamp is:

#

you are right

mighty ledge
olive escarp
#

sorry wrong warning/error

mighty ledge
#

the other templates do not have a default specified for as_timestamp

#

see the 4th pin in the pins list

olive escarp
#

Template warning: 'as_timestamp' got invalid input 'unavailable' when rendering template '{{ (as_timestamp(states('sensor.wasmachine_remaining_program_time')) - as_timestamp(utcnow())) | timestamp_custom('%-H:%M' ,false) }}' but no default was specified. Currently 'as_timestamp' will return 'None', however this template will fail to render in Home Assistant core 2022.1

mighty ledge
#

Yep, see the 4th pin in the pins list

marble jackal
#

But he is using an availability template which should avoid that I guess..
availability: "{{ states('sensor.wasmachine_remaining_program_time') != 'unavailable' }}"

mighty ledge
#

Yah, I think that PR is in now

olive escarp
#

Ok it is working but i was looking to solve the error/warnings in my log

#

If the PR solves it that would be great

#

I did read thru the 4th pin already but it is hard for me to convert the example to my use case

mighty ledge
#

how so? Did you identify the function that's being used that needs the default? If yes, follow the number of comma's and add the default within the ()

#

if you don't see a comma, that means you only are supplying 1 argument

#

i.e. you have to add the comma and place the default after the 1st argument

#

that post is meant to teach you how to add it, not spoon feed you the answer with a copy/paste

#

function(argument) -> function(argument, default=...)

#

@olive escarp if you're still struggling, post your attempts and I'll help you fix it.

marble jackal
mighty ledge
#

🤷‍♂️

#

I don't rememeber

marble jackal
#

You mean that the state templates are still rendered when the availability template returns false right?

mighty ledge
#

There was a PR awhile ago to make it not render

#

I have no idea if it passed and was put in

olive escarp
#

The availability is working correct

#

i made a mistake

#

by heving the old way without the availability and the new way with availabilty

#

old way being sensor and then platform:template

mighty ledge
#

they both use the same code, the new way just has more configuration avialable

#

so they will be the same

olive escarp
#

sorry to have bothered you guys and thanks for the help! although i still not solve it by using the pinned message

mighty ledge
vocal agate
#

Hello

#

I am trying to fetch informations about the actual connected bluetooth device in companion

#

i try to create a template but i always get a error.

#

sensor:

  • platform: template
    sensors:
    welches_auto:
    friendly_name: "welches Auto"
    value.template: "{{ state_attr('sensor.op7_bluetooth_connection','connected_paired_devices') % }}"
#

any help is welcome

mighty ledge
#

You have a % inside your template

vocal agate
#

i removed it

#

and still get : Invalid config for [sensor.template]: [value.template] is an invalid option for [sensor.template]. Check: sensor.template->sensors->welches_auto->value.template. (See ?, line ?).

mighty ledge
#

your yaml is incorrectly spaced

marble jackal
#

The . shoud be _

#

value_template

mighty ledge
#

friendly_name and welches_auto should not be in line

#

same with value.template which should be value_template

vocal agate
#

thanks mater

#

mate

#

after changing value.template -> value_template it seems to work

#

works like a charm 🙂

marble jackal
#

Did you also correct the indentation?

#

Ah, now you did 🙂

bitter stag
#

Hey guys , i have a sensors (from socket) that counts total energy for a device
in history i can see increasing value everyday
what would be the syntax for braking it into monthly usage ?

marble jackal
#

use a utility_sensor

bitter stag
#

utility_meter:

electricity_daily_khw:
source: sensor.electricity_energy_kwh
cycle: daily

electricity_monthly_khw:
source: sensor.electricity_energy_kwh
cycle: monthly

#

like this ?

marble jackal
#

Looks fine I guess, please format as code next time. And for further questions on this #integrations-archived is the proper channel

silent barnBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).

bitter stag
toxic dome
#

@bronze zinc figured I'd bring the conversation over here since making trigger template sensors is an HA thing rather then a node red one. What you want is essentially this example: https://www.home-assistant.io/integrations/template/#turning-an-event-into-a-binary-sensor. Essentially what happens in this example is when my_event is fired this sensor becomes on and then turns off 5 minutes later. Unless my_event is fired again in which case the 5 min clock restarts.

So to take it your example, by listening to a sensor created like this instead of to the unifi camera events directly you get one state change to on when someone enters the area and then one to off when no one has been detected for 5 minutes and nothing in between. Exactly what you want I believe.

bronze zinc
#

ty, I will read through it all when I get home

swift lance
#

Hello everyone, i try to get a api from a local device integrated but i cant get it to work.

The call looks like that http://192.168.0.102/INCLUDE/api.cgi?jsonnode=1&jsonparam=I

When i enter the url in the webbrowser or reqbin.com and authenticate with auth-http i get a valid answer that looks like this:

silent barnBOT
swift lance
#

https://pastebin.com/cudUGu5K sorry Mr bot

with {{ value_json.Data.Inputs.0.Value.Value}} in the template dev-tool i get the correct number, e.g 14.1, but i dont know how to use this in a template.
Any help would be appreciated, thanks

#

(foramtting may be wrong bc i copied them out)

marble jackal
#

Put this in your rest sensor {{ value_json.Data.Inputs.0.Value.Value }} and you should get 14.1 there. Don't know what you want to do with the template sensor after that

swift lance
#

so i want to have multiple sensors from one api call (max 1 per 60s) and in the restfulsensor doc i read that we use json_attributes and template to create multiple attributes from one result.

I added
value_template: "OK"
json_attributes:
- 1
- 2
- 3
- 4
- ... till 14

#

i am confused if my json_attributes are correct from 1-14 because the api returns Number : 1 instead of Number1

#

and if correct how to use this in the template sensor value_template

marble jackal
#

You can't do that, you can only use dictionary keys as attributes in a rest sensor
So use this:

value_template: "OK"
json_attributes_path: "$.Data"
json_attributes:
  - Inputs
#

Then you do need a template sensor to get the right data out of your rest sensor

#
attributes:
  value_1: "{{ state_attr('sensor.your_rest_sensor', 'Inputs') | selectattr('Number', 'eq', 1) | map(attribute='Value.Value') | join }} "
  value_2: "{{ state_attr('sensor.your_rest_sensor', 'Inputs') | selectattr('Number', 'eq', 2) | map(attribute='Value.Value') | join }} "
swift lance
#

so the Inputs work and i get a attribute list with sensor.cmi
Now to get one temperature i use this template sensor

template:

  • sensor:
    • name: Temperatur Kollektor West
      unit_of_measurement: '°C'
      attributes:
      value_1: "{{ state_attr('sensor.cmi', 'Inputs') | selectattr('Number', 'eq', 1) | map(attribute='Value.Value') | join }} "

But this spits out an error

Invalid config for [template]: required key not provided @ data['sensor'][0]['state']. Got None. (See /config/configuration.yaml, line 201).

silent barnBOT
swift lance
#

okay, so i used

sensor:

  • platform: template

instead of

template:

  • sensor:

Had to change attributes: to value_template: because it said i cant use attributes with a template sensor.
Tahnk you very much @marble jackal, without your help i couldnt have done it

#

this is my sensor now:

sensor:
 - platform: template
     sensors:
       temp_kollektor_west:
         unique_id: sensor.temp_kollektor_west
         device_class: temperature
         unit_of_measurement: '°C'
         value_template: "{{ state_attr('sensor.cmi', 'Inputs') | selectattr('Number', 'eq', 1) | map(attribute='Value.Value') | join }} "
marble jackal
visual matrix
#

hi kind friends, should this be working?

#

trigger: platform: template value_template: "{{(states.sensor.cycle_total_kwh.state | float) > (states.cycle_offpeak_kwh.state | float)}}"

#

Somehow I can not get it to trgger even if sensor.cycle_total_kwh is greater, less, than the other sensor

toxic dome
# visual matrix ` trigger: platform: template value_template: "{{(states.sensor.cycle_to...

So bear in mind how template type triggers work:

Template triggers work by evaluating a template when any of the recognized entities change state. The trigger will fire if the state change caused the template to render ‘true’ (a non-zero number or any of the strings true, yes, on, enable) when it was previously ‘false’ (anything else).
So the way it should be working is this:

  1. Should never trigger if cycle_total_kwh <= cycle_offpeak_kwh
  2. Should only trigger if a state change makes cycle_total_kwh > cycle_offpeak_kwh true but before that state change this was true cycle_total_kwh <= cycle_offpeak_kwh
#

It's not as simple as saying it will trigger if one sensor is greater then the other, it should specifically be triggering on the transition only. When the one was not greater then the other and then becomes greater then the other.

visual matrix
#

Oh so to be triggered it has to be false before it can check if the new state is true?

toxic dome
#

Yes exactly

visual matrix
#

thank you! so manually triggering the automation wont change anything

toxic dome
#

Oh, definitely not. Manually triggering an automation ignores the trigger entirely, it just executes the steps as a script

mighty ledge
#

ask yourself: is cycle_offpeak_kwh a valid entity_id?

visual matrix
#

sensor.cycle_offpeak_kwh is valid

mighty ledge
#

is that cycle_offpeak_kwh?

visual matrix
#

yes oh

mighty ledge
#

pretty sure sensor.cycle_offpeak_kwh is not cycle_offpeak_kwh

#

this is one of the many reasons to stick to the states method over using the states object.

visual matrix
#

Both are the same, I just did something wrong there

#

I made a custom sensor doing a calculation

mighty ledge
#

they are not the same

visual matrix
#

which is sensor.cycle_offpeak_kwh

mighty ledge
#

are you completely glancing over the missing word sensor.?

visual matrix
#

so should it be states.sensor.cycle_offp

#

Just noticed that I misstyped it

#

damn

#

I did so many do and undo that I probably deleted it

mighty ledge
#

that's why you should use the template editor 😉

visual matrix
#

Ill give it a try

#

thanks haha

inner mesa
#

It even does autocomplete now

#

As long as you start with the right thing, which, well, wouldn't have helped you here other than to point out that you were doing the wrong thing

visual matrix
#

useful

marble jackal
#

This will definitely throw errors in your log just after reboot, at least with states('sensor.whatever') you only get warnings (until 2022.1 finally gets shipped 😉 )
If you want to avoid that totally, and be sure the right values are used, use something like:

{% set a, b = states('sensor.whale'), states('sensor.petunia') %}
{{ a | is_number and b | is_number and a | float > b | float }}
silent barnBOT
green adder
#

I am struggling to understand why my unique_id values aren't working for a template I am writing. I am trying to make a little binary sensor to combine two other values (The logic here isn't important I can figure that out). I have this code under template in my config:

  - binary_sensor:
      - name: "Test - Vhia and Nick combined presence"
        unique_id: "person_groups_presence_primary"
        state: >
          ... some logic here ...

However the entity in the UI is always called: binary_sensor.vhia_and_nick_combined_presence which looks like a slugified version of the old name (which was Vhia and Nick combined presence). I have tried deleting the entity in the UI but it just appears again immediately with the old name. What am I doing wrong here?

#

Ideally I would also like to have the block have a unique_id prefix so I don't have to make sure they are all the same for each item in the list but I was struggling to get that to work too

floral shuttle
#

anyone seen this error before?2022-03-25 17:39:32 ERROR (MainThread) [homeassistant.components.template.template_entity] Error validating template result 'unknown' from template 'Template("{{states('sensor.alarm_panel_icon')}}")' for attribute '_attr_icon' in entity switch.security_system validation message 'contains non-whitespace: unknown'

#

my switch:```

  • platform: template
    switches:
    security_system:
    unique_id: switch_security_system
    friendly_name: Security system
    value_template: >
    {{states('alarm_control_panel.ha_rpi4_alarm') in
    ['armed_away','armed_home','armed_night']}}
    icon_template: >
    {{states('sensor.alarm_panel_icon')}}```
#

and the icon_template's entity sensor.alarm_panel_icon: ```
- unique_id: alarm_panel_icon
state: >
{% set panel = states('alarm_control_panel.ha_rpi4_alarm') %}
{% set mapper = {'disarmed':'mdi:shield-check',
'armed_away':'mdi:shield-lock',
'armed_custom_bypass':'mdi:security',
'armed_home':'mdi:shield-home',
'armed_night':'mdi:shield-home',
'arming':'mdi:shield-outline',
'triggered':'mdi:bell-alert'} %}
{{mapper[panel] if panel and panel in mapper else 'mdi:shield-check'}}

#

its really odd, because the icon it showing just fine, maybe a race condition of sorts?

green adder
#

Maybe you could try moving the check up into where you use the icon instead of or as well as inside the alarm_panel_icon

mighty ledge
#

and if name is missing the entity_id will be domain.template_<unique_id>

green adder
mighty ledge
#

You can add friendly_name to attributes

#

have it slugify the name, and then use the real friendly_name in the attributes

#

or just adjust it afterwards in the UI

#

or customize it

#

in yaml

green adder
floral shuttle
#

will try that, guard the icon template in the template switch.

mighty ledge
mighty ledge
#

also, mdi: is common on all those, just move that out

floral shuttle
#

yeah thats easy...

green adder
mighty ledge
#

that might actually solve the error too

floral shuttle
#

let me guard the states('sensor.alarm_panel_icon')

#

ok I'll use {% set panel = states('alarm_control_panel.ha_rpi4_alarm') %} {% set mapper = {'disarmed':'shield-check', 'armed_away':'shield-lock', 'armed_custom_bypass':'security', 'armed_home':'shield-home', 'armed_night':'shield-home', 'arming':'shield-outline', 'triggered':'bell-alert'} %} mdi:{{mapper.get(panel, 'shield-check')}} first and see what restart gives using the get() in the switch

mighty ledge
mighty ledge
#

put the mdi: in the icon_template

#

then it would become mdi:unknown, which probably won't fail but won't produce an icon

#

or just safeguard the icon_template

floral shuttle
#

o right. hmm. I use the sensor.alarm_panel_icon elsewhere too,

mighty ledge
#

then just safeguard it

floral shuttle
#

ok, let my try a few things. thx.

green adder
karmic prism
#

Hi I think i have a working template in developer tools templates but it's not working when i put it in a file called sling.yaml i'm trying to create an offset to a calendar event

#

is there a pastebin I can use ?

#

looking at wrong sensor , thanks

inner mesa
mighty ledge
green adder
mighty ledge
#

It's just how the onboarding process works for an entity when name and/or unique_id are supplied

#

it isn't described anywhere

#

so that page would need to be made, and then linked to from all the places that use unique_id and name

#

you're welcome to go down that path if you want

late trench
#

good afternoon. Is there anyway to use a template as a trigger? for example if i wanted any input_boolean "off" to "on" to trigger an automation and have the action from the automation also use a template?

late trench
#

tysm i'm so stupid i missed it.

mighty ledge
#

That won't work for your use case

late trench
#

yes i tried it ... i did look at this alread

#

y

mighty ledge
#

no matter what, if you have multiple booleans that turn on, the 2nd one will not trigger the automation.

#

templates need to be false -> true in order to trigger

#

if it's already true, it won't trigger again

late trench
#

ahhh

#

so i gotta just do it the old fashion way

#

list each one as a trigger

mighty ledge
#

you could trigger off state_changed events

#

but it'll catch everything

late trench
#

nope that doesn't work either

marble jackal
#

Create a template sensor with the count of the booleans which are on as state, and a list with the booleans which are on as attribute

late trench
#

i think i see where ur going with this

marble jackal
#

Trigger on state change, and get the one which triggered it by comparing the from_ state and to_state is the attribute

late trench
#

but it will also trigger from on to off in that case correct?

marble jackal
#

Add a condition that the to_state must be higher than the from_state

mighty ledge
#

Keep in mind a template sensor like that will only update 1 time per second at most

marble jackal
#

Also if you use a group and expand?

late trench
#

so i have a related question but not a template question.... is there a way to use an array as a trigger instead of listing each as its own trigger?

mighty ledge
green adder
#

I have updated my config to be:

template:
  - unique_id: "person_presence_"
    sensor:
      - unique_id: "test"
        attributes:
          friendly_name: "Test Presence"
        state: >
          ... logic here ...

which is much closer to what I want. However now have the entity coming out as: sensor.template_person_presence_test. Where does this template_ come from and can I remove it? I tried to have a quick look in components/template/sensor.py but I couldn't easily find where it was being added.

green adder
#

right but can I remove that?

mighty ledge
#

Yes, through the ui

green adder
#

but not in yaml?

mighty ledge
#

Already told you that too. You have to supply all three

#

Name, unique ID, friendly name. Entity Id will be a slugfied name.

green adder
#

That would mean I can't use the prefixing logic if I use name though right? because if name is provided then the unique_id's are not used at all in entity_id generation. Is there a way to get both the prefixing logic and not having it magically add strings to the entity_id?

mighty ledge
#

What?

#

Just make the name and the unique ID exactly the same. Then use whatever you really want the name to be in the UI the friendly name

green adder
# mighty ledge What?

So I can use unique_id at the outer layer to prefix all my entities with something (eg in my example above I use "person_presence_"). Then inside my individual items I have just the suffix. If I use name instead then doesn't that mean I need to put the whole name and copy/paste the prefix a bunch of times

#

Also I would really like to avoid changing things in the UI. I am going to have quite a lot of these things once I get my test one working so I would rather keep it in the config

mighty ledge
#

I think you don’t understand what unique ID does. It’s for the system to know what it is not for the user. A unique ID will be unique across the entire system. Each integration attaches a unique phrase to each unique ID that is unknown to the user

#

The whole point of adding a unique ID so that you can use it through the UI

#

So if you don’t want to edit things through the UI, don’t add a unique ID

green adder
#

ok, I will just set name + friendly_name. There is no logic to do the same kind of prefixing that you can with unique_id (both at the top layer and per sensor) for name in the config though right?

mighty ledge
#

I don’t understand what you mean with prefixing. What’s the point?

#

It literally does nothing

green adder
#

it just means I don't have to copy/paste the entity prefix over and over and possibly typo it

#

why does it exist for unique_id if it does nothing?

mighty ledge
#

What the hell do you mean entity prefix

charred dagger
green adder
#

I have logical groups of entities which I would like to all have a particular prefix eg for all my people presence ones I want person_presence_<person name>. With unique_id I can specify the person_presence_ once and just use <name> inside each sensor (with unique_id). I was just asking if there was a way to do the same with the entity_id generation

#

which is why using unique_id seemed appealing for getting the entity_ids that I wanted. but as you said it adds template_ which seems unavoidable

mighty ledge
#

Just use name instead with friendly name

#

Unique_id is for the system

#

i feel like htis is beating a dead horse, so your options are:

green adder
mighty ledge
#
- name: my_entity_id
  unique_id: some_prefix_my_entity_id
  attributes:
    friendly_name: Some really friendly name

or

#
- name: some_prefix_my_entity_id
  attributes:
    friendly_name: Some really friendly name
#
  1. will give you <domain>.my_entity_id 2 will give you <domain>.some_prefix_my_entity_id
green adder
#

I was asking if there was something like:

- name: "my_entity_id_prefix_"
  sensor:
     - name: "suffix"
       attributes:
         friendly_name: Some really friendly name  

That would give me an entity id of my_entity_id_preifx_suffix in the same way that you can for unique_ids

#

but it seems like the answer is no

mighty ledge
#

i'm not sure what you're expecting out of that

green adder
#

It's just to avoid copy/pasting the same constant in my config multiple times

mighty ledge
#

are you just trying to not repeat the prefix? That isn't possible in all of yaml

green adder
#

It just seemed like a cute feature for unique_id so I wondered if the code did the same for entity

mighty ledge
#

that's the unique_id adding the integration prefix for the system.

#

it's only built into the unique_id, so that the ID is unique across the system incase someone uses the same unqiue_id on 2 separate integrations

#

it's not a cute feature, unique_id is meant for the system, not users

#

What you're describing a want for can be done through a device in the UI

#

but template sensors don't have a device, so you don't get those benefits

#

If you're referring to the unique_id assigned to the root template level, that is unique to template sensors. If you look in the configuration variables, you'll see that name does not exist at that level. FYI, this would have gone alot smoother if you used the terminology in the documentation instead of talking about a prefix that's in the description of a field.

#

or a link to what you're talking about would have helped too. Then I wouldn't have gotten frustrated with you repeating this prefix talk without an example.

#

I guess you did mention it, but you used "outer layer". Sorry.

green adder
mighty ledge
#

Recipe for frustration. Anyways, sorry. And no, what you want doesn’t exist but it could exist.

green adder
#

no problem, it happens. Thanks for the help anyway, with the descriptions of the 3 fields I now have the entity_ids that I want and I have unset unique_id so the UI isn't allowed to change them (which is also what I want)

marble jackal
mighty ledge
# late trench 👍👍

if you really wanted a unique string for every possible combination of an input boolean being on, this would work

{{ states.input_boolean | map(attribute='state') | map(attribute='1') | list | join }}
late trench
mighty ledge
late trench
#

Oh very cool!

marble jackal
#

Don't you get the same result without casting it to a list first?

mighty ledge
marble jackal
#

Just tested in dev tools, it does 😀

mighty ledge
#

now just need to commit that to memory

green adder
#

I am building a sensor which abstracts over a manual override, the normal home/away tracking and possibly using other sources to determine if someone is home/away. So far I have this sensor (with some unimportant fields snipped):

  - sensor:
      - name: "person_nick"
        state: >
          {% if is_state("input_select.nick_status_override", "Auto") %}
            {{ states("person.nick_davies") }}
          {% else %}
            {{ states("input_select.nick_status_override") }}
          {% endif %}

Is there a nice way I can avoid copy/pasting the logic for every person I want to track? Currently they are all the same. I can generate the config file if necessary but I wanted to check if HA already had a way of simplifying this

#

I also have a similar problem with the input_selects I am using for the override eg I do:

input_select:
  nick_status_override:
    options: &status_override_options
      - Auto
      - Unknown
      - Home
      - Away
  vhia_status_override:
    options: *status_override_options
  ... more people here ...
floral shuttle
# floral shuttle ok, let my try a few things. thx.

well, this must be it then, no more error: icon_template: > {% if states('sensor.alarm_panel_icon') not in ['unknown','unavailable'] %} {{states('sensor.alarm_panel_icon')}} {% else %} mdi:shield-check {% endif %} feels somewhat clunky, but it gets the job done..

strange geode
#

have anyone success with combinde a IKEA curtan, an control it from google home ? (Instead of only using voice )
Im not the biggest code writer 😦

green adder
#

Is there a way to raise an error in a template? I have a condition I know is an invalid config and I would like to crash and tell the user

inner mesa
#

No, but you can have it output something that you can look for and write a log with a service call. There's no crashing

untold zodiac
#

is there a template way of creating a temperature sensor with the temperature from an hour ago? I know there's a statistics platform, but I'm only just setting up HA and just figuring things out. Its for working our a temperature trend, ie, if 20 an hour ago and 19 now, then the trajectory is negative....and it means I turn heating on earlier than just letting it get to the min value

inner mesa
untold zodiac
#

ok, that sounds like it might do it all in one thing....thanks I'll have a try

#

stupidly at the same time, I had a triggered template sensor in my configuration.yaml....

#

I want to move it to my sensors.yaml, but can'y quite figure out the levels

#

commented out now, but in configuration.yaml it was:

silent barnBOT
inner mesa
#

You can't put that in sensors.yaml

untold zodiac
#

has to stay in configuration.yaml?

inner mesa
#

You could create a templates.yaml and !include that

untold zodiac
#

ok sweet

#

thanks

lyric sun
#

hi, can I use comments within an array within an template?

#

set stuff = ["blah", #comment
"blub", #comment
"ding" #comment]

marble jackal
#

@lyric sun No, you can only use comments outside expressions or statements.
And Jinja comments look like this {# This is a comment #}

#

You could do this:

{% set blah = 6 %} {# Some comment #}
{% set bluh = 6 %} {# Another comment #}
{% set stuff = [ blah, bluh ] %}
vestal aspen
#

Hey guys, I have this as a sensor attribute data last_goal: 'Elias Lindholm (32) Wrist Shot, assists: Matthew Tkachuk (48), Johnny Gaudreau (55)' I need to just isolate the first name out, Elias Lindholm everything else after and including the (32) I don't need, How could i go about this properly?

#

last_goal: 'Michael Carcone (1) Wrist Shot, assists: none'

#

another example.

marble jackal
#

.split(' (')[0] should give what you want

vestal aspen
#

ty @marble jackal I will try that.

vestal aspen
#

Ty sir!

marble jackal
#

No problem. It splits the string on ( and takes the first part

vestal aspen
#

Yup kinda understood it, lol.

#

Now i can have audio callouts for the last scorer for my NHL scoreboard.

fast mason
vestal aspen
#

🎉

finite dune
#

Trying to set a input_datetime a year into the future, so as to automate Earth Hour procedures; this funky fresh templating isn't doing the trick; any suggestions?

{{ strptime(states('input_datetime.earth_hour_week'), '%Y-%m-%d %H:%:M:%S') + relativedelta(years=1) }}
marble jackal
finite dune
stuck remnant
#

I have a volume level helper and a service that sends a keypress of 'volume up/down' : 100 max volume, with a step of 2 so that's 50 keypresses total range, is there a way for a template to send the required amount of keypresses according to how I move the slider?

#

hmm, it would be a template to add/subtract the difference to 'now' and divide that by two, no?

marble jackal
#

Yes, calculate the difference between the old value and the new value and divide that by 2

stuck remnant
#

how? do you know the template? presses are switch.thegoat420_volumedown and switch.thegoat420_volumeup, sensor is input_number.volume_level

marble jackal
#

I assume you use an automation with the input_number as trigger?

stuck remnant
#

yes

nocturne chasm
#

Why wouldn’t you just use the state of the slider? Auh, key presses 😉

marble jackal
half cedar
#

I have a question regarding using variables in templates and scripts. I've already read the appropriate site but I'm not quite sure on some things.
The example in ( https://www.home-assistant.io/integrations/script/#passing-variables-to-scripts ) shows
data: title: "State change" message: "The light is on!"

and the same but with {{}} in the title and message. My question here is does it have to be "title" and "message" or can it be something else?

marble jackal
#

Can be whatever you want

half cedar
#

Thank you. I've now been playing with this and found that out also 😄

#

How would I put the variable "streamer" here **Followers**: {{state_attr('sensor.{{streamer}}','followers')}} using this will just ouput None ? I think it tries to search for {{streamer}} but there is none called that way. Yes I recieve the variable when using url: https://www.twitch.tv/{{streamer}}

#

ah okay I might just need to add two +

#

Nope doesnt seem to work

lyric sun
#

but I think its even worse there as its script within a template within a script

marble jackal
lyric sun
#

mhh ok but that complicates the script, guess it's fine for now

haughty kite
#

Not sure if I am right here. Is there a way with a sensor template to only set a new value if the sensor is not already having a data for the current day?

inner mesa
#

I suppose, based on the last_changed property of the template sensor

#

{{ iif (states.sensor.whatever.last_changed.date() != now().date(), "some_value", states('sensor.whatever')) }}

haughty kite
#

Maybe I can reframe my question. There is a plug-in and it is getting data from my heating. Whenever I restart HA this plug-in is getting the data and storing it. The value is the same on every request cause it gives the energy consumption of the last whole day. It is in kWh. In a Template Sensor I get that data and divide it by 10 to roughly convert it to m3. What happens now is that also for this template sensor it is having multiple states that day (all with the same value). And the HA energy dashboard calculates all these values and that is wrong. So what I tried to do is that I only store this data in the template sensor if the template sensor is not having data from this day. How could that be solved best?

inner mesa
#

what I provided seems fine for that

haughty kite
#

What happens if I had three states on the source sensor and the first was „unavailable“. Then it would lead to the fact that the next state with valid data would not be processed, right?

inner mesa
#

you can add and states('sensor.whatever') != 'unavailable'

#

or base the check on the source sensor

finite dune
#

Step Details section says: Error: Template rendered invalid service: input_datetime.set_datetime ''

inner mesa
#

that's bad syntax

#

you can't set a variable in one template and then use it in another, but there's no reason to do it that way

#

without paying attention to what you're trying to do:

  - service: input_datetime.set_datetime
    data:
      datetime: >-
        {% set d = as_datetime(states('input_datetime.earth_hour_week')) %}
        {{ d.replace(year=d.year + 1) }}
      entity_id: input_datetime.earth_hour_week
normal geyser
#

{{ state_attr('weather.kgrr_hourly', forecast')[0].precipitation_probability }}

I finally got this to work in the template editor and it gives me the output I want, but struggling to integrate it into home assistant. How do I go about using this data? I've tried to create a sensor in my configuration.yaml but I'm lost

inner mesa
#

"integrate" it how? What do you actually want to do?

#

do you want a template sensor with that as the value?

#

I've tried to create a sensor in my configuration.yaml but I'm lost
Perhaps sharing what you've done will help

normal geyser
#

I just want to be able to use that data I'm getting somehow. If I could turn that data into an entity or something.

`sensor:

  • platform: template
    sensors:
    kgrr_hourly:
    value_template: "{{ state_attr('weather.kgrr_hourly', forecast')[0].precipitation_probability }}"
    friendly_name: Weather Hourly Rain
    unit_of_measurement: '%'`

this was one of the things I tried in my config.yaml. Been googling like crazy and can't find the right way to get that working

normal geyser
inner mesa
#

the only thing wrong with what you posted is that you're missing a quote next to forecast

#

if you fix that and it's still not working, then please be more specific about what's not working the way you would like

normal geyser
#

I feel incredibly dumb now thank you rob it’s working now 🤦🏻‍♂️

tardy basin
#

Hey all. I am fairly new to all of this, so please tell me if this is a bad way to go about this.
I am trying to set up presence detection based on if the HA app detects if my phone is connected to a certain wifi access point. I have the HA android app all set up and can see it is showing the wifi ID.

I moved on to create a template and while no syntax is being flagged as incorrect, I am not sure it is working, as my presence is still marked as not_home in HA.

configuration.yaml is:


# Text to speech
tts:
  - platform: google_translate

automation: !include automations.yaml
script: !include scripts.yaml
group: !include groups.yaml
template: !include templates.yaml```
and templates.yaml
```sensors:
  pixel_5_home:
    state: >-
      {% if states('sensor.pixel_5_wifi_connection') == "WIFI" %}
        home
      {% else %}
        not_home
      {% endif %}
    name: 'Pixel 5 Home (SSID = WIFI)'```
silent barnBOT
nocturne chasm
#

The HAss companion app has a device tracker. Why are you not using that?

tardy basin
#

I believe I have that set up? I have "WiFi Connection" enabled under "Sensors" in the companion app

#

Unless that is something different

#

Ohh the GPS.

#

The GPS on my device consistently is wrong so I didnt want to soley rely on that. When I did get it working and set my home location to where it was saying I was, it still had me as not_home.

nocturne chasm
#

Are you allowing tracking permissions.

#

@tardy basin , I would also use the ssid sensor instead of the connection status, as every time you are connected to,WiFi it will show you as home

tardy basin
nocturne chasm
#
{% if is_state('sensor.your_device_ssid', 'Your_SSID') %}
  home
{% else %}
  not_home
{% endif %}
tardy basin
#

Great I will give this a try. Thank you!

astral turtle
#

Hi,
Pls help me with a template that will show for how long the door is opened based on (binary_sensor.door_contact state), in a format of hh:mm. Thanks!

stuck remnant
marble jackal
marble jackal
astral turtle
#

Well I will use it to assign a message. I am not asking the full thing cause understand what to do, just need help with this template.
Thanks 😉

marble jackal
#

Yes, but you can assign the message in one go

#

example:

message: >
  {% set gate_open = ((now() - states.binary_sensor.door_contact.last_changed).seconds / 60) | int %}
  {{ 'Gate just openened' if gate_open < 2 else 'Gate is already open ' ~ gate_open ~ ' minutes' }}
astral turtle
#

What do you mean?
My idea was to have a message like this message: {{ states('sensor.gate_notify') }}. Make alert repeat every let say 60 min, once opened sensor will be opened, that it will me opened for more than xxxx.

marble jackal
#

Well, like I have done above 😛

#

but that will show it in minutes, you can also use a time format

astral turtle
#

not that good at templates was using such constructions before

  • name: "robot_1floor"
    state: >
    {% if is_state

Thanks!

marble jackal
#

Or you can use this:

message: >-
  {%- set entity = 'binary_sensor.door_contact' %}
  {%- set gate_open = (now() - states[entity].last_changed).seconds %}
  {%- set open_for = relative_time(states[entity].last_changed) %}
  {{ 'Gate just openened' if gate_open < 120 else 'Gate is already open for ' ~ open_for }}
#

It will not show an exact time, but minutes if minutes are relevant, hours if hours are relevant, days if days are relevant, etc

marble jackal
astral turtle
#

Sorry for stupid question.
"message: >-"
What does this mean. Before I was using state: > and then using the value of the sensor to in messages to telegram.
Something like this
message: |
{{"\U0001F916"}} Robot: {{ states('sensor.robot_1floor') }}.

stuck remnant
#

haha you'll like this

#

the helper triggers the keypresses for volume change via your template and also gets updated by a sensor in order to reflect the volume on the pc. When the sensor updates it triggers the template so it just goes on and on like that

marble jackal
#

You can template the message in your alert

#

so that's why I used message

astral turtle
#

Ok, googled it, found some examples, have now information to think and experiment. Thanks!

marble jackal
stuck remnant
#

yeah I know, it's the expected behaviour, I just thought it was neat :p

#

anyway, the sensor updates the helper because sometimes I change the volume via the pc. Don't really know how to get around this

marble jackal
#

I expect iif(states.input_number.volume_level.context.user_id) only returns true if you changed the input_number by yourself (by moving the slider) and not when it is updated by the actual volume change

marble jackal
stuck remnant
#

wow thats nice

marble jackal
#

and add the following to your automation so you don't get messages about the automation running multiple times

mode: single
max_exceeded: silent
#

However, that does mean you'll have to wait until your change has been fully processed until you can change the slider again

stuck remnant
#

that's cool, it'll do

#

cheers!

#

ok now it doesnt trigger at all, after I added the condition

marble jackal
#

@stuck remnant It's a template, use "{{ iif(states.input_number.volume_level.context.user_id) }}"

finite dune
astral turtle
cyan musk
#

Im trying to figure out how to format a state attribute to only show the time rather than the date and the time, my current attempt at the code:

template:
  - sensor:
      - name: "Next Tram to City"
        state: "{{strptime(state_attr('sensor.tram_to_city', 'origin_stop_arrival_time'), '%Y-%m-%d %H:%M') | timestamp_custom('%I:%M %p') }}"
        icon: "mdi:tram-side"
marble jackal
marble jackal
cyan musk
marble jackal
#

Hmm, 2nd one works for me as well, but it the other one works it's probably fine

sick whale
#

Hi! I'm a super newbie with Home Assistant, I installed it last week. I'm trying to have an entity that is the sum of two entities. From the docs I got that I need to create a template with the operation, I tried the template in the template editor and it works. But I can't figure out where I need to store that template. I know this is really basic, but I've been browsing the docs and looking at youtube videos and can't figure it out :(.

marble jackal
sick whale
#

Do I need to add "template" as an integration? I tried that and it told me that template was not available as an integration

inner mesa
#

you need to edit the YAML as shown in the docs

sick whale
#

Thanks, yes, I've figured that I need to edit the YAML, but still stumbling with the syntax. All the template docs I could find are about how to write the template, not about where to add the YAML code :(.

inner mesa
#

into configuration.yaml

proud crater
inner mesa
#

I don't see anything inherently wrong with it. Did you reload templates and check the logs?

buoyant pine
#

== 0 isn't ideal tbh. I'd reverse the logic (> 0)

inner mesa
#

well, yeah. check the template in devtools -> Templates and make sure that it says what you want, in addition to monitoring the state

proud crater
#

in developers tools template working wtf

#

but no default was specified. Currently 'float' will return '0', however this template will fail to render hmm @inner mesa

inner mesa
#

what was the actual state?

proud crater
#

in HA old state is off, in developers tools working state is Washing

inner mesa
#

of the sensor that you're trying to convert to a float

sacred sparrow
#

I am getting this error "value must be at most 1 for dictionary value @ data['volume_level']. Got None"

service: media_player.volume_set
data: {}
target:
  entity_id: media_player.sonos_system
data_template:
  volume_level: '{{ states.media_player.sonos_system.attributes.volume_level + 8 }}'
inner mesa
#

you have both data: and data_template:, and data_template: was deprecated around 2 years ago.

#

remove the data: line, change data_template to data:, and ensure that the template actually returns what you think it does in devtools -> Templates

buoyant pine
#

Also, volume_level has to be between 0 and 1, so you'll need to account for that in the template

sacred sparrow
#

great - thanks guys 🙂

#

so I got this to work

#
service: media_player.volume_set
target:
  entity_id: media_player.sonos_system
data:
  volume_level: '{{ states.media_player.sonos_system.attributes.volume_level + 0.1 }}'
#

but when I do it with my tv:

#
 service: media_player.volume_set
target:
  entity_id: media_player.living_room_tv_kd_75x8500e
data:
  volume_level: >-
    {{ states.media_player.living_room_tv_kd_75x8500e.attributes.volume_level + 0.1 }}
#

for example the tv is set to 41... it then goes to 51 for half a second then goes to 43 for some reason

#

why would it turn itself down? - is it because the TV is connected to the sonos(first code) via arc

stuck remnant
clever dawn
#

Hi everyone, tom_l has been helping me with grabbing a list of bus times from a website. I have been able to get the first time, but the website lists anything up to 5 times depending on the time of day. I'd like to grab all available and add them to a card on my dashboard. Here is the code I am using at the moment- platform: rest name: Bus Times json_attributes_path: "$.buses[0]" json_attributes: - route - time - destination resource: https://transperth.maxrumsey.xyz/api/v1/busTimes?stop_number=18418 value_template: "{{ value_json.buses[0].time }}"

#

How do I specify buses[1-4] even though at night there may only be 1 or 2 or even 0 times available if there a no further buses coming today

#

How often will this sensor refresh by default?

clever dawn
#

Thanks, thats a lot more frequent than I need but will work

marble jackal
#

For your main question, what would you like to have? A comma seperated list with all the times?

clever dawn
#

Open to ideas, I was going to put it in an bus times entities card and have each time on a new line, but that would work also

#

The route # and destination wont change

marble jackal
#

{{ value_json.buses | map(attribute='time') | join(', ') }} this would give the times

#

You don't need the attributes then

clever dawn
#

if its the end of the day and no more buses are available, it will just display nothing?

marble jackal
#

yes

clever dawn
#

and no requirement for json_atrributes...?