#templates-archived
1 messages · Page 98 of 1
can you write in English exactly the conditions you want? that usually helps
I mean 'and' these:
- condition: template
value_template: "{{ trigger.from_state != 'unavailable' }}"
- condition: template
value_template: "{{ trigger.from_state != 'unknown' }}"
and or these
- condition: template
value_template: "{{ states('sensor.live_hass_version') != states('sensor.current_version') }}"
- condition: template
value_template: "{{ states('sensor.live_hass_version') != states('sensor.beta_version') }}"
and 'and' them together
when from_state is not equal to 'unavailable' and from_state is not equal to 'unknown' and (hass version is not current or hass version is not beta version) alert
right?
I think your just reducing the code, which is great, but the conditions aren't hitting as I expect
I don't think your conditions are correct
for instance, if from_state is "unknown", your 'or' statement will pass because it's also not 'unavaialble"
you're just oring them all together
I'll reformat it with if, elif etc thanks
probably easier than wrestling with the YAML formatting, to be honest
Ya
trigger.from_state also needs to be trigger.from_state.state
Thanks I'll move it back
I have it set to read tomorrow
randomly adding or deleting things is one way to solve problems
it just may take infinite time
I'm looking for a way to check and see if all of our iphones are charging. Would a template be the correct way to do that?
sensor.tommys_phone_battery_state The value is either "Charging" or "Not Charging" for this sensor
comeon bot..
https://www.home-assistant.io/integrations/template/
would say with something like
{{states('sensor.tommys_phone_battery') }}
or something from:
https://www.home-assistant.io/docs/configuration/templating/#states
thank you!
looks like images aren't allowed here, but i'm trying to remove new lines using regex. this is my current markdown card code (had to remove weird = that appeared already).
`Hello, {{user}}
{{ state_attr('sensor.xxxx_email', 'body') |regex_replace(find='=', replace='', ignorecase=False)}}`
using the imap_email_content default config (which pulls the body of the email)
{{"test
test
=
test"
| regex_replace(find='=', replace='', ignorecase=False)
| regex_replace(find='\n', replace='', ignorecase=False)
}}
this worked for me
@river saffron did you see that?
sorry, saw it now
{{"test test = test" | regex_replace(find='=', replace='', ignorecase=False) | regex_replace(find='\n', replace='', ignorecase=False) }}
@timid osprey didn't work, but restarting
yeah, that doesn't work
in your template tester?
in the markdown card. the = part works (i removed it and the = reappeared) but the \n did nothing
okay, I know nothing about that card but markdown does line returns with double spaces
{{
"test
test
=
test"
| regex_replace(find='=', replace='', ignorecase=False)
| regex_replace(find='\n', replace='', ignorecase=False)
| regex_replace(find=' ', replace=' ', ignorecase=False)
}}
you could try that
The line break you're trying to remove is likely to care about which OS you typed it on.
yeah, I stepped away and realized what was going on
i guess i'm confused how regex works. is it dependent on what OS it is being viewed on? or what OS HA is installed on?
per the link \r\n is for windows. i'm viewing it on windows but HA is installed on a debian machine
New to templating here. I'm trying to create a template that I can evaluate with "everyone_ready_for_bed". Here's the template, but I don't see it under Developer Tools -> States. This is in a file "bedtime.yaml"
- platform: template
sensors:
everyone_ready_for_bed:
friendly_name: 'Everyone ready for bed'
value_template: >-
{ % if is_state('sun.sun', 'below_horizon') and
is_state('tommys_iphone_battery_state', 'charging') and
is_state('cindys_iphone_battery_state', 'charging') and
is_state('tylers_iphone_battery_state', 'charging') and
is_state('sarinas_iphone_battery_state', 'charging') %}
'on'
{%- else -%}
'off'
{%- endif -%}
Is that under sensor: or binary_sensor:?
Are you getting config errors? How is bedtime.yaml included? Is HA even seeing it?
Ah. I think that's the first problem. The file is in an ./includes folder, which I though was included automatically, but apparently it's not. So, I guess i need to move that to my automations folder.
Actually, I'm not sure. I'd like to set a binary sensor for the state, which I can check to automatically set my home alarm and turn off a few things.
Well where you put that YAML code depends on how you have your system configured. But assuming it ends up under binary_sensor:, then there are two problems. First, the entity_id's in the is_state() function calls aren't valid entity_id's. I'm assuming they should be sensor.blah. The second problem is a template binary sensor's value_template should evaluate to true or false. Putting these together I'd suggest:
value_template: >
{{ is_state('sun.sun', 'below_horizon') and
is_state('sensor.tommys_iphone_battery_state', 'charging') and
is_state('sensor.cindys_iphone_battery_state', 'charging') and
is_state('sensor.tylers_iphone_battery_state', 'charging') and
is_state('sensor.sarinas_iphone_battery_state', 'charging') }}
how would you go about setting a templated automation to use a condition in the name.
something like this:
- id: ikea_power_on_trigger
alias: Turn on ikea light when heard join notification
trigger:
platform: mqtt
topic: zigbee2mqtt/bridge/log
action:
service: light.turn_on
data_template:
entity_id: light.{{ trigger.payload_json.meta.friendly_name }}
which would only apply if the name contained _light
i guess i'm confused how regex works. is it dependent on what OS it is being viewed on? or what OS HA is installed on?
@river saffron regex will work the same on every system. The difference is the input. If I create a file in Notepad on Windows with line breaks in, Windows will add \r\n. If I save it, send it to you, and you open it on Linux, those line breaks are still \r\n. They're invisible characters in the file and don't change automatically just because you're viewing it on a different OS.
Hi, I'm trying to make a climate toggle switch and I'm tring to make a template switch
- platform: template
switches:
aerconditionat_on_off:
value_template: "{{ is_state('climate.mideaac', 'on') }}"
turn_on:
- service: climate.turn_on
entity_id: climate.mideaac
turn_off:
- service: climate.turn_off
entity_id: climate.mideaac
Now i'm here, but when i turn off, after 3 seconds it goes back to off
@river saffron regex will work the same on every system. The difference is the input. If I create a file in Notepad on Windows with line breaks in, Windows will add \r\n. If I save it, send it to you, and you open it on Linux, those line breaks are still \r\n. They're invisible characters in the file and don't change automatically just because you're viewing it on a different OS.
@ivory delta ok so it's the source of the content. since it's the imap_email_content, it must be how the email is formatted then.
@vast parcel does climate.mideaac go to the state 'on'?
Any guess why this isn't rounding at all? I want no decimal places:
value_template: >- {{ (float(states.sensor.jane_s_room_temperature.state) + float(states.sensor.gameroom_thermostat_temperature.state) + float(states.sensor.upstairs_thermostat_temp.state)) / 3 | round()}}
I think you're rounding the 3 at the end, then doing the division.
Put brackets around everything before the | round()
ok I tried
{{ (float(states.sensor.jane_s_room_temperature.state) + float(states.sensor.gameroom_thermostat_temperature.state) + float(states.sensor.upstairs_thermostat_temp.state)) / 3 }} | round()
but still geting 78.333333333
Ah jeez ok I've always called those parentheses
That's another name. It just takes longer to type 😄
[] brackets
Square brackets, yes 😉
😛 are you US?
When I'm not being lazy, I'll use the full 'parentheses' (), 'square brackets' [], 'curly braces' {}. Clarity of language matters when describing dev stuff.
No, I'm British. Happy to hear that the US also uses the correct terminology though.
im american and just dont bother learning the names lol
good on you to keep propagating the stereotype
"parens" "square brackets" and "curly brackets" for me
I tried creating a template cover using a shelly 1 relay and wyze door contact sensor. I get it showing up in lovelace but only the open arrow is operational the close arrow is not. The icon also will not change depending on if the door is open or closed. Below is my info
cover:
- platform: template
covers:
garage_door:
value_template: "{{ is_state('binary_sensor.wyzesense_77a56ff3', 'on') }}"
open_cover:
service: switch.toggle
data:
entity_id: switch.shelly_shsw_1_e0980694eb47
close_cover:
service: switch.toggle
data:
entity_id: switch.shelly_shsw_1_e0980694eb47
icon_template: >-
{% if is_state('binary_sensor.wyzesense_77a56ff3', 'open') %}
mdi:garage-open
{% else %}
mdi:garage
{% endif %}
@spark isle
your states are off
binary sensor = on/off
not open
can I stick such a template in a single line?
- condition: or
conditions:
- condition: template
value_template: "{{ 'single' == trigger.payload_json.click }}"
- condition: template
value_template: "{{ 'double' == trigger.payload_json.click }}"
@thorny snow
value_template: "{{ trigger.payload_json.click in ['single', 'double'] }}"
I realy should learn jinja - thanks a lot petro
np
I'm working on an automation to test if all of our phones are charging, and just set an input_boolean to reflect that. This would require two automations, correct? One that would trigger if they are all charging, and another if not.
Why not just create a binary template sensor? No need for automations.
I've been messing with that to no avail. Thought I'd break it down. I hate to bug people, and I've read through the docs but I'm not understanding real well. You helped me with that some yesterday. Would that binary template sensor be considered an automation?
Binary sensors are #integrations-archived
They're not triggered, as such. Their state just changes as needed as the underlying entities update.
so, I've got my config split out into a folder for automations, packages, and then one called "includes" which are directly reference from configuration.yaml. I'm just not understanding where to place it.
Well that's a separate issue. One thing at a time. Do you understand how to create a binary template sensor for this?
Taking care of it in #integrations-archived, we'll find out in a sec if it's okay 🙂
Ah. I had that channel muted so I didn't notice. 😅
Probably should ask in #330944238910963714.
how do I test properly in an if else template?
- service_template: >-
{% if (trigger.payload_json.click, 'off') and
is_state("switch.relay", "off") %}
light.turn_off
{% else %}
script.turn_on
{% endif %}
``` I got the feeling that I'm close
You can put that in the template editor, after:
{% set trigger = {"payload_json": {"click": "off"}} %}
But I can tell you (trigger.payload_json.click, 'off') isn't right. It should probably be trigger.payload_json.click == 'off'.
that makes things faster - I restart here over and over
@thorny snow You can also avoid template altogether and sue the new choose action 🙂
hi there! I am a newbie and ask me how to set conditional icon according my roller shutter state. I use shelly relay to manage the shutters. I got on dashboard a card with inside my shutters, I can change icon but how to ser mdi:window-shutter icon when state is close or up to 80% close and mdi:window-shutter-open when it's open ?
you can change the icon of a template sensor using a template: https://www.home-assistant.io/integrations/template/
or you can change the icon in Lovelace with a card that supports it (like custom button card: https://github.com/custom-cards/button-card)
I do this for my garage door:
- platform: template
sensors:
garage_door_state:
value_template: '{% if is_state("binary_sensor.garage_door_sensor", "on") %}Closed{% else %}Open{% endif %}'
friendly_name: 'Garage Door'
icon_template: '{% if is_state("binary_sensor.garage_door_sensor", "on") %}mdi:garage{% else %}mdi:garage-open{% endif %}'
thanks @inner mesa
Thanks Frenck, pnbruckner pointed me already to it, but I dont like the structure to much.
I actualy prefere the template syntax.
Hi all, still prett fresh to this; I’ve been trying for hours now to set up 2 x template sensors and can’t work out where they go.
I’ve built an ultrasonic level sensor for a tank and by default it measures distance to object. Using a lambda filter I can get it to return either percentage or litres, however I would like both % and L displayed in lovelace. I think I do that using template sensors and the default distance output and a maths equation.
I’m struggling to find where I put the template sensors and how to build the value_template from my formula. I’ve tried putting it in my sensor.yaml and it faults and I’ve tried putting it in my config and it faults. Feel like I’m missing something. I’m using supervisor hass
~template
bot is dead
need to see your config and your errors
Nah, discord changed something and he hasn't had time to work on it
pff 😄 at least.
(just get the deam emojis back 😛 )
check out this page
https://www.home-assistant.io/docs/configuration/templating/
@inner mesa so it’s meant to be in config rather than the sensor.yaml?
@thorny snow man I tried reading that, it’s so far above my head haha 😦
it can be in either location, but it depends on what you're doing
need to see your config
sensor yaml is fine
but packages might help you out
https://www.home-assistant.io/docs/configuration/packages/
(you can put everything in it)
if you have a sensors.yaml or similar, then do that
I'm guessing that you probably put sensor: in there, and that's your problem
but random guessing without seeing what you alredy have
I’ll take a screenshot
no screenshots here
screenshots of text are worthless
Was just to show error
I guess youre missing the first step
go to your frontend and into developer-tools/template
Oh yeh where you can try it out. Sorry I must sound like the biggest noob but I couldn’t figure out that either
in there delete everything and start with this
{{ states("sensor.NAME_OF_YOUR_SENSOR_FIND_IN_STATES") }}
(the button 2 left of template)
Brb I’ll goto computer, trying to copy text on my phone isn’t ideal
just use the one you got already in there
Anne Therese is at {{ states("device_tracker.anne_therese") }}
Paulus is at {{ states("device_tracker.paulus") }}
thats the start of almost every template,
Thanks mate, from there I should be able to get the equation sorted. Then I gotta figure out where to put it all
thats a little tricky too,
I advice you to create a package folder, its realy waaay easyer in the start, but you ll hate you later when you want to tidy it up
then you can have a file with content like this
@maiden raven posted a code wall, it is moved here --> https://paste.ubuntu.com/p/4dZC5GckKj/
rly bot.. 😄 just check the link
take care that you dont mix " and ' in the variables (line 8)
use one inside and anotherone outside
you ll need both things here, templates wont update themselfs without an entety
Still getting started with template. What do I need to use to grab the entity's friendlyname?
nah - head over to states
friedly name is just for humans
you ll need the Entity ID
@thorny snow thanks heaps i'll check it all out and have a crack
friendly_name is an attribute, so follow the instructions here using is_state_attr()
here's the trigger in one of mine:
- alias: 'fr_yttv_started'
initial_state: true
trigger:
- platform: template
value_template: >-
{{ is_state_attr("remote.family_room", "current_activity", "Watch Shield") }}
Thanks, I will take a look at it!
Sadly it looks like my friendly_name doesn't actually change, there is a attribute called sonos_group that has the value of ['media_player.beam', 'media_player.one'] What would be the correct format to use that? just putting that between the "" doesn't do the trick.
who can tell me why this isn't working in .113 anymore?
https://paste.ubuntu.com/p/tkmB5Hf2kH/
"doesn't work"?
yeah before i got a nice list of device_tracker entities out of this template... now it stays empty :/
did you look at sensor.wifi24devices in dev->States?
Sadly it looks like my friendly_name doesn't actually change, there is a attribute called sonos_group that has the value of
['media_player.beam', 'media_player.one']What would be the correct format to use that? just putting that between the "" doesn't do the trick.
Nevermind, it works but for some reason it reports false
@fierce hornet I'm sure there's a more elegant way, but this would work:
{% set attr = state_attr(sensor.xxx, "attr") %}
{% 'media_player.beam' in attr and 'media_player.one' in attr %}
What would go into the place of sensor.xxx? I'm using a template switch. So would that become the template switch itself?
whatever the entity is
ohh
that's an attribute of something, right?
looks like "attr" should be "sonos_group'
just piecing things together from your messages
point is, I don't think it'll work as just a string comparison
Trying it now using sonos_group as attr
share your template?
Using
{% 'media_player.beam' in attr and 'media_player.one' in attr %}```
screenshot of the entity in dev->states?
@thorny snow i havent gone through packages yet but as far as adding it to my water_tank_level.yaml i get the following error, gets caught up at sensors:
mapping values are not allowed here in "/config/esphome/water_tank_level.yaml", line 49, column 10: sensors: ^
No need for sorry, wouldn't have been able to figure this out myself
this should work in a template trigger:
{% set attr = ['media_player.beam', 'media_player.one'] %}
{% if 'media_player.beam' in attr and 'media_player.one' in attr %}true{%endif%}
I had it working and then made some changes that I thought would get it closer to what you need. And I broke it 🙂
Uhh it seems to be always true now? 😅
@marsh thunder https://discord.gg/DBsn59
@fierce hornet not for me
what does the attribute look like in your failing test case?
- media_player.beam
thanks rob, i'll try over there
this returns nothing for me, while the previous one returns true:
{% set attr = ['media_player.beam'] %}
{% if 'media_player.beam' in attr and 'media_player.one' in attr %}true{%endif%}
you could put an {%else}false in there if you want "false"
Maybe we are not on the same page. I want it to display true when the sonos_group attr contains the beam & one entity and false when it only contains the beam entity
so just add {%else}false in there
I'll try that
{% set attr = ['media_player.beam'] %}
{% if 'media_player.beam' in attr and 'media_player.one' in attr %}true{%else%}false{%endif%}
works for me
but I don't think it's necessary for a trigger. Looks like 'true' is enough from here: https://www.home-assistant.io/docs/automation/trigger/#template-trigger
{% set attr = ['media_player.beam'] %} {% if 'media_player.beam' in attr and 'media_player.one' in attr %}true{%else%}false{%endif%}
This doesn't do it for me
But
{% set attr = state_attr('media_player.beam', 'sonos_group') %}
{% if 'media_player.beam' in attr and 'media_player.one' in attr %}true{%else%}false{%endif%}
this does
But when using your template it always displays false
you're right, it will. it was a test case to return false
I see the diff now. I was explicitly testing for both when only one was present to test false because you said that your test always returned true
anyway, you have a solution now?
that's what I was afraid of
think through it and it'll help you in the future
['xxxx', 'yyy', 'zzz'] is an array in Python/Jinja and 'xxx' in array just tests whether 'xxx' is one of the elements in the array
make sense?
np
It fully works now! A switch that disables / enables the speakergroup of those 2 sonos speakers 🙂 with correct state!
and you learned about arrays and some conditional syntax. all in all, a productive day
Never had such a productive day before
@marsh thunder
were already in the bed. thing ist that you cant mix up esphome syntax and home assistant syntax.
they work togeter but are effectly complete diffrent things.
The way I shown you would take the output from your sensor in home assistant and do the maths, but you could defenitly do all this in esphome itself.
@thorny snow Yeh I think that’s where I went wrong. I was trying to use home assistant template sensor in esphome config.
I’ve got it working for now, using HA templates. I’ll work our the esphome side later, computer is playing up after I installed some drivers whoops.
Cheers for all your help
np, lurking around here to offer and get help 😛
Good day, a question from a simple person. I would like to check whether there has been a power cut to a Raspberry Pi in my cellar. The RPi measures electricity consumption and feeds the data via MQTT to my HA controller. So the set up I have come up with is that every 5 seconds the RPi sends a timestamp via MQTT. And I have created a sensor on the HA controller that records the RPi timestamp, and a template sensor that compares the HA controller timestamp with the RPi timestamp. If there is a difference of more then 10 seconds the output is "false" (and if there is not the output is "true"). To trigger the template I have used sensor.time. However this has not worked in spite of the template showing the correct output when I run it on the Developer Tools/Template page. I now realise that sensor.time triggers once every minute so it will not pick up a power cut until a minute has passed. While this is not a deal breaker, I would like to know within a few seconds. So my question is: Is there a way of triggering the sensor template more frequently than 1 minute? TIA.
Actually even if I leave the RPi off for more than a minute the template sensor continues to result in "true". Which is odd. Here is the template:
check_cellarpi_running:
friendly_name: "Cellar power check"
entity_id:
- sensor.time # required to update now()
- sensor.cellar_pi_timestamp
value_template: >-
{% set t = now().timestamp() *1000 %}
{% set c = states('sensor.cellar_pi_timestamp') |float %}
{{ (t-c) < 10000 }}
value_template: >-
{% if state_attr("sensor.smarter_kettle_status", "sensors")["base"] == "On" -%}
on
{%- else -%}
off
{%- endif %}
can anybody se an error here
working in dev tools but always of as a template sensor
@lyric sun I'm sorry Icould you tell me
@lyric sun I'm sorry I'm too far down the food chain to answer your question (unless it is something to do with needing sensor.time to trigger your calculation). But please could you tell me how you put in the red line showing the new thread? Thank you.
thats there automatically if somebody posts while you don't look at the chat window
OK thank you.
I'm trying to get a list of entities that have a certain attribute 'node_id'... I am trying this:
{{ states.light|map(attribute="node_id")|list }}
but I just get a list of 'undefined' entries
Are you sure they all have that attribute? I get the same problem with your example but it works if I use the attribute entity_id.
no, they do not all have that attribute
that's what i am trying to do: build a list of entities that do have that attribute
I found a for loop that will do it, but I'm struggling with how to build a list in a template... it seems .append() is not allowed
{% set my_list=[] %}
{% for state in states %}
{% if state_attr(state.entity_id,'node_id') != None %}
{{ my_list.append(state) }}
{% endif %}
{% endfor %}
make it an input_select
Look at |rejectattr() in the jinja docs
value_template: >- {% if state_attr("sensor.smarter_kettle_status", "sensors")["base"] == "On" -%} on {%- else -%} off {%- endif %}
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
Could shorten that to
'{{state_attr("sensor.smarter_kettle_status", "sensors")["base"] == "On"}}'
@dreamy sinew I think the issue is that state attributes are not considered attributes in the jinja sense
Those ones aren't state attributes though, right? So it's right that they're not accessible in the same way.
It's like the last_changed stuff.
Hmm
Not something I've attempted
But it's best to try to use select/selectattr/reject/rejectattr rather than do it yourself
Could shorten that to
'{{state_attr("sensor.smarter_kettle_status", "sensors")["base"] == "On"}}'
@dreamy sinew thanks, sure, that should work
There is a way but it's a bit obnoxious
@lyric sun when your desired output is a bool, no need to overcomplicate with an if block
I just found it wired that binary sensor seems to need true/false although documentation says "The state of a Template Binary Sensor can only be on or off" however I just read the template part and it says "The sensor is on if the template evaluates as True and off otherwise."
It's a boolean. Why overcomplicate it?
Plus different classes can show other values in the UI for it's state
Open/closed etc
Binary is always just boolean. Let HA figure out how to display it.
sure just changed it
a bit wired is that in the automations you then need to use off/on instead of true/false
Binary is always just boolean. Let HA figure out how to display it.
@ivory delta sure, i didn't want to change the display that way I just wanted to change the value, which I now know needs to evaluate to true/false instead of on/off
I'm not sure it can be done: {{ states.light | selectattr('friendly_name') | list }}
for example, does not work
they all have that for sure
You need a test
Or a list comprehension
{{ [x.friendly_name for x in states.light] }}
I also found this works: {{ states | selectattr('attributes.node_id') }}
hey guys whats a proper way to debug and troubleshoot homeass? Im trying to get entity_picture_template to work but it doesnt.. And i'm not sure what the issue is
I have a sensor.al and im trying to update the entity_picture depending on the value. I have found a couple of threads and examples and i try to follow them. I've check the templating engine that it does return the /local/img/image.png and that it is accessible from a browser... But still the god damn image doesnt change
/local is cached
I've got the following thing for my action.
data:
clickAction: https://myhome{state_attr('camera.mycamera','entity_picture')}}
message: https://myhome{state_attr('camera.mycamera','entity_picture')}}
Problem is: in the message field, template is executed just, but it is not in clickAction (I've got state_attr literally)... I'm very confused
Rule 1 of templating
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
Also missing a { on both
(sorry bad cc)
i see
so... it is mandatory to use the file editor instead of the automation page when doing so?
Hmm, I don't remember as I don't use the ui
Or HA automation either for that matter
that's very useful, thanks
friendly_name: 'Edith On Time'
value_template: '{{ (as_timestamp(states.sun.sun.attributes.next_setting) + (states("input_number.edith_sunset_offset") | int) * 60) | timestamp_custom("%I:%M %p", True) }}'
hour: ?
minute: ?
edith_off_time:
friendly_name: 'Edith Off Time'
value_template: "{{ (state_attr('input_datetime.edith_off_time', 'timestamp') | int | timestamp_custom('%I:%M %p', False)) }}"
hour: ?
minute: ?```
Can anyone help me figure out how to format the hour and minutes for both of those sensors?
Oh, that is helpful thank you
Is there a way in a template to set a state that doesn't exist? I have that "edith_on_time" and off_time and I want to set a state "hour" and "minute" for each of them. I believe I understand the formatting now (thanks BUSheeZy!)
I'm a beginner with HA, not sure what's the right place to ask. I want to make a card that lets me specify a wakeup time and duration, and an 'enabled' switch then send those commands to my tasmota light
how do i template an event trigger
as an example:
- platform: event
event_type: zha_event
event_data:
unique_id: "00:17:88:01:04:e4:db:43:2:0xfc00"
command: "down_hold"
this
in relation to this:
action:
- choose:
# IF motion detected
- conditions:
- condition: template
value_template: "{{ trigger.to_???.???? == 'down_hold' }}"
sequence:
- service: light.turn_on
entity_id: light.ikea_tradfri_balcony
data:
brightness: 225
color_temp: 250
nvm i found what i needed
having an issue with my scripts and just be missing something basic here. ive included my error here and the relevant yaml snippets https://hastebin.com/zosubugena.sql
im just not sure where its expecting a decimal. if i try the data values in developers tools for the service it works fine, so i know its not the service that wants a decimal value
the turn off functionality works fine
You'll need to convert the hex to an int
hmm, definitely something something the logic there as if i try to just pass the static code, its fine
@mighty ledge why?
well, it's expecting an int and you're feeding it a string
what is expecting an integer? not the service
Yes the service is
that's what the error is saying
expected int for dictionary value @ data['code']
then why would the office_fan_off script work perfectly or simply taking out the if statement and putting 'code: 0xE4EB82' work?
np
Does anyone have any good examples/cookbook/tutorials on how to use templates in automations? I've been trying to figure out how to activate a switch based on a sensor and just can't quote get there.
i have good luck googling for what im trying to do and reading the docs
forums can be a good place to look too
Thanks. Yeah, googling helps. Just thought I'd ask if anyone had some good examples that are proven work, don't have tons of threads going back and forth, and possibly were tutorials or had lots of cases covered.
templates are just Jinja so there's nothing too specific there. First identify what you want to do, then see how you can do it in HA with templates
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
@dreamy sinew That is exactly what I was looking for. Thank you!
the docs get me pretty close unless i want to do something a little maybe out of the norm.
like right now i want to track how much time my hvac is on cooling, heating, or fan. i can easily do one of them, and i can do each individually with separate template/history sensors, but id love to find a way to combine it all with template
a 4th sensor adding them together?
if the history sensor could be templated for the state it cares about, or give it multiple states to track. but then it would need attributes or something to track each state's time
it was a fleeting thought i had while mowing last night 🙂
@thorny snow under his profile change the language to French.
@mighty hawk sounds like you want an automation, not a template.
Hi, not sure if this is the correct place. I have added a snmp sensor for uptime for my pfsense. Its coming in 1/100 seconds. But I want to show it as days, hours, minutes. I was able to get into minutes from this: '{{((value | int) / 6000) | int}}'
Templates can use some basic Python. Try something like this: https://stackoverflow.com/questions/748491/how-do-i-create-a-datetime-in-python-from-milliseconds
Wil datetime work? Uptime is showed like this 340994900, what means 39 Days 11 Hours 13 Minutes 15 Seconds
I do not have any date
@quiet current this is what I used to use:
{%- set time = value | int // 100 %}
{%- set minutes = ((time % 3600) // 60) %}
{%- set minutes = '{}min'.format(minutes) if minutes > 0 else '' %}
{%- set hours = ((time % 86400) // 3600) %}
{%- set hours = '{}hr '.format(hours) if hours > 0 else '' %}
{%- set days = (time // 86400) %}
{%- set days = '{}d '.format(days) if days > 0 else '' %}
{{ 'Less than 1 min' if time < 60 else days + hours + minutes }}
will have format 39d 11h 13m and omit seconds
I now use
- platform: snmp
host: !secret unifi_closet_ac_lite
name: Hall Closet AC Lite Uptime
baseoid: 1.3.6.1.2.1.1.3.0
value_template: >
{{ (now().timestamp() - (value | int / 100)) | timestamp_custom('%Y-%m-%dT%H:%M:%S.%f+00:00', False) }}
this will display in the UI as a 'relative' time. So it will only work on entity or entities cards
and your result will be 5 weeks ago instead of the exact timing
Ok, thanks, will give it a try. Still trying to get it to work
both templates work out of the box
just copy and paste template into your value temlate section and it will work.
Boom. Worked perfect. thanks 😄
np, which one did you use?
Used the first one
Quite new to this code thing, but getting my HA like I want step by step. Even if it feels like baby steps sometime 😛
I'm a template beginner, need help! I currently have this code: https://paste.ubuntu.com/p/NWW2Y8h6tF/ but i want to modify it to start my lights at full brightness. Where do I add the attribute for brightness?
`
action:
- service_template: "{% if is_state('group.bedroom_lights','off') %}light.turn_on{% else %}light.turn_off{% endif %}"
data:
entity_id: group.bedroom_lights
brightness: 105
mode: single
`
you can change something like this
@slate osprey
Thank you!
It didn't work for me. Config is valid but the automation doesn't do anything.
here is the updated code: https://paste.ubuntu.com/p/HZfmH5G4FB/
@slate osprey remove the space before light.turn_on
check the HA logs, it will tell you why
Here is the log! https://paste.ubuntu.com/p/qpRHR3vvhy/
extra keys not allowed @ data['brightness']
you can't add brightness to a light.turn_off service call
action:
- service: light.turn_on
data_template:
entity_id: group.bedroom_lights
brightness: "{{105 if is_state('group.bedroom_lights','off') else 0}}"
this should accomplish what you need
Gee what a crash course in templating haha
Maybe I bit off more than I can chew
Thanks Villhelm I'll try that!
It worked! I'm so proud of myself haha!
Thank you so much
I have this switch.bhyve_standard_program with this as an attribute start_times: 06:00. The template editor returns the value as ['06:00'] for {{ states.switch.bhyve_standard_program.attributes.start_times }}
@mighty ledge last time I used an automation without a template, I remember getting an error in HA about something related to not having all the cases covered. Let me test this real quick and see what I get.
What's my_pypi_package?
@hollow bramble I don't think you can use the light.turn_on service with a group entity. In fact, I'm sure I just saw someone else saying that in a recent post somewhere. Anyway, I think that would work if the service was changed to homeassistant.turn_on.
But, honestly, I haven't tried it myself, so I don't really know.
🤷 apparently it worked, but I don't know either. I was just working with what they had. If it still didn't work I would have suggested a light group
@mighty hawk that doesn't make sense
not sure what 'cases' wouldn't be covered. My guess is you were missing a key.
What's my_pypi_package?
@next coyote Anyone?
I'm having trouble setting up an integration
#integrations-archived is probably the place to be
No replies there unfortunately
@next coyote what's it in reference to
Unable to import component: No module named 'my_pypi_package'
that could be hundreds of different things
I used scaffold to build up the structure
that's a lazy programmer. They didn't change the name of the package they created
so, it literally could be anything
that's a template
you're supposed to use your code
object oriented language, that'd be you making a subclass from that specified class. Which will change depending on what you want to use. What are you trying to do? You should be asking these in the dev channel, but it seems like this might be a bit over your head?
How can I round a properly formatted time to the nearest hour?
that's a loaded question. We'd need to know the input format
object oriented language, that'd be you making a subclass from that specified class. Which will change depending on what you want to use. What are you trying to do? You should be asking these in the dev channel, but it seems like this might be a bit over your head?
@mighty ledge So sorry for that. I was new here and thought that all the channels are for devs.
Most channels here are for support, regardless of your background or programming knowledge. The ones that start with dev_ are for questions about the code itself - whether it's because you want to contribute or just because you're curious about how things work.
There's no need to apologise for posting in the wrong place. Now you know where to go for better help 🙂
There's no need to apologise for posting in the wrong place. Now you know where to go for better help 🙂
@ivory delta Thanks for the support 🙂
@mighty hawk posted a code wall, it is moved here --> https://paste.ubuntu.com/p/syGdRjGHbb/
I have an issue with an icon_template which doesn't work. I set up the if elif else but it doesn't show the correct icon. Search the forum and adjusted to the examples but it still doesn't work.
https://paste.ubuntu.com/p/DZ6h4wKXQS/
what i want to do is check how many persons are at home and adjust the icon to the number
I don’t think you can access entity states by just specifying the entity ID. I think what your looking for is something like states(‘sensor.personen_thuis’) | int > 2
I don’t think you can access entity states by just specifying the entity ID. I think what your looking for is something like
states(‘sensor.personen_thuis’) | int > 2
@radiant aspen that works! I thought it could done it both ways 🥴
thanks!
I have this template that adds 4 days to the base sensor, how can I round the time to the nearest hour?
{{ (as_timestamp(states('sensor.bhyve_front_central_zone_history')) + (4*24*3600)) | timestamp_custom('%a at %-I:%M %p', True) }}
@spiral imp it's painful
{% set t = as_timestamp(states('sensor.bhyve_front_central_zone_history')) %}
{% set dt = t % 3600 %}
{% set t = t - dt %}
{% set dt = (dt / 3600) | round(0) * 3600 %}
{{ (t + dt + 4*24*3600) | timestamp_custom('%a at %-I:%M %p', True) }}
haha, thanks. No wonder I couldn;t figure it out
I have a similar sensor that has an attribute frequency:. There seem to be sub-attributes. I am trying to extract the interval: attribute from the following.
{{ state_attr('switch.bhyve_standard_program', 'frequency') }} returns this:
{'type': 'interval', 'interval': 4, 'interval_start_time': '2020-07-27T12:00:00.000Z'}
{{ state_attr('switch.bhyve_standard_program', 'frequency')['interval'] }} likely
bingo! Thanks. Learned something new. I hadn't dealt with "sub-attributes" before
can sensor templates do pythony things like create a list and then index into that list dynamically?
i'm gonna guess no, but thought i would ask
yes
but you have to use namespace. And you can't use appending, you have to add lists together
{% set ns = namespace(my_list=[]) %}
{% for i in range(5) %}
{% set ns.my_list = ns.my_list + [ i ] %}
{% endfor %}
what about maps, which i just realized was my real question
well... what are you trying to do
eg
LOCK_NOTIFICATION = {
"1": "Manual Lock",
"2": "Manual Unlock",
"5": "Keypad Lock",
"6": "Keypad Unlock",
"11": "Lock Jammed",
"254": "Unknown Event",
}
then index into LOCK_NOTIFICATION with alarm_type
{%- set LOCK_NOTIFICATION = {
"1": "Manual Lock",
"2": "Manual Unlock",
"5": "Keypad Lock",
"6": "Keypad Unlock",
"11": "Lock Jammed",
"254": "Unknown Event",
} -%}
{{ LOCK_NOTIFICATION["1"] }}```
yah that
ooh, that looks very sexy. let me try that out. thanks!
the new ozw integration doesn't do the fancy string building for lock_status, so i'm trying to emulate it
i wasn't trying to dynamically create, i was trying to dynamically index into it 🙂
gotcha
I thought you wanted to create and add to list items, which is outside the scope but you can get there with work arounds
you can also do fun stuff like this
states('sensor.living_room_temperature')|float,
states('sensor.office_temperature')|float,
states('sensor.thermostat_temperature')|float
]
%}
{{(sensors|sum / sensors|reject("eq", 0.0)|list|length)|round(1)}}```
haha, impressive. i might just snip that and file it away 🙂
@dreamy sinew you can skip the | floats in the sensor list and add {{ sensors | map('float') | sum ...
XD
does this work?
{% set level = states('sensor.front_lock_alarm_level') | int %}
{%- set LOCK_NOTIFICATION = {
"1": "Manual Lock",
"2": "Manual Unlock",
"5": "Keypad Lock",
"6": "Keypad Unlock",
"11": "Lock Jammed",
"254": "Unknown Event",
} -%}
{{ LOCK_NOTIFICATION[{{level}}] }}
nope, get rid of the internal {{ }}
they aren't needed
also, your keys are not ints
aha, gotcha. thanks
{% set level = states('sensor.front_lock_alarm_level') %}
remove the int in that line
ok
your other option would be to keep the int in that line but change all your dictionary keys to ints 1: "Manual Lock"
ah, i see. just a type mismatch. i could go either way
id keep the strings
yeah
also, to be safe you should do this instead
actually, even better .get(level, level)
that will translate it if it matches and output it as is if it doesn't
that'll cover Uav/Unk from the state and also if it returns some other number for some reason
nice. thanks
there's still more to integrate, but it should follow the same pattern
Hi all. I have a BME280 in each room. These calculates the temperature, humidity and pressure. I think the windchill in the room must be a best value to check the confort of this room. Any of you have the formula to check this inside a room? In Internet I only find the outdoor formula that counts the wind velocity.
@honest mauve We'll need more of an explanation. Also, what have you tried?
@echo dew use the outside formula with a wind velocity of zero.
@mighty ledge you are a funny guy. youre the master of templates and while I checked out your repo i can hardly find used templates (maybe I just not found them 😛 )
Lol, i don't use them much 😉
There are a few files that have them, but for the most part, i've moved away from complex jinja. Most of my stuff is appdeamon
I do have 4 coronavirus templates that are complex.
look in sensor.yaml for most of it
Also, check the sensor.yaml history. It has things i've removed.
nice nice, but already seeing an issue when the responses are bigger then 255(?) letters
But been a time since I last used such a monster API
😄 Transition from Mercurial to Git
Yeah, I still use Mercurial. But I've been transiting to Git with GitKracken
I used tortoiseHG for most of my previous work
Hi all...so I have a vacuum.xiaomi_vacuum_cleaner entity with a cleaned_area attribute (which is expressed in square meters).
I'd like to set up a value template to convert the cleaned_area to square feet (rounded to the nearest whole number). So far I know I need to multiply the cleaned_area value by 10.76391 to get the square feet, but I can't figure out the syntax to make that calculation and the rounding happen. Thanks for your help!
{{ (state_attr('vacuum.xiaomi_vacuum_cleaner', 'cleaned_area') * 10.76391)|round(0) }}
That will work if the attribute is a number. If it's a string representation of a number, then:
{{ (state_attr('vacuum.xiaomi_vacuum_cleaner', 'cleaned_area')|float * 10.76391)|round(0) }}
Thanks @chrome temple!
been searching on and off for a couple weeks, reddit/forums/other since i got my zwave thermostat (GoControl) for hints on setting the fan mode, lovelace thermostat doesn't have the fan button, but the thermostat does allow control of it, and i can manually set it if use the lovelace edit screen, any suggestions what terms to search for or if there are any guides out there ?
Not sure what you mean by "i can manually set it if use the lovelace edit screen." Please go to the STATES tab of the Developer Tools page. Find the climate entity that corresponds to that thermostat. What do you see for its attributes? Specifically supported_features, fan_mode & fan_modes?
by "manuall set it" i mean in the overview tab, config UI, when edit the default lovelace icon i can set the fan to on/off, sorry, can't paste screenshot here, in developer tools supported_features: 75 ```fan_modes:
- Auto Low
- On Low```
You can call the climate.set_fan_mode serivce (https://www.home-assistant.io/integrations/climate/#service-climateset_fan_mode). The allowable values for the fan_mode parameter are the values you see in the fan_modes attribute.
Hi all, long story short - learned a big lesson... My SD card bit the dust the other day. Lost everything - backups included - Decided to come back with a Linux PC running HA and I'm glad. my issue is I had some ESP8266 with temp and motion sensors. They are back running but is there a way to read the installed config? I used ESPHome to initially set them up and I want to use that setup to make some new ones. They do not show up in ESPHome but do in HA for what they were set up to do
awesome, thanks for the pointer on that, was mostly curious what caused the fan button not to be displayed on the card https://www.home-assistant.io/lovelace/thermostat/ my card has a power icon where the fan icon is in that picture
hadn't downloaded backups anywhere?
@eternal basalt did you click on the three dots in the upper-right hand corner? For my Nest that brings up the "more info" window, and it has a drop-down for fan mode.
Mine also has a power icon. I have no idea what it does, and I'm afraid to click on it. There's no tool tip, and the doc page doesn't say either.
ya, that brings up advanced options and that's where i can change the fan mode, was just looking to include it in the main card like the tutorial shows
the power button is the same as if you hit off on the thermostat, as in heat/cool/off
Ah, ok, I guess that makes sense. I wonder what the first icon means??? Must mean away mode or something.
BTW, you said "config UI, when edit the default lovelace icon." Just to be clear, I mean the three little dots in the thermostat card, not going off to some UI config page.
Dear all, I have template sensor:
{{ (( as_timestamp(now()) - (states.input_datetime.nachalo.attributes.timestamp)) / 86400 ) | round(2) }}
the value is correct only after HA restarted, and the value is not updating at all, only after HA restart. What should be changed/updated ? It looks like as_timestamp(now()) returns the permanent value
@serene merlin posted a code wall, it is moved here --> https://paste.ubuntu.com/p/4vPv6hfB2Y/
Hi All
A question to gurus:
is there a way to pass on a 'calling' entity id into the the script? Like {trigger.entity.id} section example above?
A script isn't triggered, so not the way you've done it. If you're calling a script from an automation, the automation would have access to the trigger object and could pass it in as a parameter.
@ivory delta thank you. But how about a cover? I have a bunch of covers and I would love to avoid a need to create open/close/stop scripts for each of them. Is there a way to make the code neater?
I found trigger.entity_id could I use that like:
script: open_kitchen_blind1: sequence: - service: esphome.roller_blinds_controller_control_stepper data_template: target: "{{state_attr('trigger.entity_id', 'max') | int}}"
also, i'm struggling a bit with the trigger.to_state part where I need to do some math. I'm doing this:
data_template: target: '{{ ( trigger.to_state.state | int ) * ( state_attr('input_number.kitchen_blinds_extreme_positions', 'max') / 100 | int )}}'
but I get errors than 'colon' is missing after /100 part
You don't have access to the trigger object in a script...
And you need mixed quotes.
oh, i see.. that sucks 😦 thank you very much @ivory delta
It doesn't suck. A script can only do what it's told. You're expected to provide all the necessary information.
How do you call these scripts?
script.open_kitchen_blind1
script.close_kitchen_blind1
script.stop_kitchen_blind1
script.open_kitchen_blind2
...
@ivory delta where do I need mixed quotes? I'm sorry
i didn't mean to be annoying, sorry, coming here was my last resort after hours of research
You're not being annoying.
The mixed quotes thing is because you're starting your template with a ' and then using a ' within the template. When HA reads the template, it thinks the second ' is the end and everything after that is garbage.
If you're using ' inside your template, surround your template with " instead.
And I know what your entity names will look like. Where are you using those?
If it's from a button on the frontend, the button will need to tell it the entity - buttons aren't triggers.
If it's from an automation, there is a trigger and you can dynamically pass in an entity ID. But you still wouldn't have the logic for trigger.xxxxx in the script, that would move to the automation.
@ivory delta I think I got you confused somewhat, sorry. So scripts and the trigger.to_state part are 2 different things.
- I'm using scripts to control window blinds positions from template cover and since I have a few of those covers I was hoping I could avoid coding multiple scripts for each.
- I'm using 2 input_numbers: 1 to store min and max values for the position of the blind and the other one (a slider) to control their position. The position is controlled by automation that sends value of required position to esphome like so:
`automation:
- alias: Send Kitchen Blind 1 Position to ESP
trigger:
platform: state
entity_id: input_number.kitchen_blind1_stepper_control
action:- service: esphome.roller_blinds_controller_control_stepper
data_template:
target: {{ trigger.to_state.state | int}}`
So since the since input_number.kitchen_blind1_stepper_control is set to values from 0% to 100% I need to convert the % value into actual steps by '{{ trigger.to_state.state | int * ( state_attr('input_number.kitchen_blinds_extreme_positions', 'max') / 100 | int )}}' and that's where I ran into 'trigger.to_state' syntax problems (i think)
- service: esphome.roller_blinds_controller_control_stepper
problem also is that it looks like dev tools don't validate trigger.XX states/entities (or at least I couldn't make it work) so I'm in the dark
You can still test most of your template in
> Templates. Just replace the first part (trigger.to_state.state) with a reference to your input_number instead.
They mean the same thing. The information just gets plugged into your template from a different source.
right.. I thought of that but the difference was that in case of actual input_number value states platform will be used while I thought that trigger.XX is different
maybe mistakenly.. hence I ended up here 🙂
states('trigger.to_state') | int does the job but I wasn't sure at all it's the same thing
Well to be honest, you could probably use states('input_sensor.your_sensor_name') instead of using the trigger in your automation and it'd still work the same. I doubt there's even a difference in performance. It's just handy to use the trigger object so you can 'see' where it comes from.
From what I understand with latest update to Automations I can achieve the same thing for all covers with just 1 automation though?
You could probably do it with the old automations too 😄 But that's a question for #automations-archived
Once you're happy with your template, take it over there to finish the automation itself.
This whole process of reworking this was triggered by this automations update if i'm honest 😅
oh yeah? lol, okay 😃
@ivory delta I'm sorry, just to confirm. So would target: {{ trigger.to_state.state | int}} do the same thing as target: '{{ states('trigger.to_state') | int ?
I don't think that's valid, no. You can try it...
But like I said, if you're happy that your template works and converts from your percentage to an integer, the rest of your problem is for #automations-archived.
damn.. I mean this is so silly.. sigh.. i hate feeling dumb like that
dev tools validate this just now target: "{{ 'trigger.to_state' | int * (state_attr('input_number.kitchen_blinds_extreme_positions', 'max') / 100 | int )}}"
only '' were missing around trigger.to_state.. jeez
@ivory delta thank you so much for all your help and taking time to explain all this to me ❤️
Hi guys, i have this automation for my window https://paste.ubuntu.com/p/36MNXRP76m/ for a few days, when I close the window and the thermostat should activate in hot and not cold mode as it should if the boolean is on, could you help me understand what is wrong?
maybe a problem with the template?
You haven't told us what's wrong yet. What happens?
when i close the window and the boolean is on it should turn on the thermostat in cool mode
That's what should happen. What actually happens?
set the termostat in heat mode
Ok. And you posted 3 automations in that link. Which one is the problem?
I have also published all the automations to make the operation understand, however I think the problem is here: https://paste.ubuntu.com/p/tRR8jGb9QT/
Well first check your template at
> Templates. Does it return 'cool' or 'heat'?
your template is fine, seems like your automation chain is overly complicated. Also, nothing points to you 'closing the window' in any of those automations.
the window is a switch
ok, is the window on when open or closed
switch on = window on
it's odd that it's a switch and not a binary_sensor
i try the automation and works good
It's still odd 😄
Switches are things you control. Sensors are things that provide information.
yes, i make this choise because with binary_sensor when i restart HA don't have the retain function
and now i use a sensor 433 with espurna
first thing I notice is that when the window is open you turn off the automation that does everything
yes
If you turn it off, it won't run again...
to prevent it from being activated if the thermostat is off
You normally shouldn't turn automations on/off. It's enough to use the triggers and conditions to decide if the actions should run.
but that's what doesn't make sense, if you just open the window, you turn off the other automation. Making it's trigger 100% pointless and it will never fire.
your trigger in the other automation looks for the switch being on for 45 seconds, but you just turned that automation off.
it will never fire.
ever.
and that's what starts the 3rd automation.
so, you have flawed logic.
we had developed these automations with a channel moderator that I don't remember the name now, but until a few days ago everything worked perfectly.
that doesn't mean the logic is correct.
Turning off automations = bad. If you can't ensure they're turned back on properly, you have problems like this.
i see
you can turn them on/off all you want, you just have to understand when an automation is off, it's off. When you turn it off, it cancels currently executing actions.
so the first automation it is not necessary
All you want to do is turn on cool when you shut the window? And you only want to run it once if it's set to heat?
the automation is designed to turn off the air conditioner if the window is open, if the last mode is cold, when you close the window you must turn the thermostat back on and set it to cold, otherwise hot. If the thermostat is off, no automation must be activated.
since the thermostat does not remember if it was hot or cold or rather it always sets it hot, I had implemented a bolean to remedy this problem.
as I said everything worked perfectly, after updating to the latest version I had this problem
Yes because actions cancel now
Add a condition to the automations checking the state of the thermostat.
or input boolean if that's what stores the on/off
i have this is action
and in condition when the window is open
but it seems that the automation does not put in the proper state, it only turns on the thermostat in heating mode
even if the bolean is on to remember the cooling state
you'll probably have to rewrite your automations with your goal in mind, and with the intention of the automation being active at all times
Can you help me on this? 😊
Nope, you gotta learn on your own. It seems like someone already fed you the answer and you're unable to debug it. You should learn how to do this yourself so you can fix it.
Ok thanks
Does anybody know how to get the delay_time from the alarm_control_panel to use in an automation? I have this now states(alarm_control_panel.armed_away.delay_time) but the template editor says alarm_control_panel is undefined. If i look at the states it's clearly there tho.🤷♂️
so...I just had to move the sequence of actions, because it turned off automation before it did the important things.
now all works good
evidently in the previous version it didn't matter
Yes that’s new in this version. When you turn off an automation it cancels the actions currently running
Does anybody know how to get the delay_time from the alarm_control_panel to use in an automation? I have this now
states(alarm_control_panel.armed_away.delay_time)but the template editor says alarm_control_panel is undefined. If i look at the states it's clearly there tho.🤷♂️
@keen crater is delay_time in the attributes?
You need quotes around entity names inside states()
Like so: message: "Alarm active in {{ states('alarm_control_panel.armed_away.delay_time') }} Seconds"
still doesnt work 😦
also tried it like this: 'Alarm active in {{ states("alarm_control_panel.armed_away.delay_time") }} Seconds'
How do I use MQTT topics to satisfy the actions in a cover template? I have an MQTT garage door that I can read and change the state with successfully from HA. I was trying to hierarchically add a platform:mqtt under the cover template in my yaml, but that seems to be the wrong way to go about it. Do I need to define the mqtt somewhere else and use reference that somehow in the cover template?
seems like you want this? https://www.home-assistant.io/integrations/cover.mqtt/
I think that is exactly what i was looking for, thank you!
Can someone help figure out why I am not getting the expected result? I wrote up what all i'm doing here: https://pastebin.com/7Jpy8rgv
You have an array with one entry, a string.
The value inside the double quotes isn't an object/dictionary.
Unless I'm being dense. It's been known to happen.
Yeah... this template complains that 'str object' has no attribute 'get':
{{ test[0].get('datetime') }}
Whatever you're doing to generate test is definitely making an array of strings, @brisk temple
ok thanks, i'll work on it
Why |map('lower')? That's definitely converting the dictionary into a string.
map attribute didn't give me all the line i wanted
you'd want to use | map(attribute='datetime') or not use map at all.
not using map at all would result in {{ test[0].datetime }} working
{% set test = (state_attr('weather.openweathermap', 'forecast') | selectattr('datetime', '>=', start) | selectattr('datetime','<=', end) | list)%}
{{ test[0] }}
{{ test[0].datetime }}
hey i'm having an issue with using a template in an automation for the first time and I am wondering if someone can point me in the correct direction. what have I done wrong here?
...
action:
- data:
brightness_pct: >
{% if (now().hour) > 20 %} 70
{% elif (now().hour) < 7 %} 50
{% else %} 100
{% endif %}
color_name: >
{% if (now().hour) > 20 %}'slategray'
{% elif (now().hour) < 6 %}'coral'
{% else %}'palegoldenrod'
{% endif %}
entity_id: light.2nd_floor_2
service: light.turn_on
Np, easy fix
figured it was going to be a "we get this question a lot" situation
Haha there's a handy bot command usually
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
Helps if I use the right one
Hey guys, im trying to figure out how to get a template to output the time a entity has been in a certain state
specificaly:
{{ states('device_tracker.xxx') }}
Would like to get the output in minutes or hours this entity has been home
any tips?
Use the search function, @lapis quarry 🙂
https://discordapp.com/channels/330944238910963714/672220450977349653/734765609665036338
And from there, you just need to use some strftime magic to get it looking how you want.
@lapis quarry you can't with just a template
{{ states.device_tracker.keyring06a.state }} for {{ (as_timestamp(now()) - as_timestamp(states.device_tracker.keyring06a.last_changed) ) | round(0) }}
unless you are specifically looking for the last state only.
Then you can.
But if you are looking for the 'total time on today', you'll need to use the history stats integration
since last change is fine
Ok, then the first order of business is to integrate sensor.time, date_time integration.
now just strugling to convert it to minutes as outpuit is in seconds 😅
without it, your sensor will not update properly.
have sensor time allredy
ok, what format are you expecting after for?
Also, where are you placing this in the UI or is it for a message
its for a message
{{ states.device_tracker.keyring06a.state }} for {{ ((as_timestamp(now()) - as_timestamp(states.device_tracker.keyring06a.last_changed) ) /60)| round(0) }} this is working
its for a notification
yeah that would be seconds
this is what i have ended up with:
- service: notify.notifier_name
data_template:
title: >
{{ states('input_text.house_number') }}
message: >
No Keyring or Phone Detected in Room 07 for
{% if (as_timestamp(now()) - as_timestamp(states.group.room07.last_changed)) | round(0) < 60 %}
{{ (as_timestamp(now()) - as_timestamp(states.group.room07.last_changed)) | round(0) }} seconds
{% elif (as_timestamp(now()) - as_timestamp(states.group.room07.last_changed)) | round(0) < 3600 %}
{{ ((as_timestamp(now()) - as_timestamp(states.group.room07.last_changed) ) /60)| round(0) }} minutes
{% elif (as_timestamp(now()) - as_timestamp(states.group.room07.last_changed)) | round(0) > 3600 %}
{{ ((as_timestamp(now()) - as_timestamp(states.group.room07.last_changed) ) /3600)| round(0) }} hours
{% endif %}
why not just use the last_changed secondary info?
or device_class: timestamp for a sensor
because I barelly know what im doing 😅
took me 3 or 4 hrs to figure this out
😩
im sure they are better ways but at least it seems to work
No, you did it the right way, I keep thinking you want this as a sensor. Not in a message.
{% if ts_delta < 60 %}
{{ ts_delta }} seconds
{% elif ts_delta < 3600 %}
{{ (ts_delta /60)| round(0) }} minutes
{% elif ts_delta > 3600 %}
{{ (ts_delta /3600)| round(0) }} hours
{% endif %}```
change your entity back and you're good
Lol, I was just typing that up but got side tracked by work
lol
{% if ts_delta < 60 %} {{ ts_delta }} seconds {% elif ts_delta < 3600 %} {{ (ts_delta /60)| round(0) }} minutes {% elif ts_delta > 3600 %} {{ (ts_delta /3600)| round(0) }} hours {% endif %}``` @dreamy sinew 👍
yes
ok cool
if you want it to be accessible elsewhere you need to make a sensor like petro suggested
no need, just wanted to confirm I can use the same name in diferent templates
👍
apologies for the wrong channel, i can never seem to get it quite right
APIs are fun. Anyone know how to parse out specific words from grabbing JSON - eg, parsing out "Round Up" and then moving on to grab the next option in the array?
https://paste.ubuntu.com/p/ckWcH5VCjX/
x-post for prosperity
I've tried some IF statements but they never seem to take
so you're wanting the roundUp property for each?
Not quite - I want to not parse anything with the description of Round Up "description": "Round Up",, and instead move on to other transactions
what do you want the final output to be?
ignore the one with Round Up and move on to the following transaction
I... don't think it's quite possible because I've hardlinked the array numbers with [0] etc
are there n number of transactions at any given moment?
no, but I can make that happen
integer
The number of records to return in each page.
e.g. ?page[size]=30```
just need to add that to my query
i have now limited it to 5 transactions on a query (which honestly makes more sense as I only have 5 transactions being required)
[x['attributes']['amount']['value'] for x in d['data'] if not x['attributes']['roundUp']]
['0.10', '0.31']
I just tried something like the following, but it states 'Round Up' as the friendly name :p https://paste.ubuntu.com/p/568cqBTG7k/
oh boy
but that would only give you things you can use in one sensor
unfortunately it also wouldn't work because the Round Up value changes depending on purchases
aka it could be any value from 0.01 to 0.99
this drops out anything that has the roundUp dict populated
where should this go? sorry
eh, you can only get a sum
it really depends on what you want the ultimate output to be
do you want multiple sensors here?
or do you want a total?
Yeah, I currently have 5x most recent transactions
ok and what do you want the value of that sensor to be?
amount unless roundup is populated?
I'm showing each transaction as a sensor, so the value_template corresponds to the amount spent and the friendly_name_template is the description of the transaction
so if description = "Round Up", move on to the next transaction
i understand that this is like jamming a square in a round hole, so I understand if I should bugger off and figure it out myself/make a custom integration
oh i get it
I can attach a photo if that will make more sense with what I currently have going on
my if statement inside of the templates created 'Round Up', instead of ignoring it and moving on
ok, here's this
{{parsed}}```
replace rest['data'] with states.sensor.up_transactions.attributes["data"]
add that to the top of each template and all the roundups will be dropped
proceed as you have with your indexing
above friendly_name_template?
lemme give it a whack ty
where should this belong? replace anything? above the friendly?
oh i get it, im dumb
omg
you absolute legend
i could kiss you, ive spent a couple days on and off trying to sort this and it keeps going to the back of the queue
buy you a beer or anything like that mate?
there might be something you could do on the rest sensor to pre-reject but i'm less handy there
all good man, just pass it forward
unfortunately its not my rest api - it's direct from my bank
I can definitely raise an issue on their github though
oh boy, here we go deeper
i just haven't touched it much
HA is very similar to a hydra
you think it's good and you're fine to leave it alone but then you think "ah wait, that could be done cleaner"
ehh looks like you can't there unfortunately. you can template the value but not the json attribs
it's all good - it worked somewhat but you've basically given me the keys and I can nut the rest out
that's about as clean as i can get it for now
nah it's all good! I never even found anything about set parsed in my searches so that's opened pandoras box for me
only way to make it cleaner would be to add another template sensor in the middle to do the parsing but that might get ugly within HA
since you still need the list
realistically, i should do an integration at this point
could be a good project if you're handy with python
somewhat - jack of all trades, master of none and all that
making an integration that does that would be super easy.
its a bit of a lift to get started but you have a lot more control
well, it is the weekend now, so i mean, there's nothing really stopping me :p
just modify whatever's currently creating the sensor you're getting now
make it a custom integration and you're good to go, just give it a new name
rad, i'll have to take a geeze. appreciate the help phnx!
thanks petro :)
oh my god, im dumb. it DOES work perfectly - I just didnt realise Uber took a double payment today
🤦♂️
@lapis quarry posted a code wall, it is moved here --> https://paste.ubuntu.com/p/2PK23BKRdc/
a wall of code lol
- service: notify.notifier_name
data_template:
title: >
xxx
message: >
No Keyring or Phone Detected in Room 07 for
{% set ts_delta = (as_timestamp(now()) - as_timestamp(states.group.room07.last_changed))|round %}
{% if ts_delta < 60 %}
{{ ts_delta }} seconds
{% elif ts_delta < 3600 %}
{{ (ts_delta /60)| round(0) }} minutes
{% elif ts_delta > 3600 %}
{{ (ts_delta /3600)| round(1) }} hours
{% endif %}
Outputs this:
No Keyring or Phone Detected in Room 07 for
27 minutes
Could you tell me what I need to do to join all the message so there is no spacing and the output is all 1 line?
do i need to write it all in one line? makes it dificult to read:
No Keyring or Phone Detected in Room 07 for{% set ts_delta = (as_timestamp(now()) - as_timestamp(states.group.room07.last_changed))|round %}{% if ts_delta < 60 %} {{ ts_delta }} seconds {% elif ts_delta < 3600 %} {{ (ts_delta /60)| round(0) }} minutes {% elif ts_delta > 3600 %}{{ (ts_delta /3600)| round(1) }} hours {% endif %}
this way it works, i guess I can write a message any other way?
{{ (ts_delta /3600)| round(1) }} hours
{% endif %}
{% if ts_delta < 60 %}
{{ ts_delta }} seconds
{%endif%}
{% if ts_delta < 3600 %}
{{ (ts_delta /60)| round(0) }} minutes
{%endif%}```
if you want all 3
oooooh wait, i see
sec
{%- set ts_delta = (as_timestamp(now()) - as_timestamp(states.binary_sensor.living_room_occupancy.last_changed))|round %}
{%- if ts_delta < 60 -%}
{{ " {}".format(ts_delta) }} seconds
{%- elif ts_delta < 3600 -%}
{{ " {}".format((ts_delta /60)| round(0)) }} minutes
{%- elif ts_delta > 3600 -%}
{{ " {}".format((ts_delta /3600)| round(1)) }} hours
{% endif %}```
try that
Error rendering template: TemplateSyntaxError: unexpected '}', expected ')'
check your copy paste, this is working in the template tester
also make sure you swap your entity back
the - remove white space
needed to add the .format() statements to add the space you want back in
is there a way to have rejectattr('eq', 'example removed') read from a list at the top? rather than having multiple 'example removed's?
ive been trawling the Jinga documentation and cant find anything
what's more pretty in ur opinion
{% for json in value_json.metrics if json.tags.model == "SAMSUNG HM321HI" %} {{json.fields.temp_c }} {% endfor %}
or
{{ (value_json.metrics|selectattr('tags.model', 'eq', 'SAMSUNG HM321HI')|first).fields.temp_c }}
The second one. Not only is it a single line, it reads in order too.
And I wouldn't call either 'pretty'. The second is more elegant.
is there a way to put something like vars: list_of_dicts: into home assistant for a sensor to read?
What are you trying to achieve?
I actually have my code on git now! is it ok to link to that to show an example?
I tried merging all the rejectattr's like so: https://hastebin.com/cikisufubu.bash
but it doesnt recognise them all and seems to just ignore all of them
What's the full config? That doesn't show the type of integration you're creating.
Okay. So you're trying to extract information from the REST sensor to make other sensors?
To answer your initial question, no, I don't think you can do that. You can only define things in YAML that are an integration or HA won't validate it.
that's it, everything works great, im just trying to make the one line with rejectattr look a little cleaner and easier for other people to add exclusions
i thought so. i should make an integration, but it's terrifying so i'm trying as much as i can in a sensor.yaml first :p
I'll be honest, I'm not great with templates... others might be able to suggest a cleaner way but your current approach might be as good as it gets.
that's all good! I appreciate the lookin' anyhow. Phnx seems to be the God of Templates
@merry flame
{% set parsed = states.sensor.up_transactions.attributes["data"] | rejectattr('attributes.description', 'in',['Round Up', 'Interest', 'Cover from rent n bills', 'Cover to Spending']) | list %}
and technically, you can map each one.
{% set parsed = states.sensor.up_transactions.attributes["data"] | rejectattr('attributes.description', 'in',['Round Up', 'Interest', 'Cover from rent n bills', 'Cover to Spending']) | map(attribute='attributes.description') | list %}
then the result would be
{{ parsed[0] }}
but you'd have to make sure to map properly because some of the values you're trying to get would need | map(attribute='attributes.amount.value')
and, you'd probably want to add safety to the templates to avoid errors at startup:
friendly_name_template: >
{% set parsed = state_attr('sensor.up_transactions', 'data') %}
{% set filter = ['Round Up', 'Interest', 'Cover from rent n bills', 'Cover to Spending'] %}
{% set parsed = parsed | rejectattr('attributes.description', 'in', filter) | list %}
{% set descriptions = parsed | map(attribute='attributes.description') %}
{{ descriptions[0] }}
value_template: >
{% set parsed = state_attr('sensor.up_transactions', 'data') %}
{% set filter = ['Round Up', 'Interest', 'Cover from rent n bills', 'Cover to Spending'] %}
{% set parsed = parsed | rejectattr('attributes.description', 'in', filter) | list %}
{% set values = parsed | map(attribute='attributes.amount.value') %}
{{ values[0] }}
sadly the last one doesn't work, first does though!
Any chance using something like I mentioned above is possible in sensors? list_of_dicts
actually, I may not need to if I can use beginning of phrases, such as "Cover from", "Cover to" etc
hahaha damn, so earlier in the day when i tried https://hastebin.com/cikisufubu.bash, i just didnt put spaces before/after certain parts
if i can use wildcards, that would be great
Hopefully correct area, but just wondering if anyone knows if you can you have multiple universal media players? I'm guessing I've messed up the config, but I have two configured, and only the second one seems to stick?
Media players are #integrations-archived
Templates are all that curly brace nonsense you can see up above.
Sorry, just figured because the config does have templates in it, might be relevant. will pop over there.. thanks!
If your problem is the templates within your config, someone here can help out. You'll want to check that your config in general is correct first though.
thanks. I've probably stuffed the YAML
I'm trying to setup a template binary sensor but I would like to have it on a "set/reset" behavior, is that possible ? I tried to use the state of the sensor itself in the value_template but that generates an error on restart.
The way it would work would be to use 2 automations to set the binary_sensor ON and OFF. I am hoping that a cleaner way to accomplish this exists.
Oh I found a mistake in my template, you can use the state of the sensor itself to accomplish a "set/reset" function as in "set_trigger or sensor_itself and not reset_trigger"
Hi all, I'm experiencing a behavior I don't understand
if I put the "{{ states('binary_sensor.updater') or (states('sensor.custom_hacs_pending_updates') > 0) }}" in
->Template it shows "on"
but creating a binary_sensor with the same code it shows "off"
.share the config of your sensor
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
here it is: https://pastebin.com/KjTPXWtW
Your template evaluates to "on" when binary_sensor.updater is on.
and "off", otherwise.
Both of which is not True and thus sets the binary_sensor to off
You probably want {{ is_state('binary_sensor.updater', 'on') or (states(...) > 0) }}
It's extra annoying because on IS True in yaml, but not in jinja.
exactly
is there a way that i can do this in an automation data template?
{{ (homeassistant.util.convert.color_temperature_to_hs(3000)) }}
no
dang. ok
are you just trying to set a color for a light?
nah but I'm (probably obviously) overcomplicating something, gonna fix that
thanks
Hi, I'm looking for how to create an alert using Node Red. In this case I have a Tesla PowerBall, if the power grid goes off, I would like it to turn on a red light bulb in my room, but when the power returns, the light bulb returns to its previous state. That state can be off or on with the color and brightness that have it before.
#node-red-archived is a better channel
Quick help/scan of my sensors.yaml file? I'm 'trying' to tidy up by adding a secrets.yaml and pulling the sensors into a config.yaml. I've done this and syntax seems to pass, but my influxdb sensors have disappeared from frontend - so clearly something daft I'm doing. Would someone mind scanning this file and letting me know if there's something wrong here? https://paste.ubuntu.com/p/7v5NKkVrXp/
Not completely sure this is the right place to ask, but I'm having trouble with a for loop in a template I'm trying to use inside a Lovelace markdown card. I have a bunch of sensors for my recent bank transactions, where the amount is the state and additional details like the time, description etc are state attributes. My goal is to loop through these sensors and print out the relevant attributes.
{% for transaction in expand('group.up_transactions') -%}
{{ transaction.name }} is ${{transaction.state}} and
{% endfor %}
This template works fine for the name and state, however I can't figure out how to get the other attributes. I thought something like state_attr(transaction,"description") would work, but it breaks the template. {{ state_attr('sensor.up_transaction_1','description') }} displays the attribute as expected, though.
I need some help in creating a switch that, when switched on, sets the color and brightness of a lamp to something specific and when switched off reverts to the color/brightness set earlier and turns off the lamp
It sounds like you want a script for the 'on' action. The script would capture a scene, then set the new states. The 'off' action could then just restore that scene.
ok, so a scene inside a script. Scripts and scenes is new territory for me 😅
This is where I've gotten to, not sure whether it can work or not
https://paste.ubuntu.com/p/vfpg3sJDKM/
Well what happens when you try?
The RGB state attr apparently has braces in it
I'm guessing its because of the commas
{{ state_attr('light.tv_lamp','rgb_color') }}
returns (0, 0, 255), but states shows
rgb_color: 0, 0, 255
Yeah, this is why you'll probably need to record/set scenes. RGB is a tuple, not a string.
oh
Hi guys, I'm trying to round an output in my template, but it doesnt do anything. Maybe someone of you got a hint for me? 1
"{{ states.sensor.fritz_netmonitor.attributes.uptime | int / 3600 | round(2) }}" The output is "20.25111111111111", no matter what number I'm inserting in round(??)
Order of operations. You're rounding 3600.
"{{ (states.sensor.fritz_netmonitor.attributes.uptime | int / 3600) | round(2) }}"
"{{ (states.sensor.fritz_netmonitor.attributes.uptime | int / 3600) | round(2) }}"
Snap 😄
😅
awesome, thx guys
Yeah, this is why you'll probably need to record/set scenes. RGB is a tuple, not a string.
Can you walk me through it mono? I've set a scene with the light in it.
Is there a way to display the time like this: 1d 2h 3m for this template? Its the uptime of my Internet Connection. Now its just displayed in Hours
I don't know much about scenes, sorry. Check the docs for how to capture one on the fly.
Em_Cee - you'll probably want to use strftime. There's plenty of guides on the internet for it, it's just a Python function that takes a time and spits it out in another format.
You can try searching the Discord for examples too.
thx m8
@thorny snow very simple example
import time
hours = time.time()
days = hours / 24
print(days)
states.sensor.fritz_netmonitor.attributes.uptime is hours?
seconds
oh that's easy
import time
seconds = time.time()
days = seconds / 60 / 60 / 24
print(days)
where do i insert the code?
that code isn't exactly to paste it, it's to give you an idea on how to accomplish what you wanted in python
hello :)
I couldn't find any doc on selectattr, the only mention i found was in the 'expand()' section of the template doc, but nothing else.
I can't quite make it work, does someone have a link ?
i can see it's a jinja filter (https://jinja.palletsprojects.com/en/2.11.x/templates/#selectattr) but it dosn't list what kind of test can be done
i have try a lot of thing to work around my issue, but homeassistant jinja limit the append function, and i can't set a variable in a for loop to retreive it afterward ...
i can't find how to simply make {{ expand('group.battery') | selectattr('state', 'lt', '15') | list | count > 0 }} work, because my state return an string but i need an int to compare number :(
I have a rather complicated sensor template that hits someone's api endpoint. It updates every 10 seconds. The problem is that sometimes their api returns a value that is inaccurate resulting in a sensor value of 0. This happens anywhere from about once an hour on the best of circumstances or like once every 2 minutes on the worst of times. This leads to an inaccurate sensor value.
Long story short, is there a way for me to make the template sensor skip updating the value if value is not desired (0 in this case)?
Depends. Can you detect it logically?
I don't think you can skip but you could probably default it somehow
could I default it to its previous state?
Not sure, probably not there
Could have an automation update an input value whenever the sensor changes and pull from that input value
great idea, working on that now.
@lapis quarry posted a code wall, it is moved here --> https://paste.ubuntu.com/p/KxvYps8Bnn/
I was using 8 automations before to do this, if i can do it in 1 template it would be awesome
You can simplify further
Just get rid of to the to: line and use a single trigger block. It will trigger on both
but then I can do this for the off :
for:
seconds: 20
True
Also, the last lines are wrong. Get rid of the quotes and use trigger.to_state.state, not ‘name’
something like this?
- data_template:
dev_id: >
{{ trigger.to_state.entity_id }}
location_name: >
{% if trigger.to_state.state == ‘on’ -%}
home
{%- elif trigger.to_state.state == ‘off’ -%}
not_home
{%- endif %}
service: device_tracker.see
like that?
ok think i got you, like that should work?
You probably want trigger.to_state.entity_id for dev_id
Or maybe not. Maybe ‘name’ is what you want
Try it and see
i just want motionlr01x from binary_sensor.motionlr01a
Right
gues name is what i want?
let me try it and see
Invalid config for [automation]: invalid template (TemplateSyntaxError: unexpected char '‘' at 32) for dictionary value @ data['action'][0]['data_template']['location_name']. Got None. (See /config/configuration.yaml, line 45).
need to hit the bed, 3am allready, will give it another shot tomorow 🥱
@lapis quarry you copied that from the forums? It has the invalid quote type. Replace all your quotes with the non-fancy quotes
I could really use some help here with mqtt fans and openmqttgateway. The topic is the same for all fans, i simply have different values to check. Also, not 100% sure how i should be handling payload_on as its pretty much that if any of the low, medium, or high speeds are set, then its on. And of course, none of the speeds even show up in the entity ui for each fan. When I do use a remote to set it to low, it is correctly the fan as off or on though. https://hastebin.com/ujeyetexip.bash
I'm pulling start times via an API and unfortunately it's coming in as Eastern Time (I'm in Mountain, which is two hours behind) and having a really hard time finding how to subtract the 120 minutes from either the time itself or a timestamp.
tcm_starttime:
friendly_name: Start Time
value_template: '{{ states.sensor.tcm.attributes["time"] }}'
tcm_starttimestamp:
friendly_name: Start Timestamp
value_template: '{{ states.sensor.tcm.attributes["timestamp"] }}'
Any pointers?
The attributes are coming across as:
time: '08:00 pm'
timestamp: '2020-08-02T20:00:00'
Is it not returning the timezone in the timestamp?
It's not...
That blows
I agree. And there's no way to specify the timezone in the call...
You can add one but you're going to have to touch it every 6 months for dst adjustments
That wouldn't be too terrible.
Is it an API that you have to use an account for?
No. It's Turner Classic Movies' free one.
Lame
Maybe take the time, convert it to the integer timestamp, subtract 2 hours and then turn it back into a time string
That could work. It's a little kludgey, but it's just for me, so who cares? 😛
(as_timestamp()|int - 10800) I forget the rest
HA template docs should have something though
That's a great jumping off point. I can work with that! Thank you!
Np!
{{ as_timestamp(states.sensor.tcm.attributes["timestamp"])|int - 7200 }}
gives me the right value, so now I all need to do is turn that back into realtime.
Something like
tcm_starttimestamp:
friendly_name: Start Timestamp
value_template: '{{ as_timestamp(states.sensor.tcm.attributes["timestamp"])|int - 7200 }}'
tcm_realtime:
friendly_name: Start Time
value_template: '{{ as_timestamp(states.sensor.tcm.tcm_realtime) | timestamp_custom("%H:%M", 0) }}}}'
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:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
you have a whole bunch of } at the end of the last line 🙂
Even without the extras.. 😉
Still coming up as as "Unavailable"
tcm_starttimestamp:
friendly_name: Start Timestamp
value_template: '{{ as_timestamp(states.sensor.tcm.attributes["timestamp"])|int - 7200 }}'
tcm_realtime:
friendly_name: Start Time
value_template: '{{ states.sensor.tcm.tcm_starttimestamp | timestamp_custom("%H:%M", 0) }}'
Error rendering template: UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'tcm_starttimestamp'
Well, does it?
I barely know my way around templates. That error is uninteligible to me.
You’re trying to reference an attribute and it’s telling you it doesn’t exist
Go into
-> States, search for sensor.tcm
Make sure it exists. If it doesn’t, you’ll need to figure out what entity you’re actually looking for
If it does, look in the right column and see what attributes it has and what they’re called
If you don’t understand it, where did it come from?
I'm calculating tcm_starttimestamp from a real attribute on sensor.tcm to subtract 7200 seconds
The code, I mean
Learning on the fly. 🙂
Did you copy it from somewhere?
Wanna see the whole thing?
Ok, follow the instructions above
No, let’s find the right sensor and attribute and go from there
And test your templates in
-> Templates
so tcm_starttimestamp = sensor.tcm - 7200
basically
?
I'm guessing that isn't being passed to the template
Yes. I'm taking sensor.tcm.attributes["timestamp"] - 7200
@inner mesa would he have to pass that to the template also?
(i know sweet FA about templates)
The original attribute is coming over from an API
He/She needs to follow the instructions I wrote above
It's called timestamp
@inner mesa I see what you're getting at, I guess we wait
what are its attributes
It has the following attributes
- name
- releaseYear
- tvParticipants
- tvDirectors
- description
- runtimeMinutes
- time
- timestamp
OK
You just weren’t answering
so do I