#templates-archived
1 messages · Page 100 of 1
thanks for helping
I apprecaite it
I think python_script is the way to go - I didn't know about them
@dapper bridge just realize you can't create methods in the python_script environment. So you won't be able to have a recursive function. You'll need to make a bunch of for loops and only go to a specific depth.
@dapper bridge whelp, give it a try then. Last I remember, it wasn't possible.
memory could be wrong 🤷♂️
https://gist.github.com/tioan/ae95e43ae828ce41ae5587af839cd74b
how i can use the template in the gist as availability_template for an fan template?
@tropic hill your indentation is wrong for availability_template and you can simplify your template to:
{{ is_state('switch.shelly_shsw_pm_006037', 'on' ) or is_state('switch.shelly_shsw_pm_006037', 'off') }}
lordt this is driving me nuts. Can someone spot the reason my switch won't replace my variable with the proper data? command_on: ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.134 curl bobby@localhost:44462/set_data_value?name=GUI_chargeLimitRequest&value={{ states('input_text.chargelimit_value') }} >> /dev/null
noob trying to make a template sensor from api response. Got it to work pulling one attribute, but not sure formatting now if i do it within this same template, or if i create another sensor for each attribute / key and template for then grouping all the responses.
@narrow quiver make 1 rest sensor to peel the information from. Place the whole json object into attributes, then use template sensors to grab the data out.
Okay do I just shorten the value template aspect of that then to not be specific
Hello there,
I was wondering if there is a way to access the last_seen property of a https://github.com/home-assistant/core/blob/0.114.1/homeassistant/components/zha/core/store.py#L33 in a template ? (as it's not part of the state object as far as I understand, it might be tricky ?)
Does it show on the
> states entry for that entity?
nope
because it's not part of the entity (I do not want the last_updated that comes when the value changes)
Probably SoL then
but the last time HA received a message from this device
Probably SoL then
@dreamy sinew pardon me but... what'sSoL? 🙂
S**t outta Luck
oh ok 🙂
hi, i’m having a sensibo, (climate) and i am trying to exclude the fan as a seperate etinity - true that i need to use fan template ?
Haven't messed with that device but you could try it
Thx, I have searched alot for exemples but can’t find alot that makes sense. Like this one :
’input_boolean.state’
What does input_boolean do? 🤦🏻♂️
If I use the exemple you sent me, where do I write my climate entity? Cant figure that one out
configuration.yaml like the docs say
So where it says: ’bedroom_fan:’ i should write ’climate.hall:’ ?
Ok, that’s what i Mean, where in this template do I link my climate...
@narrow quiver you want to make sure your value template is a result that continuously changes. So it doesn't matter what you put in it as long as the main state field updates (value_template links to the main state field).
How do I set volume_mute in Universal Media Player
I've tried:
volume_mute:
service: media_player.volume_mute
data:
entity_id: media_player.ht_z9f_2
is_volume_muted: '{{ is_volume_muted }}'
invalid boolean value {{ is_volume_muted }} for dictionary value @ data['is_volume_muted']
Question with jinja and yaml: how can I put a multi-line yaml variable into a jinja yaml template and have it properly indent the multiline value?
Hey You! Thank you for reading this 🙂 The following is an event that i am passing to an automation. I need to get the values from "event_response" to pass them in an Delay action. When i try:
seconds: '{{ event_response }}'
i get an error that there is no float in this variable and i noticed that it this variable is nothing (like a space)
Theevent_response_typeis catching normal in the trigger... So how i can traslate it so the Delay action understands the number in event_response in seconds?
{
"event_type": "alexa_actionable_notification",
"data": {
"event_id": "actionable_notification_kucheon",
"event_response": 3,
"event_response_type": "ResponseDuration"
}
I found I could do something like {{ my_var | indent(width=6, indentfirst=False) | default('') }} but wasn't sure if there was something less fragile (i.e., if the rest of the YAML template changes and that indention line changes, I have to adjust that width value)
invalid boolean value {{ is_volume_muted }} for dictionary value @ data['is_volume_muted']
@little gale where did you got theis_volume_mutedvariable?
Can someone spot the reason my switch won't replace my variable with the proper data? command_on: ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.134 curl bobby@localhost:44462/set_data_value?name=GUI_chargeLimitRequest&value={{ states('input_text.chargelimit_value') }} >> /dev/null
Is it just not evaluating the template, @karmic oar?
Does the correct command get executed but with the literal template as part of the path?
Yes, exactly
The same thing worked in my rest_command before I switched it to a command_switch
I've tried every iteration of quotations I could think of and it works in the template editor
You've tried wrapping the whole command in quotes?
I have
I can't find the page I saw the other day but there's a note on shell commands and elevated privileges. Something about not being able to use templates because it runs in a different context.
Are you able to do the curl without ssh?
D'oh. It's on the shell_command page, I just glossed right over it:
When using templates, shell_command runs in a more secure environment which doesn’t allow any shell helpers like automatically expanding the home dir ~ or using pipe symbols to run multiple commands.
Well apparently so did I
Try without piping to null?
The template itself should be fine. I remember someone having similar issues recently and they got templates to work.
No, I can't. Because I can't set up my reverse tunnel to port 22222 (home assistant host), I have to ssh to another pi on my network and run the curl command there instead
Makes sense. Skip the pipe to null?
?
>> /dev/null
No effect.
I added that hoping it was the curl response preventing the command from working
Hmm. I'm outta ideas. I'm a rookie when it comes to Linux.
If I could just get my reverse tunnel set up to the host I'd be all set
Then I could just use rest commands instead
Unfortunately it appears the ONLY way to setup ssh keys to the host is to import them from USB
The same thing worked in my
rest_commandbefore I switched it to acommand_switch
@karmic oar see how in the docs rest_command says ”(supports template)”, but command_switch does not? I’d guess that has something to do with your problems. FR time?
We established that already. Thanks.
Oh. Sorry. Must have missed that. My bad.
Got any gouge on how to get an SSH key set up for port 22222 that doesn't involve importing from USB?
I must be having some problems with discord dropping messages or something, because this entire exchsnge makes no kind of sense to me, so I better drop out of this. But I’ve had quite a few problems with ssh from hass - all of which were related to the hass docker container running as root rather than as a user. After making my own dockerfile to fix that things worked much better.
I just need to be able to access the host
Normally to get SSH access you'd follow the instructions for importing a key via USB
I run HA in a VM so I can't. No way to do USB passthrough
I run HA in a VM so I can't. No way to do USB passthrough
@karmic oar what hypervisor? because I know you can do USB passthrough with virtualbox and with vmware
My VM is in FreeNAS
is it allowed to use # comments in multiline templates ?
Hey. Not sure if this is the right place but here we go:
Is it possible to combine scripts to define an entity of its own?
I have an ac unit which I cannot directly integrate with. So I'm doing it through ifttt and scripts into home assistant.
I am going to create turn on and off scripts.
Turn up and down the temperature scripts.
Would be nice if I could template a air conditioner device somehow like mqtt devices or adb devices.
Really I'm looking for a ac type for this:
www.home-assistant.io/integrations/fan.template/
@karmic oar
Does this work?
command_on: ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.134 -t curl bobby@localhost:44462/set_data_value?name=GUI_chargeLimitRequest&value={{ states('input_text.chargelimit_value') }} > /dev/null
How do I set
volume_mutein Universal Media Player
I've tried:volume_mute: service: media_player.volume_mute data: entity_id: media_player.ht_z9f_2 is_volume_muted: '{{ is_volume_muted }}'
Any help guys??
it does
https://www.home-assistant.io/integrations/shell_command/
The commands can be dynamic, using templates to insert values for arguments.
Well, it certainly hasn't yet.
You need to quote the entire line
I've tried that. I've tried every variation of quotation I could think of
Almost everything works in the template editor. Nothing works in practice.
Command failed: ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.134 curl bobby@localhost:44462/set_data_value?name=GUI_chargeLimitRequest&value={{ states("input_text.chargelimit_value") }} >> /dev/null
That's all I ever see
Why ssh to a remote to execute a curl?
Because I don't have access to my host
So the reverse tunnel to port 44462 is set up to another rPi instead and I SSH there to run the command
Otherwise if I could set up my reverse tunnel directly to the host I would do that and just use a rest command
But I can't do that
Because the only way to set up SSH to the host is by importing keys via USB
and I can't do that
Because I run HA in a VM on FreeNAS that doesnt allow USB passthrough
I tried manually entering my key via VNC to my host
But I've either still got a typo or I've got the key stored in the wrong spot
Either way, documentation is lacking
K
Yeah, that's about the response I normally get.
@karmic oar Are you certain the rest of the command is valid and working? I remember that the log entries echo out the template and not the evaluated value of said template. I would ignore the unevaluated template in the logs - it's probably a red herring.
I'm actually trying the shell_command now. Before some of the users were confused as I was using the command_line switch. I'm trying to run a shell command now but it's still not evaluating the template correctly
Try the same command but insert a static value yourself. i.e.:
ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.134 curl bobby@localhost:44462/set_data_value?name=GUI_chargeLimitRequest&value=3 >> /dev/null```
That will work, and so will
shell_command: "echo {{ states('input_text.chargelimit_value') }} > test.txt"
Well... it'll work if there's nothing wrong with that command and it connects to the target host okay.
Removing the template from the mix is just to prove it's probably not the template that's causing it to fail.
I'm rebooting now... but I think it's supposed to be this > set_chargelimit: ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_rsa pi@192.168.1.134 "curl 'bobby@localhost:44462/set_data_value?name=GUI_chargeLimitRequest&value={{ states("input_number.chargelimit_value") | int }}' > /dev/null"
Find out in a few minutes when it comes back up
Piping it to an int seems unnecessary since you're just immediately concatenating it onto a string... but wrapping the remote command in quotes might be a good shout.
Your next problem will be that you're not using mixed quotes 😉
The quotes starting at "curl end at states(".
Well I am... Double, single, double
Not in all the places that matter.
Since I tried just escaping them and the the validation tool got very upset
That's to be expected.
> Templates will want real quotes.
Okay, so that works
Will there? Most of mine use single quotes for all my sensors
friendly_name: 'Solar Generation (Raw)'
device_class: power
unit_of_measurement: W
value_template: "{{ state_attr('sensor.neurio_raw', 'channels')[3]['p_W'] }}"```
Single or double is fine, as long as you're mixing them to avoid the need to escape.
Valid: value_template: '{{ states("input_number.chargelimit_value") | int }}'
Also valid: value_template: "{{ states('input_number.chargelimit_value') | int }}"
Invalid: value_template: "{{ states("input_number.chargelimit_value") | int }}"
In your shell command, it looks like it's evaluating the template before trying the shell command, which is why it works.
If it looked at the pairs of quotes first, you'd have two double quoted strings and some gibberish in between.
But it works, which is what matters.
If I want a notification message to contain the device and action that triggered it is that something I need to use a template for?
See the state object documentation to see the stuff you can access: https://www.home-assistant.io/docs/configuration/state_object/
Can't make much sense of that page to be honest
It doesn't explain the syntax of how to refer to an entity state
Inside of an automation, you can use the trigger object. You have information like the new state (to_state) an the old state (from_state).
So you could, for example, get the new value of whatever triggered the automation using {{ trigger.to_state.state }}
Likewise, you can get its friendly name with {{ trigger.to_state.name }}
Sorry I don't understand what you mean by that and it doesn't look like anything I'm seeing in the automation triggers YAML or the states > entity view
Why would it look like anything in States? It's a template. States are just single values.
Here's an example automation that uses that templating: https://hastebin.com/dipumuyela.cs
It watches for the change in state of two switches. It doesn't matter which one changes, the template near the end knows what the new value of that switch's state is.
I have an entity called sensor.26c2_battery - if I want to include the current state in a message would that be {{ state.sensor.26c2_battery }}?
Better to use the states function in case it doesn't return a value: {{ states('sensor.26c2_battery') }}
But that's nothing to do with what 'triggered' anything...
How would you refer to the triggering state change then?
🤦♂️
I gave you an example. Scroll up.
I don't know what part you don't get, so I don't know how to make it any clearer.
Tried making the notify message {{ trigger.to_state.state }} and it changed to '[object Object]': null after saving
🤷♂️
What are you actually trying to do and what don't you understand?
So far your feedback has essentially been 'I don't get it'.
I have 10 devices that can send tilt, vibrate or drop alerts. When any device does any of those 3 things I want to trigger a noticifcation that says 'device' has 'dropped/tilted/vibrated
I have one automation with all the triggers and I want the Action to be Call the service and send a message that says what trigger has fired
I'm not sure how my previous answers don't give you the solution 🤷♂️
ok thanks for your help
Is there some way to set a temporary variable within a sensor template? I have over 30 door sensors I want to check, and I want to generate a sensor that outputs the status of any that match a condition. e.g. if door's X and Y are open but the other 28 are closed, the sensor would read: "Door X is open. Door Y is open.". Ideally, I would set a few temporary variables, "sensorText", "sensorName" and "desiredState". If sensorName.state != desiredState, then text should be "sensorText sensorName is sensorName.text", otherwise the text should be nothing. I'd then list out all 30 entities with those three variables set, so that the sensor is blank if everything is closed, and only looks like "Door X is open. Light Y is on." if the entities are not in the desired state.
Ultimately I'm seeking to have a service named "going to bed" that then sends me a message on telegram confirming that it has run the necessary things (e.g. turned off some lights) but also report out on any door/window sensors that aren't in their desired state. I think the sensor is the best start.
You can make variables in jinja but they only live in the context of that one template
@dreamy sinew Thank you, that helps. I'll start digging into it.
Is it possible for 'wait_template' to have multiple entities in it? For E.g: ```
wait_template: {{ is_state('binary_sensor.alarm_part1', 'on') AND is_state('binary_sensor.alarm_part2', 'on') AND is_state('binary_sensor.alarm_part3', 'off' AND is_state('binary_sensor.alarm_part4', 'off')) }}
Yes, but don't capitalize "and"
Cool! I got an error with the capital letters, then built this workaround which might work, but if the lower case and works its first prize. Appreciated!```
wait_template: >-
{% if is_state('sensor.risco_alarm_garage_status', 'armed_away') and
is_state('sensor.risco_alarm_outside_status', 'armed_away') and
is_state('sensor.risco_alarm_living_area_status', 'armed_home') and
is_state('sensor.risco_alarm_master_bedroom_status', 'armed_home') -%}
True
{%- else -%}
False
{%- endif %}
Better off using what you had first and making the AND lowercase
Hi guys! Does anyone know how I can create a volume slider? Right now I have several buttons that control the volume of my home HiFi in intervals of 10 but it is pretty ugly and bad for voice assistants.
input_number and an automation that fires whenever the state of that slider changes
<helped them in #the-water-cooler, where they crossposted>
Ah thanks
Hi folks!
I've been following this: https://www.home-assistant.io/integrations/template/
to create my ac_hrly_template.yaml file.
ac_hrly_template.yaml has this: https://paste.ubuntu.com/p/hprqqQJHVb/
Doesn't work with the unique id in, if I take it out it works just fine.
What am I doing wrong?
note:currently running the docker verion of 0.113.0
‘Doesn’t work’ means what?
When I use the 'check configuration' from the server controls, I get the some what cryptic: Invalid config for [sensor.template]: [unique_id] is an invalid option for [sensor.template]. Check: sensor.template->sensors->ac_history_stats_hrs->unique_id. (See ?, line ?).
hmm, works for me
VSCode doesn't like it, but config check passes
I'm using 0.114.1, tho
Thanks RobC, I'll pull the new docker image tomorrow and see if that resolves my issue
is the last line really on a separate line?
it looks like you have a newline, with the second half of the expression starting at the beginning of the next line
or maybe it's wrapped and is confusing pastebin
ok. yeah, I dunno. I didn't know that you could manually assign unique IDs, so that's news to me
I stumble on that in the https://www.home-assistant.io/integrations/template/ doc and wanted to test it out
it looks like that was just added: https://github.com/home-assistant/home-assistant.io/commit/ac5172cd366652f72ba8a2fbf988d92053f03b0a#diff-d448aa9773d8ccf9f10018be947b45ef
I'm trying to find it in the release notes, but failing so far
docs were updated 14 days ago
I'm guessing it came into 0.114
Add optional unique_id attribute to the template platforms (@michaelarnauts - #38011) (template docs)
I just looked at that 'pull note' < sorry i don't know the prpoer term
Pull Request
Thank you ---
I’m mainly just satisfying my own curiosity
Thanks again folks, I will pull the newer docker tomorrow and try this again
anyway to get uptime with this mess?
{{now().strftime('%H:%M') - state_attr('binary_sensor.ozw_network_status', 'TimeStamp')|timestamp_local }}
I hate working with time in templates
Me too. I’m never surprised when it doesn’t work 🙂
‘I’ll be of no help here, moving on’ 🙂
Hi, trying to create a fan from a climate integration. Here is an error I got, what could be wrong
Invalid config for [fan.template]: required key not provided @ data['fans']['hall_fan']['turn_off']. Got None required key not provided @ data['fans']['hall_fan']['turn_on']. Got None. (See ?, line ?).
Can anyone see whats wrong here: https://paste.ubuntu.com/p/S2VyPCxrvQ/ ? When I trigger it I get UndefinedError: 'dict object' has no attribute 'from_state' in the log
I get the same error even if I remove {{ trigger.from_state.state }} from the message
Are you triggering it through the device or the UI?
@nocturne chasm you have a clue for my problem? 2 posts up...
No, is your yaml consistent with the docs. Use hastebin to post what you have done
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
https://hastebin.com/erowotivuk.php here is my code
@nocturne chasm through the device
Progress - if I change the trigger type from device to state it works https://paste.ubuntu.com/p/kjhJptTHPF/
So now is there some way of making it so if ANY sensor state changes to drop, or tilt it will trigger and send {{ trigger.entity_id }} and {{ trigger.to_state.state }}
is there a generic entity you can use for an else in a data_template? Similar to homeassistant.update_entity in a service_template? I don't want anything to happen
i guess i can just create a input_boolean that does nothing
@obsidian nacelle you can't use state triggers, you'd have to use event triggers for that
which would completely change your template as well
@brisk temple make a condition template prior to that action
ya, i definitely need a condition, it triggers the action non-stop
but needed the kids to go to school and wife to work so i can think
yes, so put a condition prior to the action and the action wont execute. Instead of a 'blank entity' in the else.
post your action section and I can help.
I can't see any examples for that - I imagine its not an that uncommon - to have multiple motion sensors and an automation that alerts which one has triggered
the sensor.stats_ states update constantly while they are on their laptops, it's a history_stats sensor
you should just make 2 template sensors
well, lets take a step back.
how are you populating input_text.aislin_laptop_time?
that actually isn't needed in the trigger state, i just took it out, but it's manually done setting how many minutes the kid can be on the electronics
i was thinking of a or template condition that would filter until the time is under 7 minutes for each
it's a history_stat sensor and i couldn't find the refresh interval
ok
it's fed by a ping sensor, so if that's the interval every 5 seconds
and you just want to notify at 3 minutes and 7
ya
you don't want a notification every 5 seconds either
i have another automation that initiates the notification only once, when the input_boolean turns to on
Ok, if you make these 2 sensors:
sensor:
- platform: template
sensors:
notify_orla_laptop:
value_template: >
{% set child = 'orla' %}
{% set v = (states('sensor.stats_orla_laptop_daily') | float * 60) round(0) | int %}
{% set t = states('input_text.orla_laptop_time') | int %}
{{ t - v }}
notify_aislin_laptop:
value_template: >
{% set v = (states('sensor.stats_aislin_laptop_daily') | float * 60) round(0) | int %}
{% set t = states('input_text.aislin_laptop_time') | int %}
{{ t - v }}
they will count down.
k i actually have a count down senor for that
ok, then why are you doing the input booleans?
if you already know when 3 and 7 minutes are hit?
i wasn't sure it would hit exactly
why even turn on booleans?
are you firing a script?
if you have the countdown sensors, build an automation based on the count that notifies the correct script based on the number
no need for input booleans
and then in the action do the notification?
yea, unless you have different messages. But if you're just saying '3 minutes' or '7 minutes', just do that.
using the sensors I posted above...
trigger:
- platform: state
entity_id: sensor.notify_orla_laptop, sensor.notify_aislin_laptop
condition:
- condition: template
value_template: "{{ trigger.to_state.state | int in [ 3, 7 ] }}"
action:
- blah
I can help you with the action, but i'd need to see what you intend to notify.
thanks, i'll give it a go
I read that but it didn't help, thanks.
@obsidian nacelle https://www.home-assistant.io/docs/automation/trigger/#event-trigger
event_type would be state_changed
your template info https://www.home-assistant.io/docs/automation/templating/#event
{{ trigger.event.data.entity_id }}
you'll have to register to the event to see the shape of data to properly grab out the to_state.state. I would assume it's:
trigger:
- platform: event
event_type: state_changed
condition:
- condition: template
value_template: "{{ trigger.event.data.to_state.state in ['tilt','drop'] }}"
action:
- service: persistent_notification.create
data_template:
message: "{{ trigger.event.data.entity_id }} reports {{ trigger.event.data.to_state.state }}"
title: motion
mode: single
thanks @mighty ledge, thats really helpful - just knowing to subscribe to events is very useful
yep, it's in the developer tools > event tab
{% set entityDesiredState = "off" %}
{% set entityTextToSend = "Door Sensor 3 is open" %}
{% if is_state(entityName, entityDesiredState) %}
{# do nothing #}
{%else%}
{{ countOfEntities }}) {{ entityTextToSend }}
{% set msgText = msgText ~ newLineChar ~ countOfEntities ~ ") " ~ entityTextToSend %}
{% set countOfEntities = countOfEntities + 1 %}
{%endif%}``` I am considering using this text 30+ times in a sensor, so that I have some text to send myself in a Telegram bot that reports out on every entity that is not in a desired state. (use case: heading to bed, want to know if any doors are open). Any reason to not have such a lengthy and computationally complex sensor?
Ooh, I could maybe set up an array so that each device, desired state, and text to send is on one line, then i just iterate through the length of that array.
Ok, that text works in the Template editor, but when I create a sensor template with it it only seems to update when HA is first started. How can I force this to update?
Ah, homeassistant.update_entity may work.
is there a way I can reload sensors only?
{% if state == "50:1A:A5:4E:55:1F" %}
Jabra
{% elif state == "FC:62:B9:27:AC:6B" %}
Golf
{% elif state == "B4:EC:02:97:83:34" %}
Tiguan
{% else %}
NotConnected
{% endif %}
{% endfor %}
this sensor works in the templating tool but not as a sensor.... trying to work out whats up but restarting every time is pain
nope, unfortunately
looks pretty straightforward. Can you share your whole template sensor definition?
Yeah, also explain what you mean by not working
hastbin works again now; https://hastebin.com/zosuyevezi.pl
so the sensor, right now with noting connected... shows nothing as the state.. but when it was connected to the 'Tiguan' showed, 'NotConnected'.
and with the Jabra connected, it actually shows Jabra.
now funnily in the teplating tool, I am just realising it is not showing 'NotConnected'. hmpf
so I am thinking it is not looping, since htere is nothing in the attr array
I'm pretty sure you could do that better with a map
sure but I think I need an if that checks the length of the list first.. if the list is length 0 then say Not Connected... else a case/family of if statements
kinda confused what that's trying to do
do you want one thing out of that whole for statement or several things?
well the attr connected_paired_devices is a list
sure, so you could do something like this:
blah. There's almost certainly a better way to do that, but I need to devote more brain cells than are currently available 🙂
I don't think you really want a for, but instead a set of if xxx in "connected devices"
ah, yeah. True
and it would bail after the first one found
well the for would return the first one found also
it actually won't
it will go through all the connected devices
that's where it starts to confuse me
ah, yeah. so you would get the last
does jinja have a case statement?
can I say 'if NotNull in "connected devices' somehow?
(you can set a variable at the top for the state_attr() clause and simplify the rest...)
what are you trying to do with "NotNull"?
oh, just the length test.... eg. there being a mac address I dont' recognose vs being not connected
your length test is fine, IMO
yeah, but you were making life easy for me? 😛 lol
random example from the docs:
{% set iterated = false %}
{% for item in seq %}
{{ item }}
{% set iterated = true %}
{% endfor %}
{% if not iterated %} did not iterate {% endif %}
in your case, {% set devices = state_attr('sensor.jurgen_bluetooth_connection', 'connected_paired_devices') %}
yeah, I just found it. n1
I haven't really used jinja since my ansible days
Legend, tyvm for your assistance... super appreciated @inner mesa
np, glad to help
I could probably use 'set' in a lot of my templates, tbh
it's just template-scope, so kinda limited
yeah, sure but I have some hectic templates that are a ballache to read
helps to avoid typos, too. Or at least localize them 🙂
hey, one ting that has already annoyed me in HASS is when you restart... when you click on a sensor or switch the 'time since last state' is actually counting back to the last restart.... not the last state change..
I think that's a known issue. making "last_changed" restorable
I vaguely remember Paulus mentioning it recently
ok, I restarted. It seems to be looking better now. We will see over time
is this valid syntax?
condition:
- condition: template
value_template: "{{is_state('trigger.payload_json['TRIG'], 'SINGLE') }}"
Nope
You have an extra quote to start
I would get rid of is_state() and just use ==
like this? value_template: "{{ trigger.payload_json['TRIG'] == 'SINGLE' }}"
Looks reasonable
ok thanks.
Hi all, I have a couple of template switches that are supposed to get their values from input booleans. I've noticed that only do they turn off a couple seconds after activation, but they always have an 'update for switch failed' message in the log whenever I restart. Is there anything I can do?
~share your templates?
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
First thing I notice is that calling the scripts like that will cause them to run in parallel
Is that your intention?
Yeah - I've set up some motion detected lights in the kitchen that turn off after X seconds of no motion. The idea is to have an option to turn the lights on via voice and keep them on, so the template turns the lights on and ignores motion detection
Point is that motion_stop and lights_on will run concurrently
Ah OK. I haven't noticed an issue with its functionality to date, but if it could cause issues down the road how would I get them to run one after the other? Big fan of stability!
Just trying that now
I switched all of my scripts to run concurrently and then realized that order actually matters for some
Just made the change and functionality is retained - thank you, I didn't know scripts could be called like that
Still having the issue of the switch value itself not being updated. When I turn it on/off/via alexa, the lights work, but the switch value doesn't change. When I flip the switch myself through the lovelace interface, the lights work fine, but the switch itself flips off after a couple seconds (but the lights stay on so that's good)
ah, the plot thickens
Thankfully the lights themselves work exactly how I need them to
It's literally just that switch acting weird in lovelace, though it does what I want it to
there's nothing there that I can see that would cause the lights to turn off shortly after turning them on, so there must be something else going on
Thats the strange thing - the lights themselves don't turn off, they work as intended
the lights stay on, but the switch in lovelace interface flicks back to off after a couple seconds
oh, I see that now
If I didn't look at lovelace/error logs, I wouldn't even know there was an issue
you could just remove the value_template: completely if you like, and it will just assume that it turns on when you flip the switch.
oh, this is wrong:
is_state('input_boolean.kitchen_boolean')
you need to use is_state('input_boolean.kitchen_boolean', 'on')
that's probably causing both problems
see the example here: https://www.home-assistant.io/integrations/switch.template/
That did it! And helped clean up my config/script code! Thanks a lot
np. couldn't see it staring at my phone, but it was clear when I pulled out my laptop 🙂
Hello, is it possible when defining, or loading, a input_select to define a value/label pair? Like display Heat but the value is heat! Or display Eco Mode but the value is eco! Or to use in channels display Name but the value is the channel number!..
Nope
Not for the input itself. You'd have to do template magic to go from a display value to some other value.
Hello, hope i'm in the good channel, otherwise, i'm sorry but i was creating a script and it throws me an error to the last line column 14 and i don't know what is bad, can you help me ? ```yaml
test:
alias: Test Script
mode: single
sequence:
- data_template:
entity_id: input_select.select_sound_cdj_speaker
service: input_select.set_options
options: '{{states(''sensor.cdj_speaker_sounds_list'')|from_json}}'
Why is there a red cross emoji on my message ?
ah ok, i will post my code to hastebin
because it's not valid YAML
i don't see where is the problem
if you really have those '' instead of ", that's a problem
i need to change the last line to that ?```yaml
options: '{{states("sensor.cdj_speaker_sounds_list")|from_json}}'
it also doesn't match the examples: https://www.home-assistant.io/integrations/input_select/
you have to nest things properly
in the examples, there's not an example with a sensor state
that doesn't matter
options: and entity_id: are both children of data_template:, but that's not what you're written there
your indentation and ordering are wrong
- data_template:
service: input_select.set_options
entity_id: input_select.select_sound_cdj_speaker
options: '{{states("sensor.cdj_speaker_sounds_list")|from_json}}'
still wrong 🙂
follow the examples
- service: input_select.set_options
data_template:
entity_id: input_select.select_sound_cdj_speaker
options: '{{states("sensor.cdj_speaker_sounds_list")|from_json}}'
there may be other issues, but at least that's the properly format
see the difference?
@noble herald posted a code wall, it is moved here --> https://paste.ubuntu.com/p/MdGXPWkVBC/
I can't tell what's going on there
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
ok
i'm restarting hass with the first to try and see
ok the script runs well but not add the options like i want
this is the state of the sensor ["beep","cigales","humans","test"] and this is the only option i have in the input select ['beep', 'cigales', 'humans', 'test']
do you know to get that working properly
i have not write that ['beep', 'cigales', 'humans', 'test'] myself
it's the script
you don't like the quotes?
i've no problem with quotes
i don't understand where the problem is because when i do the trick manually it works but not when the script does that i explain :
when i paste {{states("sensor.cdj_speaker_sounds_list") | from_json }} in the template dev tools it outputs me ['beep', 'cigales', 'humans', 'test'] and if i paste this in the options : in the service call dev tools it works well and set the options according to the list but when the script does this the only option in the input select is ['beep', 'cigales', 'humans', 'test'] do you know what's going on ?
RobC help me please I beg you
why are you using "|from_json" if the state, as you mentioned earlier, isn't JSON
this ["beep","cigales","humans","test"] is json no ?
yes but a json formatted list
yes i know but i just tested without |from_json and it is the same problem but now the ' ' framing the item are now " "
so, that doesn't solve the problem
i forget to mention but the state of the sensor comes from a command line sensor
The problem is that templates always return a string even if it looks like a different data type
So while that looks like a list, it's actually a string since it's the result of a template
and it can't be converted into a list ?
Nope
so, what i want to do is impossible ?
Is it going to be a fixed length list?
no but i can put a limit if necessary
You'd basically need to ensure the list is a fixed length and then do something like
data_template:
options:
- "{{ states('input_select.whatever')[0] }}"
- "{{ states('input_select.whatever')[1] }}"
...
i will explain what my first need is. I want an input select have all the filenames in separate options of a linux folder in a raspebery pi without the extension visible if possible so like that i can choose i file in the frontend and call a script with the state of the input select inside it
What is the ultimate goal here though
to have a play button aside from the input select and be able to start playing a music on the raspberry pi 3.5mm jack but i want to have the hability to upload new .wav files in the specified folder in ftp and that home assistant refreshes the input select automatically or with a refresh button
the only part that is not working for now is the automatic update of the input select, all of the rest works perfectly fine
but if it is impossible to do, i will add options to the input select manually but this is not very fun to do
😢
so, i can conlude this isn't possible ?
Not in they way you're trying at least. Home assistant isn't really meant to be a media server though
yes i know
Thank you anyway
Hi everyone. I'm having an issue with a light template whereby using unique_id results in an invalid option error although it's in the documentation. https://www.home-assistant.io/integrations/light.template/#unique_id
Invalid config for [light.template]: [unique_id] is an invalid option for [light.template]. Check: light.template->lights->living_room_light->unique_id. (See ?, line ?).
light:
- platform: template
lights:
living_room_light:
unique_id: living_room_light
Home Assistant 0.113.2
If you want to use all the newest features, you need to be on the newest version. You're a major version behind.
I believe the unique_id fields were only added in 0.114, @dusky bison
If you follow the link from the docs to the GitHub for that integration, you can see the commit that added that feature was only made 17 days ago.
@ivory delta Thanks. That makes perfect sense.
I want a sensor to tell me how long I'm away from home -
device_tracker.me_2 is my mobile phone which shows that I left home as 08:10 and arrived at work at 08:24
though {{ states.device_tracker.me_2.last_changed }} reports 09:00
create 2 input_datetimes. Create 2 automations, one to set one of the inputs when you leave, one to update the other when you get home. Add a template sensor to subtract 1 from 2
would probably need additional handling for when you're currently away
alright, thanks @dreamy sinew
@orchid onyx posted a code wall, it is moved here --> https://paste.ubuntu.com/p/j8xcgnmsv6/
Anyone?
You're missing required entries for turn_off and turn_on
So this part
{% if states('climate.hall') in ['heat_cool','heat','cool','dry','fan_only'] %} on {% else %} off {% endif %}
dont help me a shit then?
Thx
That just defines the state. You still need to give it services for turn_on and turn_off
Will this solve my problem:
turn_on: service: climate.turn_on data: entity_id: climate.hall turn_off: service: climate.turn_off data: entity_id: climate.hall
No error so I will try now 🤩
Wow it works, thx alot. Been trying to make this work for weeks now,
thx alot for help
Can you explain what thisone does:
oscillating_template: > {% if is_state_attr('climate.hall', 'swing_mode', 'Off') %} False {% else %} True {% endif %}
Defines a template to get the osc state of the fan. Valid value: true/false
I have those modes avaible:
swing_modes: stopped, fixedTop, fixedMiddleTop, fixedMiddle, fixedMiddleBottom, fixedBottom, rangeFull
should I use this instead to controll osc:
oscillating_template: "{{state_attr('climate.hall', 'swing_mode')}}"
and
set_oscillating: - service: climate.set_swing_mode data_template: oscillating: "{{ oscillating }}"
The code worked but the result is these:
`speed_list:
- quiet
- low
- medium
- medium_high
- high
oscillating: null
speed: null
friendly_name: Sensibo fläkt
supported_features: 3` so it did not work :/
If you use 3 backticks at each end, those code posts will be a lot less ugly 😉
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
Thx for info, learning something all the time 😄
me and my wife charge both our phones in the same smart power outlet. Is there a template i can use to turn off the plug when both phone is above 80%? I'm really new to this,
If anyone can write a template that would work would be really nice! 😄
an automation with a template trigger
{{ states('sensor.phone_a_batt')|int > 80 and states('sensor.phone_b_batt')|int > 80 }}
Thank you so much !!! 😄
{{ states('sensor.phone_a_batt')|int > 80 and states('sensor.phone_b_batt')|int > 80 }}
@dreamy sinew Thanks it works 🙂 But i use the battery sensor from HA android app. Is there any better way to get battery sensor that updates more often ? 😄
The phone charging mode should mostly take care of the problem that I think you're trying to solve
What do you mean ? 😛
if you're just trying to avoid charging to 100% to avoid stressing the battery, most modern phones take that into account. iOS tracks your battery usage/charging behavior and dynamically chooses how much to charge and when to stop
in other words, you'd be gaming something that's already optimized
Since this isn't the first time you've asked this question, I'm going to repeat my answer from last time - modern battery tech doesn't 'remember' charging like old battery tech did. What you're trying to do is a complete waste of time, even on Android.
@ivory delta but charging to 100% reduces the overall number of charge cycles you get out of the battery before it reaches EOL (supposedly)
I'm sure that's a myth. I remember Apple's official guidance on it was always that charging from 50% to 100% only counts as half a charging cycle for the purposes of working out total battery life.
Unless you discharge and recharge, it's not actually contributing to wear.
The IC's in the chargers take care of overcharging.
it it the first time about charging 🙂
I think the only no-no is leaving it completely discharged for long periods of time?
which happens to all the gadgets in drawers and closets
I've been charging my 3-year old mobile to 100% every night forever. Still only gets back down to about 60-65% at the end of a day.
Wait, we're in templates, oops
No noticeable decrease in capacity over 3 years.
My Apple pencil died from lack of use and wouldn't work at all
somebody else started it...
If I had thousands of devices to test, I'd be happy to carry out a more thorough study 😉
any battery experts here?
and the plural of anecdote isn't data 🙂
fat chance they'd be hanging out in templates
Is jōk
Then i use the template to turn off the charger when both is at 100% 😄
Hi everybody. I am planing to create a floorplan using https://www.youtube.com/watch?v=XV4xzgraNEk using Drzzs tutorial. I'm planing to add a binary sensor using zwave and phoscon. However, I'm don't understand what is platform, state_topic and name in this yaml. I gone through the doc but still don't understand how the yaml works for binary sensor..
any tutorial can cover this topic?
It’s a tall order to ask folks to watch a video to figure out what you’re asking about 🙂
It sounds like you need to research MQTT sensors
Sorry for that. Let me simplify. I am using Zwave sensor and switchs to create a 2D floor plan but i don't really understand how binary sensor setting in yaml. any tutorials link can cover more about this part of yaml? i watch few video but difficult for me to links the dots together
Yes, the documentation
Actually that’s not a good link. You need to look for the type of binary sensor that you care about
Etc
Thanks for the quick response and the links. I noticed that each binary sensor type have difference setting and i should not blindly follow the tutorial yaml setting. Newbie here😅 . Thanks for clearing that up and navigate me to the correct direction. Appreciate your help.!
Hey...
I'm trying to show IP as a mqtt sensor with the following configuration
- platform: mqtt
unique_id: oTeWg7KnYNo36rqBdbGJCsiWCDt
name: "testroom_main_light_ip"
state_topic: "tasmotas/testroom_main_light/tele/INFO2"
value_template: "{{ value_json.IPAddress | string }}"
availability_topic: "tasmotas/testroom_main_light/tele/LWT"
payload_available: "Online"
payload_not_available: "Offline"
icon: mdi:eye
But I'm getting unknown state
It seems like it takes the value as integer (looking at the graph): https://imgur.com/a/8xZKX85
I have a template for the outside temperature that only refreshes every 3 hours.
Can I change the refresh rate or is this because of the integration not refreshing?
outside_temperature:
friendly_name: "Outside Temperature"
unit_of_measurement: '°C'
value_template: "{{ state_attr('weather.home', 'temperature') }}"
I've tried the met.no integration aswell as the météo france integration
template sensors update when the entities referenced in them update, so this would be an issue with the weather integration
Hey everyone, I'm using a led strip where the effects change (add/removed). I have a list of the effect names sent over mqtt-json. Is there a way to make a template for the effect_list?
Hi
I have to make a daily and cumulative counter which feeds according to the state of a sensor. I created a counter but I do not know how to retrieve the value of the sensor to increase the value of the counter.
Regard
{{ states('sensor.sensor_name') }}
@quick crane I just helped recently with a similar question in the community forum: https://community.home-assistant.io/t/counter-increase/218043
Hey guys! wondering if someone can help with a data_template? Im trying to use input text to send a song or artist to the alexa integration.
- alias: Select Music on Alexa
trigger:- platform: state
entity_id: input_text.music_select
action: - service: media_player.play_media
data_template:
entity_id: media_player.kitchen
media_content_type: "AMAZON_MUSIC"
message: "{{ states.input_text.music_select.state }} in everywhere group"
- platform: state
states.input_text.music_select.state? 🤔
Im trying to return the text entered and am confused
states('input_text.music_select')
- service: media_player.play_media
data_template:
entity_id: media_player.kitchen
media_content_type: "AMAZON_MUSIC"
message: "{{ states('input_text.music_select') }} in everywhere group"
like that?
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
Looks better. Try it out and see what happens. But you didn't tell us what's actually wrong, I'm just pointing out the obvious mistakes.
Just does nothing lol
It'll do something, even if that something is an error in the logs.
- alias: Select Music on Alexa
trigger:
- platform: state
entity_id: input_text.music_select
action:
- service: media_player.play_media
data_template:
entity_id: media_player.kitchen
media_content_type: "AMAZON_MUSIC"
message: "{{ states('input_text.music_select') }} in everywhere group"
Ill check the logs
it might not like this: message: "{{ states('input_text.music_select') }} in everywhere group"
If you're using it in an automation, you can also use the trigger object in later steps. The new state of whatever changed would just be trigger.to_state.state
try
message: >-
{{ states('input_text.music_select') }} in everywhere group
but just kinda guessing without anything in the logs indicating a problem
While executing automation automation.select_music_on_alexa
4:14:01 PM – Automation (ERROR)
Select Music on Alexa: Error executing script. Invalid data for call_service at pos 1: extra keys not allowed @ data['message']
4:14:01 PM – Automation (ERROR)
now im even more confused lol
It tells you that media_player.play_media takes 3 arguments, none of which are optional: entity_id (the target player), media_content_id (the thing you want to play) and media_content_type (the type of media).
No message.
What are you trying to do?
I feel like I've had this discussion before...
probably many times lol
- alias: Select Music on Alexa
trigger:
- platform: state
entity_id: input_text.music_select
action:
- service: media_player.play_media
data_template:
entity_id: media_player.kitchen
media_content_type: "AMAZON_MUSIC"
media_content_id: "{{ states('input_text.music_select') }} in everywhere group"
Bingo... winner winner... chicken dinner!
Thanks for the help friends!
states.input_text.music_select.state? 🤔
@ivory delta that is valid, just not recommended
But not within states()
so much easier to type tho!
@dreamy sinew yeah, I was referencing this: #templates-archived message
Ah, skimmed it
Hey folks! I get an error (Can not read an implicit maping pair; a colon is missed) on the template after his one:
air_quality_inverted:
friendly_name: Luftkvalitet
value_template: '{{ ((states('air_quality.air_quality_norway')) | float) - ((states('air_quality.air_quality_norway'))| float * 2) }}'
The template works as expected in the template editor....??
You need to mix your quotes.
You're currently telling HA to read: '{{ ((states(' and then some gibberish, and then ')) | float) - ((states(' and some more gibberish, and then '))| float * 2) }}'
None of that makes any sense.
Ahhh
You need double quotes around it if you're using single quotes inside 😉
So " on the outer boundaries and ' inside?
Exactly. Or the other way round.
You just have to remember that computers treat things more literally than humans do. When you read your string, it makes sense that the quotes at either end match. A computer just looks for the next matching quote to complete a pair.
It totally makes sense! I feel like this fits well with the "Month of WTH"! 🙂
What am I doing wrong here? ```yaml
value_template: >-
{% if is_state_attr('light.tv_lamp','effect','Night Lamp') and is_state_attr('light.tv_lamp','brightness',3) %}
What does it resolve to in
> Templates? And what do you think it should resolve to?
@little gale that's not a complete template. Are you just trying to return True/False based on that?
Also follow what mono said and you'll get a hint
yeah sorry I fixed it, but yeah, that's just the offending part I pasted.
@tribal rock posted a code wall, it is moved here --> https://paste.ubuntu.com/p/PP9d4nWvmP/
Yikes, sorry. I didn't realise it was so long
So, I've only recently started using hass, and I could use some additional help setting up a Template Switch with a value_template.
The goal is to consolidate two separate switch entities into one template switch for controlling and monitoring the assumed state of both. I'm using SwitchBots to control the separate "Cool" and "Off" buttons on my A/C. The issue is, because they are button pressing bots, switch.turn_on and switch.turn_off provide the same function of pressing their respective buttons. This makes Google searching difficult for what seems like a niche issue.
The code here works, but I just need to add a value_template to set the state of the template switch based on the successful execution of the corresponding on/off service
Pretty code: https://bit.ly/3gfAGRK
I'm confused because I would assume that simply leaving out value_template: should put the template switch into "optimistic" mode, which should do exactly as you say
in other words, it just assumes that the switch is on when you turn it on, and off and then you turn it off
Right, however the SwitchBot service isn't always reliable, and I want to make sure that it catches errors when the occur. Also, I'd like the interface to be a toggle switch rather than two buttons whose state is based on that assumption
Sorry if I'm not making any sense 😰
how do you know when it wasn't successful?
yeah, you'll need a value template for it to show up as a toggle switch
we're probably going to end up with an input_boolean.x or something
That's one thing I'm trying to figure out, programatically at least. I know an error appears in the logs when it's unsuccessful, but I don't know how to translate that to a template.
Ah yeah, I noticed input_boolean in one of my Google searches, that would probably work, I have to look into it more though
would be better to actually read the state of the device you're controlling
it's just a way to store a bit of data, so it's only useful if you know what that bit should indicate at any given point in time
so, you either need to know whether the switch actually did what you asked, or if the device is actually in the state you expected it to be in
Right on point, so I just need some way
...to know whether the switch actually did what [I] asked
how are you controlling the "switchbot" with switch.turn_on and switch.turn_off? What error do you get in the log when it doesn't work?
how are you controlling the "switchbot" with
switch.turn_onandswitch.turn_off?
Both services cause the SwitchBot to press the button.
What error do you get in the log when it doesn't work?
Good question. It looks like its
WARNING (SyncWorker_11) [switchbot] Cannot connect to Switchbot. Retrying (remaining: 2)...
I've never heard of Switchbot before, but the docs tell you how to determine if it succeeded: https://www.home-assistant.io/integrations/switchbot/#switchbot-entity
so what do you want to do if it fails? retry? it seems like it already has some retry logic built in
just be okay with the fact that it didn't do what you asked and let you flip the switch again?
I would create an input_boolean.xxx to indicate the state of the switch, use that in the value_template: and put a condition in the turn_on and turn_off sections that determines whether to turn theinput_boolean on or off based on whether the last_run_success attribute is true
I've never heard of Switchbot before, but the docs tell you how to determine if it succeeded...
How did I miss this? This should be what I'm looking for
so what do you want to do if it fails? retry? it seems like it already has some retry logic built in
Fair point, however I think just having thelast_run_successwill allow me to create avalue_templatefor a toggle switch, should be fine for now
Thanks, I really appreciate it too, because I've been looking at this for an uncomfortable amount of time, lol
Can someone help me please, how do I use the data field from this MQTT message as a template condition? https://paste.ubuntu.com/p/PqHzPNVnTf/
You may want to look at value_json in your search
probably something like: value_template: '{{ value_json.RfReceived.Data }}'
Where would I define what value I wanted the Data to match?
no, you'd compare that with what you want to see
value_template: '{{ value_json.RfReceived.Data == "foo" }}'
np, happens 🙂
Message malformed: Expected a dictionary @ data['condition'][0] 🧐
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
your condition should look something like this:
condition:
condition: template
value_template: '{{ value_json.RfReceived.Data == "foo" }}'
your values will undoubtedly vary
Hmm, I’m missing something - it’s giving an error in the log saying value_json is undefined
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
we're just guessing at what you're actually doing
seems this guy was doing the same thing you are: https://community.home-assistant.io/t/mqtt-json-automation/25770/3
looks like the key was trigger.payload_json.xxx
Thanks for your help @inner mesa
Any ideas why sensor.unavailable_entities lists 177 entities when the template only shows 22 in dev tools? https://gist.github.com/jazzyisj/45fce29d825b8f9b29c5974444299d90
@distant plover because it's only updated on startup, you don't have anything else sparking the update
add entity_id: sensor.time and integrate sensor.time to have it update minutely.
Simply adding time_date sensor made it work apparently. But it doesn't wait 5 minutes before sending a notification it seems. It looks like it runs immediately after restart of HA and then again quite shortly after.
Why isn't the delay of 5 minutes in the package working?
hey, i have a quick question.
{{ is_state('media_player.ps4', 'standby') }}
i want to have is_not instead of is_state
how would i do this?
{{ not is_state('media_player.ps4', 'standby') }}
thanks that worked
feel like an idiot now lol
Lol it's all good
Can anyone assist? I'm trying to get my GH to play media. I had play_media before which is now media_play. Now, however, I'm getting an API error:
"Call-service API error. Error Message: extra keys not allowed @ data['media_content_id']"
Here is the content of the JSON:
{
"media_content_id": "http://172.16.x.x:8123/local/media/catbowl.mp3",
"media_content_type": "audio/mp3"
}
yeah, you should be using play_media. Look at the service caller in developer tools.
smacks head
Thanks
I've got to find a way to evaluate if the current day is the 4th saturday of the month. Not even sure where to start with that one.
You could have a look at using now().isocalendar(). Not quite the same as your request but I have something that cares about odd/even week numbers:
{% if now().isocalendar()[1] % 2 %}
Although that only gives year, week number, day number. There's probably a better way.
but now() is probably the right starting point
Just gotta figure out all the Python stuff for datetime 😉 https://docs.python.org/3/library/datetime.html
Hi, could you please explain me what is wrong with this template sensor ? This code works in templates tab:
{{ ( as_timestamp(now()) - as_timestamp("2020-07-29 15:00:00"))/3600/24 }}
but in yaml file it show errors:
- platform: template
sensors:
left_hospital:
friendly_name: "Doma z nemocnice"
unit_of_measurement: 'days'
value_template: "{{ ( as_timestamp(now()) - as_timestamp("2020-07-29 15:00:00"))/3600/24 }}"
You need to mix your quotes.
value_template: "{{ ( as_timestamp(now()) - as_timestamp('2020-07-29 15:00:00'))/3600/24 }}"```
I think you could check if the day of the week is Saturday (6) and if the date is between 22 and 28 @crude crest
Between or including
ah, ok, thx @ivory delta
I need a now().day_name
.isocalendar() gives you a tuple where the 3rd value is the index of the weekday.
looking through the python datetime documentation right now
now().isocalendar()[2] == 5
that would work as well
Hmm. Looks like it's not zero-indexed... might need == 6.
6
The 5 in my first one was deliberate. Almost everything's zero-indexed.
Python is weird. Dates are weird.
I work with NodeJS. JS dates are odd... Year is what you'd expect. Date is what you'd expect. Months are zero-indexed...
Like, wth?
fuck it, just give me unix timestamps, i'll do the math myself.
{{ now().isocalendar()[2] == 6 and now().day > 22 and now().day < 28 }}
So this should only ring true on the 4th saturday of the month.
You'll want to change those to 21 and 29 if you're not using inclusive comparators.
oh, let me add the =
well, too bad the last trigger was last night, but i might temporarily change it around to see if it'll trigger tonight.
Not like we were able to have anyone over for game night last night anyways. Gotta love the pandemic in the US. People here still haven't gotten their shit together.
I appreciate your help though. I figured it would be pretty straight forward, but I didn't think about the date range.
Nor did I. Tediore is one of the brainy ones round here.
22 and 28, right?
@ivory delta yep, thanks 😅
hello gents recently i flashed a wifi vacuum cleaner with Tasmota and I get the state and the battery % in this message {"SerialReceived":"AA1C06FF000406000000000000000000000000000000000000000000006473"}
The last 4 numbers are the battery % and the state of the vacuum, can i have a sensor only showing that part of the message?
some form of concat I'd imagine
not sure how to implement this in HA but I'd imagine something like this
var SerialReceived = "AA1C06FF000406000000000000000000000000000000000000000000006473";
var lastDigits = SerialReceived.Substring(SerialReceived.Length - 4, 4);
does it return the string the same length everytime?
{{ value[-4:] }}
``` where `value` is a reference to the sensor that has that value
but the problem would be if the battery is 100%
I was wondering if someone could help out with a rest sensor....
I have a sensor set up like this: https://paste.ubuntu.com/p/Crm9DncmR4/
It filters on this data: https://paste.ubuntu.com/p/Zk68kmvfYJ/
Ideally I want it to return the state (started|stopped) for every addon in that json data, but it only returns the state fir the first addon in the list.... I am new to this, so hoping I am doing something wrong....
{{ value[-4:] }} ``` where `value` is a reference to the sensor that has that value
ohhhhh so it's even easier than my wrong way
so just {{ SerialReceived[-4:] }} is all he needs then Tediore?
@trail estuary
{%- for x in range(0,value_json.data.addons | length) -%}
{{ value_json.data.addons[x].state }}{%- if not loop.last -%}{{ ', ' }}
{%- endif -%}
{%- endfor -%}
``` is a start. that will return all the states separated by commas. of course, you could exceed the state length limit this way
That will return all the states as a state?
based on the source data that will return
started, started, started, started, started, started, started, started, started, started, started, started, started, started
Hehehe
not sure what your goal is though
In the end I wanna set up a Grafana dashboard monitoring the state of all installed addons.... But I need to get that data somehow
The nice thing with the rest sensor is that it will return the name of the addon and the state as attributes...
But if I set up a sensor for each addon (which I have done) when installing/uninstalling addons, the sensors need updating
i am trying to pull the 'message' from a service call. specifically I have an event trigger for an automation that fires each time 'tts.amazon_polly_say' is called. I am trying to pull the 'message' from that service call using
{{ trigger.event.data.service_data.message }}
i know that is wrong but i can't figure out what else to try. ive tried just trigger.message and many others. any ideas?
If you listen for the event in
-> Events, what does the structure look like?
{
"event_type": "call_service",
"data": {
"domain": "tts",
"service": "amazon_polly_say",
"service_data": {
"entity_id": "media_player.volumio_mpd",
"message": "test of the thing"
}
},
that actually looks okay to me based on some of my own examples for other events
what does your automation look like?
getting this error
record tts to file: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'homeassistant.core.Event object' has no attribute 'service_data'
While executing automation automation.record_tts_to_file
record tts to file: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'dict object' has no attribute 'message'
record tts to file: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'dict object' has no attribute 'data'
automation is
- alias: record tts to file
trigger:
- platform: event
event_type: call_service
event_data:
domain: tts
service: amazon_polly_say
action:
- service: notify.tts_recorder
data_template:
message: "{{ trigger.data.service_data.message }} {{ states.sensor.formatted_date.state }} {{ states.sensor.local_time.state }}"
really seems like it should be working. ha
here's an example of mine:
oh i just got it haha
value_template: "{{ trigger.event.data.control in ('DON', 'DOF') }}"
{{ trigger.event.data.service_data.message }}
yeah, exactly
thanks man
that's exactly what you had above?
{{ trigger.event.data.service_data.message }}
why did it work this time haha
to which I replied, "yeah, that seems about right..."
i must have done something dumb like forget to reload the automation or something
or tried it again too soon
well, glad it's working
yeah me too, thanks
so just {{ SerialReceived[-4:] }} is all he needs then Tediore?
no ?
Hard to say without context. If that value is stored in a sensor, you just need to reference the sensor itself
{{ value[-4:] }} ``` where `value` is a reference to the sensor that has that value
@buoyant pine worked perfectly thanks!
not sure is this is the right place for this question but it sort of relates to templating. I have this {% if (as_timestamp(now()) - as_timestamp(states.switch.kitchen.last_updated)) < 10 %} line but if i press the switch the timestamp does not change
so its always false
the kitchen switch is a momentary one, so it's only "on" for a short while, but does that matter? The state change should still be logged right?
@inland crypt That won't ever update in a template sensor, switch, etc. That will only be correct if it's a condition in a script or automation.
Good morning! I can't seem to make this damned template work. Looked all over the web. You folks can probably spot the error a mile away. Basically this is going in the middle of a notification to Alexa.
`
data_template:
message: >
{% set diff = states('sensor.indoor_v_outdoor')|int %}
{% if diff > '0' %}
warmer
{% elif diff == '0' %}
the same
{% elif diff < '0' %}
cooler
{% endif %} ``
data_template: message: > {% set diff = states('sensor.indoor_v_outdoor')|int %} {% if diff > '0' %} warmer {% elif diff == '0' %} the same {% elif diff < '0' %} cooler {% endif %}
Sorry
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 were close the second time, you just need three backticks instead of one (you can also edit messages)
here's an alternative btw:
data_template:
message: >
{% set diff = states('sensor.indoor_v_outdoor')|int %}
{% if diff > 0 %}
warmer
{% elif diff < 0 %}
cooler
{% else %}
the same
{% endif %}
@north helm
no prob. when you put quotes around something it turns it into a string, but you want it to be a number
de nada
I have a follow-up if you're willing....
type: tts
message: >-
It feels like {{ states ('sensor.smartweather_feels_like')|round(0) }} degrees
out. {{ states('sensor.indoor_v_outdoor') | round(1) | abs }} degrees
{% set diff = states('sensor.indoor_v_outdoor')|int %}
{% if diff > 0 %}
warmer than inside.
{% elif diff == 0 %}
the same as inside.
{% elif diff < 0 %}
cooler than inside.
{% endif %}```
I'm getting an annoying pause between the word "degrees" and the conditional message.
TTS isn't really this forum, though, is it?
not really but how about a delay of some sort until it works out the math?
Just change the order of operations, maybe? Put the 'variable degrees' in the conditions?
Even better!
I used to run into this issue with call centers often
the metrics would hold up the auto-attendant so in some cases I just did the math before the announcements 😄
same principle applies 😄
but then again Avaya vectors are almost my native language LOL
hehe
I'm so used to calculations being almost instant in Cherwell that it never occurred to me that basic comparisons could be a bottleneck.
But it makes sense.
well my mind works on basics for the most part LOL
I try to break things down into little smaller problems instead of running after windmills with my sword 😄
BTW did you try data_template: ?
Very good thinking, Senor Q
😄
Originally, yes.
I completely suck at templates BTW
Oh wait.... Do you mean make a new sensor that's a data template?
😉
So it's basically pre-calculated...
I likes it. I likes it!
you probably know way more about templates than I do as I said 😛
Not at all.
I wrote my first one yesterday or day before .....
I've never had a use for them until now
Good thing I have some downtime right now to play with this new idea.
I did a lot of things in node-red directly, but since I'm trying to learn automations in HA... I deleted everything from Node-red and I'm starting from scratch in automations and templates
when I tell you I'm dumb you should believe me 😛
if mono tells you I'm dumb you should believe him too
lol
Now if only I can get my automation to announce this when the state changes from negative to positive in time for it to actually test when the temp changes!
😛
well my one template was on sending telegram messages to my phone when the weather state changes at home
so maybe right up my alley LOL
I'm sick of guesswork on when to open and close the windows.
So.... Which of us is dumber?
this is why I have the weather sent to my phone via telegram
so I can know if it's rainy and shut the windows
I'm going with the guy who needs to be told that it's warmer outside.
Rain is different
Let's have a headbutting contest!
who deletes a working system to figure it out all over again in another way
< this dummy
That's pretty bad.
Let's have a headbutting contest!
@north helm I warm up on concrete just FYI
It's drastic, but it's motivating!
Hi, I recently made a fan.template so I can controll my AC thru homekit- it all works great. But I saw an error in my logs:
`Logginformation (WARNING)
Logger: homeassistant.components.homekit.util
Source: components/homekit/util.py:315
Integration: HomeKit-brygga (documentation, issues)
First occurred: 16:39:34 (1 occurrences)
Last logged: 16:39:34
['quiet', 'low', 'medium', 'medium_high', 'high'] does not contain the speed setting off as its first element. Assuming that quiet is equivalent to 'off'`
does it mean i should put 'off' in front of quite?
try 'off', 'low', 'medium', 'medium_high', 'high'
Getting a different error now
sensors:
difference:
data_template:
{% set diff = states('sensor.indoor_v_outdoor')|int %}
{% if diff > 0 %}
{{states('sensor.indoor_v_outdoor')}} degrees warmer than outside.
{% elif diff == 0 %}
the same as outside.
{% elif diff < 0 %}
{{states('sensor.indoor_v_outdoor')}} degrees warmer than outside.
{% endif %}```
Is returning:
found character '%' that cannot start any token
in "/config/sensors.yaml", line 363, column 10```
Line 363 is the first line after "data_template:"
you may need to double brace
or quote
column 10 is likely the first % on 363
{%
Where would the close brace go, then? After the {%endif%}?
im pasting your temple piece by piece into the tester
try {% set diff = states(('sensor.indoor_v_outdoor'))|int %}
that stopped my error
actually
I think that's me being dumb again
yeah so nothing I did seemed to be right
Me either.
not to worry, someone will show us the ignorance of our ways, possibly calling us dumb also
{}'s for it
@north helm @cerulean cipher data_template: needs to be value_template:
and you need a > if it's multi-line (like it is)
see Denver, I told you we're dumb
well you knew this about me already
sensors:
difference:
value_template: >-
{{% set diff = states('sensor.indoor_v_outdoor')|int %}
{% if diff > 0 %}
{{states('sensor.indoor_v_outdoor')}} degrees warmer than outside.
{% elif diff == 0 %}
the same as outside.
{% elif diff < 0 %}
{{states('sensor.indoor_v_outdoor')}} degrees warmer than outside.
{% endif %}
}```
Tried it as value_template :> and value_template: >-
remove the extra braces at the beginning and the end
and I always indent the template block by 2 spaces
heh, was just about to say that
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
{{% is not valid
so instead of one person calling me dumb we got everyone out today 😄
indent everything under value_template: > two spaces like rob said
Oh, blessed relief! That was it!
Thank you everyone! .... Except @cerulean cipher
😛
You kept setting us up for it.
I did make a disclaimer that I knew less than you did about the templates 😛
so I outlined that I'm dumb but willing
😛
I either have really good ideas or really bad ones, not much in between
and often the bad ideas are more common
than the good
Well, I've learned a lot this morning!
Of course, this is all preliminary to @cerulean cipher 's idea to remove the pause in my announcement.
I'm excited to see if at least I helped in some way other than to obfuscate things
But the value of the new sensor is "6.4 degrees warmer than outside."
@north helm well that's a step in the right direction no?
so this maybe my second win today
I'd better get back to actual work that I'm getting actually paid for.
Thanks again all!
paid? Error, process not found.
Can you do a character return in a templated message?
newline? yeah, i have this as part of a template:
+ '\n'
seems to depend on whatever is ultimately rendering the output though
could be. this works for me:
test:
sequence:
service: persistent_notification.create
data_template:
message: '{{ "test test\ntest2 test2" }}'
but I also recall there being forum messages exhibiting weird and inconsistent behavior
thanks, i'll give it a go
Hello everyone! Looking for a jinja guru to streamline an integration of 17track. How can I add a filter on the below template sensor to only look for entities that contain 'seventeentrack' ?
sensors:
seventeentrack_packages_not_found:
value_template: "{{ states | selectattr('state','eq','Not Found') | list | count }}"
try 'off', 'low', 'medium', 'medium_high', 'high'
@cerulean cipher
i have no 'off' in fan_modes:
here is my code:
speed_template: "{{state_attr('climate.hall', 'fan_mode')}}"
speeds:
- 'quiet'
- 'low'
- 'medium'
- 'medium_high'
- 'high'
hi, how to correctly round value in template sensor ? this works on template tab, but not in file , don't know why
value_template: "{{ (( as_timestamp(now()) - as_timestamp('2020-07-29 15:00:00'))/3600/24)|round(0) }}"
.share the full thing
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
- platform: template
sensors:
left_hospital:
friendly_name: "Doma z nemocnice"
icon_template: "mdi:timer-outline"
unit_of_measurement: 'days'
value_template: "{{ (( as_timestamp(now()) - as_timestamp('2020-07-29 15:00:00'))/3600/24)|round(0) }}"
that will never update as you don't have an entity in there
I'm talking about round that calculated value,. When I run this in template tab, the output is 26, but when this is in file, output is 26.29683224312409
should work, but you'll still have the problem i talked about so you should work on resolving that first
I've added entity_id sensor.date, and after restarting HA is result rounded
is there a way how to read value for entity from yesterday ? II know, that I can create another sensor and save current value at 23:59 to the new sensor, but that is not what I want
I've found history_stats but it looks, that it does not return value from selected time
hi, how do i set up a similar template for rgb_color instead of kelvin?
entity_id: light.entity
kelvin: "{{ state_attr('sensor.circadian_values', 'colortemp') | int }}"```
i have no 'off' in fan_modes:
here is my code:
speed_template: "{{state_attr('climate.hall', 'fan_mode')}}"
speeds:
- 'quiet'
- 'low'
- 'medium'
- 'medium_high'
- 'high'
@orchid onyx but you posted an error "['quiet', 'low', 'medium', 'medium_high', 'high'] does not contain the speed setting off as its first element. Assuming that quiet is equivalent to 'off'"
does not contain the speed setting off as its first element is why I told you to try putting off there
how to convert a sensor from bytes to TB? {{ states.sensor.bytes_sent | filesizeformat() }}/s would this work? I assume replace filesizeformat with GB?
yea I was looking at that
just guessing, since I hadn't seen "filesizeformat()" before
so just use the other examples that do real math
where filesizeformat is would I put the 1000000000?
nvm I think I'll try a few to see which one works 🙂
yes, something like that. depends on whether you want round numbers or binary
thanks 🙂 I'm still learning this stuff, I'm getting addicted to home assistant lol
hmm results showing up as 0 probably doing the formula wrong =/
this yields a non-zero result:
{% set bytes = 2000398934016 %}
{{ bytes|float / 1099511627776 }}
you're probably missing the |float
so it's converting to an integer or something
I have that one in there to
value_template: "{{ states('sensor.lances_nas_volume_free')|float / 1000 }}"
converting gb to tb btw I thought it was bytes at first
oh well now its working lol
magic
right? lol
hmm browser caching issue I think
anyone to reload the config.yaml without rebooting?
I was about to ask that
> Server Controls for the list of things that you can reload
and feel free to request sensor reloading 🙂
If you have a feature request for the frontend you can open one here, for Home Assistant itself please post on the forum. All other feature requests should be made to the developer of that custom card/component.
there's probably already a request
if I do a | round(0) will that take out the decimal places?
so if I have a result of lets say 89.978 how would I get rid of the .978? I assume round does it
{% set bytes = "3" %}
{{ (bytes|float / 2) |int}}
{% set bytes = "3" %}
{{ (bytes|float / 2) |round(0)}}
truncate or round, your call
thanks!
(parens matter)
I noticed the config yaml is very picky with lots of things lol
in this case, you want to filter the result of the division and not just the "2"
when I tried round it put me to 0 again, trying out int to see what it does
I'm testing all of that in
-> Templates
"{{ states('sensor.lances_nas_volume_free') | float / 1000 | int }}" like this right?
no, that's not what I wrote 🙂
like I said, parens are important, including where they are
you didn't use them at all
would I incase the senor name in with it as well?
put your sensor in place of bytes in my example
{{ (states('sensor.lances_nas_volume_free') | float / 1000) | int }}
your version is just truncating the 1000 and not the result of the division
I have lots to learn with this stuff
indeed. this is just order of operations in Jinja
but I have to admit that I usually just play around with it until I figure it out
and then back into "why"
thats pretty much how I work
poke it till it works then try to figure out how the gears turned
still getting a decimal value
trying float 🙂
err
round(0)
round did it
invaluable
that's how I was able to try three things at once 🙂
I'm just fumbling around in home assistant but I'm loving tying everything together into one place
I've got another puzzle for you. (You'd think I'd be better at this by now...) And this MIGHT be more of an #integrations-archived question. My end goal is to make persistent variables between restarts using the custom component variables and MQTT. My idea is to publish 3 values to a retain'ed MQTT topic. In my native environment, this is simplicity itself, but value_template syntax continues to elude me.
```
is my payload to MQTT
Well, my DESIRED payload
I’m not sure I can visualize the whole thing from that snippet. Seems like it would be easier to use separate topics
Good point. I think I'm just failing to grasp how to group the multiple sensors and their labels into a single object.
Sounds unnecessary. Topics are free
If payload: >- were what you're trying to group those into...
You’re over complicating this