#templates-archived
1 messages ยท Page 93 of 1
before i add my thing, does anyone have a cleaner way to go to the next effect of a light ?
effect: >
{%- set effect_list = state_attr('light.nanoleaf_01_chambreg', 'effect_list') %}
{% set effect = state_attr('light.nanoleaf_01_chambreg', 'effect') if state_attr('light.nanoleaf_01_chambreg', 'effect') else effect_list[0]%}
{{ effect_list[effect_list.index(effect)+1] if effect_list.index(effect) < effect_list|count-1 else effect_list[0]}}
could anyone help me with a sensor, trying to create one for use in a bayesian sensor but im seeing something weird
binary_sensor:
- platform: template
sensors:
lights_on:
value_template: >-
{{ states['light'] | selectattr('state','eq', 'on') | list | count > 0 }}
The template tester in the UI shows it as true when a light is on but when I look at the Develop tools states its always off
@shy badge posted a code wall, it is moved here --> https://paste.ubuntu.com/p/pF9xzXpRzZ/
Move sensors: to the left two spaces @shy badge
awww how do I post here? Bot moved my post?
A little help if I may . . . Trying to setup a power monitoring socket to alert when the washing has finished.
- platform: template
sensors:
washer_on:
friendly_name: "Washing Machine Status"
device_class: power
delay_on:
minutes: 2
delay_off:
minutes: 2
value_template: >
{{ states('sensor.washing_machine_energy_power')|float > 10 }}
so I think this is correct?
but I get this error
nvalid config for [sensor.template]: expected dictionary for dictionary value @ data['sensors']. Got None
extra keys not allowed @ data['washer_on']. Got OrderedDict([('friendly_name', 'Wasmachine aan'), ('device_class', 'power'), ('delay_on', OrderedDict([('minutes', 2)])), ('delay_off', OrderedDict([('minutes', 2)])), ('value_template', "{{ states('sensor.washing_machine_energy_power')|float > 10 }}\n")]). (See ?, line ?).
You don't need to repost it after it moved it...I also answered you above
Let's see the whole binary_sensor: section
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
@shy badge posted a code wall, it is moved here --> https://paste.ubuntu.com/p/7Mzr7fGHCx/
Please pay attention to the rules...I provided a share link above...
Also just move sensors: left two spaces, not everything else below it too
aww crap sorry . . when I move sensors: the config file errors with bad indentation of a mapping entry at line 21, column 3:
sensors:
^
Based on what you originally posted, move sensors: to the left two spaces, that's what I was saying. Also, that template sensor needs to go under binary_sensor: not sensor:
I don't understand ๐ฆ Ok I have now created binary_sensor and moved the code below that. If I move sensors: back 2 spaces (starts at column 3) I get the above error.
You are asking me to make the config look like this?
Oh boy, I think I fixed it. I had to move - Platform to the left
i'm saying do this: https://paste.ubuntu.com/p/QgV45nPP3W/
yeah, I got !!! Many thanks for your help and patients
Hi all, I'm looking to create a script which context aware switches channels on my TV. So if everything is off and I want to check channel 1, it first switches on the TV and DVR, if they are already on, it immediately switches to channel 1. I came up with this, but I can't get it to work: https://paste.ubuntu.com/p/j6Z9pKN8m8/
But Iโm not sure if using a script is the right way to, all tips are welcome ๐
so just a few questions
to process multiple rows yu need > or >-
as an example
message: >-
{% set ha_version = state_attr('binary_sensor.updater', 'newest_version') %}
{% set ha_relase_notes = state_attr('binary_sensor.updater', 'release_notes') %}
Update to version {{ ha_version }} available, see release notes.
this works for this case
but it also works like this
message: >
{% set ha_version = state_attr('binary_sensor.updater', 'newest_version') %}
{% set ha_relase_notes = state_attr('binary_sensor.updater', 'release_notes') %}
Update to version {{ ha_version }} available, see release notes.
so whats the difference?
the - removes whitespace which would make no difference in both of your examples so either is fine
perfect thanks for that
now
if i want to display a message on a few rows
i use |
example
message: |
- 1
- 2
- 3
this displays correctly
now what i want to do is on those rows to have multiple templates
|> or >| dont work
how do i do it?
i never tried that so ๐คทโโ๏ธ
๐
i mean i want to display multiple rows that contain templates
tried everything i could
at this point i can safely say I DON'T KNOW ๐ฆ
even tried \n
message: >
{% if trigger.to_state.state | lower == "something is wrong!" %}
{{ trigger.to_state.attributes.friendly_names }} has a problem Please Check Dashboard!
{% else %}
{{ trigger.from_state.attributes.friendly_names }} has been fixed!
{% endif %}
is a mulitline message template if thats your goal
i belive i've fix it
found something
only one space remaining that bothers me
๐
yep it's fixed
- service: notify.telegram_cip
data_template:
title: 'Home Assistant'
message: >
{% set ha_version = state_attr('binary_sensor.updater', 'newest_version') %}
{% set ha_relase_notes = state_attr('binary_sensor.updater', 'release_notes') %}
Update to version {{ ha_version }} available, see release notes.
{{ ha_relase_notes }}
in case anyone needs it
every white space counts ๐
anywhere i can parse current version of ha
to make a sensor with that
?
found some stuff
Is it not just the version integration?
sensor:
- platform: version```
How would i show these values in the sensor card instead of vm count
https://jozef.cf/x6ertmEOX0
memtotal gb
31.99
memusage gb
30.4
maintenance mode
false
vms
8
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)
make a series of template sensors extracting the attributes
NP
Hi, I would like to create a binary_sensor w/ a quite complex value_template. Can I use the "result value" somehow? Does it exposed? Can I reach the current value? Because...
(1) if I try to reach value by it's name, the icon will late with one refreshing-cycle
(2) I don't want to copy-paste the whole, huge jinja2 template into the icon_template also
(3) and I wouldn't like create another binary sensor for the UI...
Is it not just the
versionintegration?sensor: - platform: version```
@ivory delta yes found exactly that, ty
Hi, I would like to create a binary_sensor w/ a quite complex value_template.
@dry holly The result of a binary sensor is 'on' or 'off'. They're binary.
Feel free to create a sensor if you want other values for the state.
Hi @ivory delta, the result will be binary, but it's calculation involves several states. In the other hand, I have several sensor templates and binary_sensor templates, to I think I done the first steps, but I don't know how can I efficient get the "calculated value"
You can use YAML anchors to repeat blocks
YAML has a handy feature called anchors, which let you easily duplicate content across your document
yap, @arctic sorrel you could be right, but w/ anchors I can't inject the icon names - as far as I know - plus this workaround would be my (2), where the HA calculates the value twice
Then use a template sensor, and the results of that template sensor ๐คท
so, do you prefer the two binary_sensors solution?
I don't really care if HA calculates something twice ๐
I think most people prefer the most suitable solution to their problem. Your problem is your own.
Unless you're on a Pi2 or below, the overhead is unlikely to matter
I'd argue that the mental overhead is more strenuous than any computing overhead. DRY.
I'd hate to maintain the same template in multiple places...
Which is where anchors win
Of course, I maintain a horribly complex template in two locations, because I can't anchor it ๐คท
yes, but my programmer soul's crying... I imagine, the HA calculates the value_template w/ jinja2 and then it has to have that value somehow, that I can't reach from the other place??? really?
Do anchors work across multiple files? Does HA merge all the yaml files into a single structure before interpreting them?
I don't know... it'd be handy if they did, but you have to define them before you use them
that I can't reach from the other place???
@dry holly They can all reach sensors, right?
from the other place means from the icon_template
icon_template can't read sensors?
it can read, but if the icon_template refers itself, the icon will lagging w/ one ui-refresh cycle
I don't understand the problem. Share your code.
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
e.g. you define the binary_sensor.foo, and you want to use the is_state(binary_sensor.foo, 'off') in the icon_template the icon will lagging
Then use another sensor, or accept the insignificant overhead ๐คท
Lag? Not by any meaningful amount of time...
30s...
I do changes, the icon doesn't shows the right state, but I click on the badge, the state shows the right, however the icon in the popup still bad
and after approx. 30s will be the icon fixed
I have no idea how you've managed to introduce a 30 second delay.
Also... share your code.
๐คทโโ๏ธ
i'm working on to creating sample code... I ask some minutes
here is my 3 experiments: https://paste.ubuntu.com/p/Tgw56tCSjk/
ohh, I made a mistake in the line 78... so I wanted to write "{{ states(binary_sensor.i2big_dryable) }}"
Well it sounds like Tinkerer's suggestion of using anchors with option 2 is simplest.
so, am I right, the HA doesn't expose the currently calculated value to be able to use in icon_template?... sad
ok
and can you help how can I use anchor? because I don't want to copy the whole value of the value_template? because I would like to replace the True-False values to the icon names
Tinkerer already told you how, scroll up
If you want different output from each template, they're going to have to be different templates.
as far as I know, I can't concatenate yaml anchors, so I can select and past a whole key, a whole dict, ... but can't a part of a string.
so, if you check the suggested (2) solution at https://paste.ubuntu.com/p/Tgw56tCSjk/ the value_template is a bit different that icon_template (different that expressions in the return value)
or am I wrong?
If you want different output from each template, they're going to have to be different templates.
Yes, I see they're different.
ok, so I can't use anchors too ๐ฆ
thx
Hi. I have a MQTT sensor that shows me the power usage of my washing machine. If I turn off the washing machine it just shows the power usage before it was turned off. I have now added 'expire_after' to my config so that changes to 'Unknown' after x seconds. Just wondering if it's possible to have a value template to change 'Unknown' to '0'? I've managed to get a template to work in the dev part of HA but struggling to get it working in my yaml file
value_template: "{{ {% if value == "unknown" %} 0 {% else %} value {% endif %} }}" is what I have
depends on the sensor configuration, how does the mqtt message look?
unknown is probably sent grom HA when there's no mqtt data
Yeah it is. MQTT remains at just a number but the expire_after setting on the sensor changes it to 'Unknown' if not updated within x seconds
its should be closer to {% if is_state('sensor.dryer_energy_today', 'unknown') %}
That helps a bit. I'll give it a go
i do something similar for my dryer
@dry holly use the custom template card for icons. Problem solved.
Combine with decluttering card and you have a simple configuration
@mighty ledge, can I ask some help, because I'm new for custom template card and decluttering card?
@dry holly both are custom cards, install the HACS (home assistant community store), find the cards and install them. Once installed, they'll have documentation that accompany them.
Hi, hope you are having a lovely day.. quick question: I am playing with platform: template - sensors - is there a way to reload them without restarting HA? Thanks
No
@arctic sorrel Thanks.. I am having trouble with some templates not working.. so its a bit "inconvenience" to restart everytime i change ๐ฆ
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)
No need to restart to test ๐
The template was working in the template builder.. but when I put it in the config and restart, it wasn't showing up
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
Thanks Tinkerer..
is there anyway to template the "Unit of Measurement" attribute
I want it to be changing between kWh and MWh
No, the system expects a consistent unit
I'm getting an odd error in my validation step and could use another brain to think about it. When I re-add back the sensor for Garadget as an MQTT sensor, I use an icon_template. The validator says that icon_templates are not allowed for MQTT sensors (platform: mqtt). Is this something new with the recent changes on mdi icon loading?
I used it just fine around this time last year and can't find any references in the Releases Notes
Those have only been valid for the template sensor #integrations-archived AFAIK
Here's what I have:
I wanted to check here before running over to the #integrations-archived channel.
Well, I see nothing to indicate that MQTT sensors have ever supported icon templates
<shrugs> Me either. Makes me wonder why it was working in the first place. It was a "cut and paste" job from the Garadget forums to get it working. Okay. <scratches head> Wondering how to get the icons to work now.
Automation?
I'll give a whirl. Thanks.
Was trying to wrap my head around how to use the Template sensor to refernce the garage_door_mqtt sensor. I'm just going to write it and see.
Thanks.
So I worked on getting my sensors converted to imperial... damn us.... I use round to cut it down to 2 decimal points... is there any way force the full decimal points: EX: 2.10 vs 2.1?
current template "{{ (states('sensor.sensor_a_km')|float / 1.609344)|round(2) }}"
Not if you want to keep the value as a number afaict. You'd have to convert it to a string and concat a 0 on the end
I can do it in linux, sql and 20 other methods lol but i couldnt figure it out here
Try {{'{:.2f}'.format(states('sensor.sensor_a_km')|float / 1.609344)}}
replaced double quotes with single
should work i know thats same way i would use in linux, didnt know i could do the format in front
so thats crazy... home assistant automatically converted C to F for me, but didnt do km to miles? I went to do another template and it showed 191 F ๐
Just start getting used to the superior measurement system. Fuck imperial ๐
Nothing wrong with a small measure of imperial. That said, us Brits only seem to like it for speed and distance (yes, we're strange).
i want to create a new template sensor that will be the number of seconds between each time another sensor is in the on state
any suggestions on how to do that?
so this new template sensor should be updated every time the other sensor goes into the on state and then calculate the number of seconds since the previous time the other sensor was in on
well, yes.. which in turn tells how long between each time it's on ๐
Then that's an automation, not a template sensor, since you need the previous state object
https://www.home-assistant.io/docs/configuration/state_object/ - you'd be using from_state.last_changed
and this value should be stored into an input_number?
that's the "best" datatype for this kind of use case?
Or an input datetime - up to you
what i want presented is the number of seconds between each trigger.. because i want to be able to visually see if this is increasing og decreasing
Then a number type is the simplest
There's also a trend sensor that can help you here
oooh
maybe i can use that directly instead of trying to set this up myself?
this will be trending on a binary sensor
That may be harder, the trend sensor isn't designed for duration trends AFAIK
ok, so then i guess i have to use a number type that will constantly update with the number of seconds
and i can then just view the historic values of this number type to see the trend
I'm trying to fire an event as part of an action in a template media player. It doesn't seem to like the "event" action type.... should it work?
commands: turn_on: event: event.my_custom_event
You'd have to have a script that did that
Hmmm - OK..... why? The docs imply that template 'actions' should follow the 'action' format, which supports event, no? (Trying to ascertain whether this is by design, with some logic behind it, or just not yet implmented)
yep
action: in an automation is the script syntax
None of the commands in that integration use the script syntax
hey there i want to see my battery level of some sensors ?
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
sorry
โ๏ธ Show us the code as well as the error ๐
value_template: '{{ state_attr('sensor.[17a00cbcfdd54f82829b46478004c40e]', 'battery') }}'
^ ^
Those are your problem ๐
hm
Turn those two into "
There may be other issues, but that's at least one of them
oh stupid ๐
its fine
no errors anymore
i followed an howto ๐
they told me it has to be like that ๐
but idd " ๐
lets see if the battery level works ๐
Generally speaking you need one of " and ' outside and the other inside
Treat them like "wrappers"
ok
so it has something to do with the outside needed to be " if you use ' on the inside like on 'sensor.[17a00cbcfdd54f82829b46478004c40e]'
i think i understand ๐
maybe you know it does every sensors like the sonoff dw1 window sensor has an battery level ?
i tryed it to read the battery level but it seem like it doesn't work ๐
Well, there's either going to be an attribute of the sensor, or a separate sensor ๐คท
I don't have any Sonoffs though
Hey pros, I created 3 templates to count how many lights are on/doors are open/plugs are on but the template isn't updating in real time. It's working though as I restart HA it takes the correct information.
These are the templates, any advice?
https://pastebin.com/m6cf84z5
@gusty nimbus check developer tools > states for a battery level state attribute attached to the sensor, or a separate battery level entity for that sensor
i have like 8 fire detectors
connected to sonoff RF bridge
and 3 sonoff DW1 (window sensors) (that have battery)
i don't find anything usefull in that states telling something about an battery on that devices
@high crater: give me the JSON your sensor is reporting and I'll show you how to parse it.
Use the backtick formatting (`) though, so it maintains the invalid JSON.
https://paste.ubuntu.com/p/P7C3G7yGjc/ here is the output, I want to extract severity, event, and headline so I can match it in jinja
its too big for backtick
brackets are my weakpoint I still havent figured out how to tackle crap like this sensor outputs
The best I got was getting the first I'd to output using regex matching
Just the words id lol
{{ sensor['severity'] }}
{{ sensor['parameters']['NWSheadline'] }}```
Very easy bud. Much easier to read if you just chuck it through a JSON formatter/linter, then you can see the structure very easily.
Only issue is 'headline' returns ['HIGH RIP CURRENT RISK REMAINS IN EFFECT THROUGH LATE TONIGHT'], so you'll need to clean it a bit.
that ouputs nothing for me ๐ฆ
You need to replace "sensor" with whatever your sensor is.
that list comes from states.sensor.noaa_alerts_flz204.attributes.alerts
the actual sensor state is just a number
So I believe what you want to replace sensor with is states.sensor.noaa_alerts_flz204['attributes']['alerts']
Or event just sensor.noaa_alerts_flz204['alerts'] if it's an attribute of the sensor.
I got {{ states.sensor.noaa_alerts_flz204['attributes']['alerts'] }} to output the same thing but adding severity or events does not work
Try {{ sensor.noaa_alerts_flz204['alerts'] }}
no dice
{{ states.sensor.noaa_alerts_flz204['attributes'] }} spits out a bit more info I may be able to use
https://paste.ubuntu.com/p/zcJ2dgMbSt/ output from that
{{ states.sensor.noaa_alerts_flz204['attributes']['headline'] }} spits out the headline but severity still is not working
Rip Current Statement issued May 26 at 3:22PM CDT until May 27 at 6:00AM CDT by NWS Mobile AL
thats the output from the last thing I posted
yup got it, thanks for your help!
title: {{ state_attr('sensor.noaa_alerts_flz204', 'headline') }}
severity: {{ state_attr('sensor.noaa_alerts_flz204', 'alerts')[0].get('severity') }}
Of course, didn't even click that they're just attributes of a sensor. ๐คฆโโ๏ธ
OMG Thank you, I dont know why I didnt try state_attr saw the brackets and got confused I guess. You both have been a big help
now I can write my weather announcment automations again
how did you know to add the [0].get('severity') part?
The trick is that the alert context is in a list, so unless you are fine with the top attributes of the summary you need to navigate to the first (0) alert, this works fine when there are 1 alert, but does not give the correct data when there are more.
The "get" part is just a safer method of extracting values from a dictionary
so how would I get more than one alert? the sensor state will show multiple alerts but I believe the latest alert will be the most recent, or the last in the list
The alert attribute (which is a list) will contain multiple dictionaries, one for each alert
so for a second alert it would just be [1].get('severity')
But that will fail when there are only 1
yeah, im going to hope my first assumption is the way it works for now, if not ill have to iterate through a list and use the last list value
For the last entry in a list, you can use [-1]
awsome!, sounds like I dont have to hopefully
states: sensor will return the number of current alerts, attributes will be the 1st most severe alert, with exception of alerts_string. Naming format is noaa_alerts_<your zoneid here>
from the github
Would recommend thoroughly reading the templating documentation in any event @high crater (https://www.home-assistant.io/docs/configuration/templating/). Jinja supports for loop, so you can create a string consisting of all alerts easily.
I need to up my for loop game lol, im great with if/else but for just breaks my brain for some reason ๐
Well, if {{ state_attr('sensor.noaa_alerts_flz204', 'alerts') }} returns a dict, you can just iterate through that.
true
Question; I have a motion sensor which I use to trigger multiple automations (based on time). I would like to add an intermediate switch so I can turn of the motion sensor completely (state checked in automations).
But if I check my options; Template Switch, MQTT Switch I see that I always need an on and off action. Is there another way to create a Switch without these actions or do you maybe have other tips to accomplish this?
โ๏ธ Much simpler ๐
ahh, sometimes I think way to complex ๐ฅด haha thanks!!
Hey Pros, I'm trying to show in a markdown card if the alarm is armed or not but I get the output "The alarm is unknown armed"
This is the code in config and lovelace: https://pastebin.com/ek6E7mnp
Any advice will be greatly appreciated ๐
We can add AND statements into our logic right? I didn't see specific mention of it in the docs?
{% if is_state_attr('calendar.trash_schedule','message','test') and is_state('calendar.trash_schedule','on') %}
I need the and otherwise it will give me a positive for the message since it's looking at the next item in the calendar even though it hasn't occurred yet.
yes
๐
Hey Pros, I'm trying to show in a markdown card if the alarm is armed or not but I get the output "The alarm is unknown armed"
This is the code in config and lovelace: https://pastebin.com/ek6E7mnp
Any advice will be greatly appreciated ๐
@wary helm I'm no "Pro" but I'm confused why you have theentity_id: sensor.timeIsn't your template sensor going to be sensor.alarm_on ?
Yes, that's included, the sensor.time is to update the sensor in realtime
otherwise it wont update unless you restart
and it still only updates every minute with the sensor.time unfortunately, so not really in realtime
Ah, cool. Learned something new.
What does the entity sensor.alarn_on tell you its value is in config/entities or developer tools?
"armed" so I changed that and changed a bit on the layout, now it works
although I'm still looking for something to update it in realtime ๐
now it works
I'll take full credit, thanks! ๐
Haha, take it. thanks ๐
Can a template sensor be updated in realtime? Does anyone have this working?
That would already be a great improvement
right now it's updating every minute with sensor.time added
What is in your template?
Why are you using sensor.time at all?
because it wasn't updating at all
with adding the sensor.time, it updates every minute
Even if you added alarm_control_panel.home_alarm in the entity_id section?
Even without any entity_id line it'll update when alarm_control_panel.home_alarm changes
should update
I'll try
So, with adding the alarm_control_panel.home_alarm in the entity_id section, it works. without an entity_id it doesn't want to update.
Anyway, a big thank you to you guys!
Sorry, spoke to soon, without the entity_id it's now also doing the trick
If you're having problems with your updates to your configuration:
- Check the troubleshooting steps
- Check your log file - remembering you may need to set logger to
infoordebug - Explain what the problem you're having is - sharing configuration, errors, and logs
I'm using the smhi weather service and is trying to figure out how to get the next days precipitation. How would one go about achieving this when forecasts is shown in date format and not just "day1,day2" etc?
Here is how it looks https://hastebin.com/esobekehiz.bash
{{ state_attr('weather.smhi_home', 'forecast') }} gives me the forecast list ofc. Can I somehow specify it to be the 2nd entry?
{{(as_timestamp(now())+ (86400)) | timestamp_custom("%A",true)}} would give you tomorrows date I think (86500 seconds in a day). No idea how you use that with the forecast though.
@sinful ridge Thanks but I'm not sure where to put it hehe
{{ state_attr('weather.smhi_home', 'forecast')[1] }} should give you the second entry in the array (0 index)
{{ state_attr('weather.smhi_home', 'forecast')[1].precipitation }} should give you what you're looking for
Wow! Thank's a bunch
sup guys ๐ question from my wife;
We recently build a pond in the garden and she wants to know the total liters of water pumped through the filters.
the pump is a regular'dumb' 2500liter/h model, but it's connected to a smartplug that I have available in HA.
I was thinking to make a sensor that checks the time the pump is on and converts that to liters, how would I make something like this ?
Basing it off runtime would likely be wildly inaccurate, but you could make an automation that adds to an input_number
for now runtime based is the only option we have without getting additional stuff ๐
thanks I'll check that out ๐
I think this is a template question. I have an automation where I get a notification from pushbullit when my battery is too low/high. Can I prevent getting duplicate notifications once pushbullit has pinged?
Is it using a state template? If so, it should only trigger when the state passes the threshold value you've set.
If it's firing more than once, it's possibly fluctuating and crossing that threshold more than once.
You can use an input_boolean as a filter. Turn it off when the notification is sent, and on when the battery gets to a certain level
There might be more than one solution. In this case, it means understanding the template before improving your automation ๐
You can use a template to see when an automation last triggered ๐
What madness is this? Next you'll be saying you can use that information in a condition!
Dang! I'm not able to give you guys ๐
This is HA, there's likely at least two other ways of solving a problem beyond what anybody has thought of yet
I'm looking at someone else's templating to understand it better and this has me confused.
https://paste.ubuntu.com/p/4wW4vvw5Jd/
Why in the first two line is the calendar defined with the calendar name using "['recycling2'] and in the other lines it's defined as how I would expect calendar.recycling2.attributes.start_time?
So in the first line could also be {% set pickupday = strptime(states.calendar.recycling2.attributes.start_time, "%Y-%m-%d %H:%M:%S").strftime("%A") %}?
I am. having other issues which I'm working through with the teamplating but I couldn't understand the reason to have it done that way.
I deleted my templates from the config file and they are still showing and reporting history. I have restarted HA ad did a full system reboot but still there
The entities (they were sensors) are not showing in the entities tab
Removing entities does not remove them from history
Give it a week or two and your DB should have purged all records of them
is it normal for them to be continuing to report there status? i.e, i just swtiched something on and it reports in history event though its been deleted from HA
Template sensors? If they aren't in dev tools > states then they shouldn't be reporting history
Yep. They arn't in dev tools but reporting history
Where are you seeing them change state?
within history when i hover over them
Is there a way to force the db to update?
/ purge
Are you talking about the history panel or card? What were the templates and what state are they reporting?
@dreamy sinew It does work with either formatting. Cool, albeit slightly confusing to idiots like me trying to learn templating ๐
There is a recorder.purge service
Are you talking about the history panel or card? What were the templates and what state are they reporting?
@hollow bramble history panel
And the second question?
It was a template that pulled the battery status from my vacuum. I only have a vaccuum.robovac entity in HA and needed a way to see the battery as a sensor. I have since delete the template and sensor... let me see if i can find the template again
I'm not sure how "switching something on" would change the value of that sensor. You're saying it's still changing state?
it was something like:
sensors:
robovac_battery:
value_template: "{{ state_attr('vacuum.robovac', 'battery_level') }}"
friendly_name: Robovac Battery Level
unit_of_measurement: '%'
icon_template: mdi:battery-charging```
What is the value of the sensor changing to/from?
i press go on my robot vacuum and wait a couple of minds and the sensor changes from 100% to 99%, 98% and so on. I return it to the dock and it i see it go up again
Ohhh wait, after a full system reboot it has stopped reporting the state LIVE but it is still there
i also did one from the washing machine plug which is there too (but also deleted this at the same time i deleted the above)
A system reboot is always unnecessary if you're just making changes to configuration.yaml
I've been struggling with a template for 45 minutes and the failure was I forgot the line: value_template: >- ๐คฃ ๐คฆ The complicated part was right all along!
It will show in history as long as there is record of it in the database. If it's still changing state then that's a bug, but now you're saying it's not changing state
It doesn't seem like either of them have changed states for hours
the Eufy Battery and the Eufy Battery Charge Off were automations - you can see they have been deleted. The one in question, is the Washing Machine and the Robovac Battery Charging
Sensors and automations are recorded differently in history
either wait until your next purge cycle or purge your database manually
Okay thanks..... i'll keep an eye for it and see if they drop off over the next couple weeks
Actually, i might call the recorder.purge service with the following? purge_keep_days: 5 repack: true
That's not going to clear any records from the last 5 days
according to your screenshot your sensors were reporting a few hours ago
Still having some issues with the math. In this example I found the first if statement is determining if the event is today by taking the start time and subtracting the current time. The times are divided by 86400 so I assume they want this done in days. The comparison is if start day - current day == 0.0 then it must be today. Makes sense except you never get exactly zero! You get small decimals (negative if the event was today as the start time would be midnight). This would work if it were <= I think. Or does "== 0.0" mean some rounded value?
https://paste.ubuntu.com/p/FX5x6yTgBz/
Current time / 86400 is going to be a decimal in most cases, since computers typically do time in milliseconds.
Make sure whatever you're doing is starting out with seconds or round it afterwards.
I was creating a sensor that was 90% the same as the above example so I used it as the basis. Troubleshooting someone else's template is harder than making one from scratch (almost, I'm just starting to understand templates so I need an example to follow to get the outline right). Anyway, it was a good learning task. I understand the formatting and math logic a lot better after working through it all and playing with the templating tool.
@sinful ridge I was helping the guy who made that template and he 100% did not listen to my advice to fix it. I wouldn't use that template. In that thread there's an example that handles all the days properly.
{% set bin_time = as_timestamp(states('sensor.green_bin_2')) %}
{% set midnight = now().replace(hour=0, minute=0, second=0, microsecond=0).timestamp() + 86400 %}
{% if bin_time <= midnight %}
Today
{% elif midnight < bin_time <= midnight + 86400 %}
Tomorrow
{% elif midnight + 86400 < bin_time <= midnight + 2*86400 %}
{{ bin_time | timestamp_custom('%A') }}
{% elif midnight + 86400 < bin_time <= midnight + 7*86400 %}
{{ ((bin_time-midnight) // 86400) | int }} days
{% else %}
unknown
{% endif %}
I love seeing how people solve the same thing differently to the way I'd do it, always learn something new
Only 13 ๐ค
The difference with that solution and the solution marked in the thread is that there's only 1 time conversion and the rest is math.
ยฑ47
I've always wondered why the trash day changes, I've never lived at a place it wasn't on a set day
It's nominally on a set day here, but what is collected changes, and sometimes things happen (like public holidays) that cause things to move
It's nominally on a set day here, but what is collected changes, and sometimes things happen (like public holidays) that cause things to move
Same here. Normally my trash is picked up every other week and the two other recycling bins are collected on another day that alternates every other week. Any week there's a holiday it gets moved around too. There are enough holidays that I'd say 20% of the weeks there's a change in day. Enough that using a simple reocurring event doesn't work.
trash and recycling are picked up every Wednesday morning here. Very seldom is there a holiday on a Wednesday
@sinful ridge I was helping the guy who made that template and he 100% did not listen to my advice to fix it. I wouldn't use that template. In that thread there's an example that handles all the days properly.
Cheers @mighty ledge . I think I got it working but I haven't verified the operation 100% once it cycles to the next bin. I have it showing the colored bin in an picture-entity card and then also on another card it shows the colored bin for the next bin pickup and the day of the next pickup:
https://imgur.com/a/Lu7GDxv
My templates: https://paste.ubuntu.com/p/5b5SfFMyyn/
I like your code a lot better. I'm updating mine with that logic.
@sinful ridge That code is just what he wanted. The %A that you see for the 3rd day is the name of the day. It's a nice template. You could always extend it to show the day up to 6 days out by changing the multipliers on the 86400
I understand that part and I liked how that part worked.
My issue using the code you posted above is that first line where you set the bin time. For me I was doing that from a calendar and it's a sensor in the code you posted.
PLaying with the templating tool to see what I need to put in there.
It's not liking the as_timestamp (or what I'm giving it for parameters, more likely).
I'm trying to give it the calendar attribute start_time
@sinful ridge post screenshot of the sensor & attributes in imgur from the devtools
-> states page.
also tag me if you can
@mighty ledge There's not much there: https://imgur.com/a/b7Aw3m0
My issue using the code you posted above is that first line where you set the bin time. For me I was doing that from a calendar and it's a sensor in the code you posted.
@sinful ridge My comment was in regard to this. Post the sensor/calendar that you want to use for the date and I can help you tailor the code I posted
ha!
One sec
https://imgur.com/ZxtRKi2 Blacked out my address.
All the events are in a full-day events. I have another template sensor "sensor.tonnetype" that determines the type based on the event message.
Aroo! @mighty ledge (you said to tag you, I'm not expecting you to fix my code)
I think I need to add this after set bin_time = strptime(states.calendar.trash_schedule.attributes.start_time, "%Y-%m-%d %H:%M:%S")
The output from that is "2020-05-28 00:00:00" since it is a pick up day today
Or actually, this: as_timestamp(strptime(states.calendar.trash_schedule.attributes.start_time, "%Y-%m-%d %H:%M:%S")) That gives my the decimal output that I think we're doing all the math with.
@sinful ridge That would be the correct format. But as_timestamp should work with that without needing the strptime
let me verify
The difference is exactly 1 day (86400)
Which makes sense
{% set bin_time = as_timestamp(state_attr('calendar.trash_schedule', 'start_time')) %}
{% set bin_time = as_timestamp(state_attr('calendar.trash_schedule', 'start_time')) %}
That looks simpler
in the end this would be your template
{% set bin_time = as_timestamp(state_attr('calendar.trash_schedule', 'start_time')) %}
{% set midnight = now().replace(hour=0, minute=0, second=0, microsecond=0).timestamp() + 86400 %}
{% if bin_time <= midnight %}
Today
{% elif midnight < bin_time <= midnight + 86400 %}
Tomorrow
{% elif midnight + 86400 < bin_time <= midnight + 2*86400 %}
{{ bin_time | timestamp_custom('%A') }}
{% elif midnight + 86400 < bin_time <= midnight + 7*86400 %}
{{ ((bin_time-midnight) // 86400) | int }} days
{% else %}
unknown
{% endif %}
It didn't work then I realized I copy/pasted the code into the wrong sensor and borked them both ๐คฃ I'm glad I keep text file backups when I'm doing all this debugging.
Yep, reboot: working!
Nice
Cheers. If you ever make it to a DACH region Spartan race PM me and I'll buy you a beer.
DACH?
Germany (DE), Austria (A), Switzerland (CH)
I have a season pass this year that i'll be able to use exactly 1 time
Spartan race? Aren't those the insane ultras across mountain paths?
yah, super fun if it's your thing
All of ours got postponed to very late in the year. I think there are like 5 in as many weekends near the end of the year. Doing a Trifecta on sequential weekends and the European Championship might kill me.
They look amazing but I'm nowhere near in shape for one. ๐ฆ
They extended the season pass for US holders into 2021, I'm assumign they did the same world wide
@ivory delta you're putting it on a pedestal
try a sprint, not too hard
#the-water-cooler bois ๐
Oops ๐
I don't have a season pass, I just signed up for three early on and they all got postponed to within a one month period in October ๐
I AM ABOVE THE RULES
Sorry
You're good, it's @mighty ledge 's fault
lol it's true
๐
Hi..The other day I asked about converting
oops hit enter too soon...
The other day I asked about the total liters of water pumped through my pond.
The pump is a regular'dumb' 2500liter/h model,connected to a smartplug that I have available in HA.
I was thinking to make a sensor that checks the time the pump is on and converts that to liters/h
Villhelm pointed me to an automation with input_number, i tried but failed misserably... can anyone shed a light on this for me?
There's a history statistics sensor that can give you how long something was on for
ah awesome, thanks! that looks like what i need ๐
and converting the time its on to liters per min/hour is done with a template?
Yeah
What can cause the effect that sometimes my templates aren't receiving a new state. It works 50% of the time. Like now, the count template isn't receiving any state changes unless I restart HA.
https://hastebin.com/qohuletona.coffeescript
You're not calling entities directly in the first one so ha doesn't know to update it
It worked fine, as in realtime, yesterday with the same line of code. The day before it didn't work either. I'll try adding an entity_id in
How would I add in the entities, as a list or a string?
List, always a list ๐
I'm getting the error: Invalid config for [sensor.template]: [entities] is an invalid option for [sensor.template]. Check: sensor.template->sensors->lights_on->entities. (See ?, line ?).
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
does the template work in the editor? checked - works fine
Otherwise the error is prittey conclusive: [entities] is an invalid option for [sensor.template] get rid of line 3-9
Well, yea, that's what I had before but for some reason it's not updating my states
Oh, i'll try that @arctic sorrel
Works! Thanks!
Three digits after the decimal point?
as an example this one
"{{ states('sensor.heiman_smartplug_1_electrical_measurement')|float / 1000 }}"
yes @arctic sorrel
|round(3)
cool let me try it
"{{ (states('sensor.heiman_smartplug_1_electrical_measurement')|float / 1000)|round(3) }}"
doesnt seem to do anything that round
"{{ (states('sensor.heiman_smartplug_1_electrical_measurement')|float / 1000)|round(3) }}" = 0.0704
if i chage the number
get same resoult
0.0704
what i'am doing wrong
{% set test=704 %}
{{ (test|float / 1000)|round(3) }}
``` works for me ๐คท
ye
i wish you could see it is very wierd
if i do set like you and give the exact sensor value
results are different
๐
take a screenshot and post it on imgur
Is it okay to ask a question pertaining to JS templating here? I am using it with the custom-template-card.
#frontend-archived is better
Ouki ๐
is it possible to reference other sensors outside of the one that is triggered? https://paste.ubuntu.com/p/kXRNRFvHPN/
thanks!
is it possible to reference a secret value (from secrets.yaml) inside a template?
No, but there are some custom components that allow you to do it
Alternatively, make the entire template a secret
Doesn't help of course if you want to use the same value in multiple templates
is it possible to reference a secret value (from secrets.yaml) inside a template?
@fast steppe You could reference a secret from an input_text, and use the input_text's value in a template ๐
ooh good idea
Not perfect, but it works and means you can re-use that secret elsewhere if needed.
Don't forget to also customise the input_text to be hidden so no-one can see it on your screen.
In my input_text:
initial: !secret address_home
In my customize.yaml:
hidden: true```
The hidden option doesn't do anything anymore
That was for the old UI
You can, however, set the input text to password mode. Supposedly that does something
I haven't tried it without the hidden option but it's most definitely hidden from my default dashboard (Lovelace controlled). I didn't set password mode.
You're talking about a generated lovelace view?
Yus
Yikes. Okay I guess it does still work on the generated view for those that use it
๐
If it's deprecated, I haven't come across anything yet to say so. Granted, I'm new to this...
The documentation could be a little clearer on what hidden is supposed to do. People are often confused about that one
It used to be more relevant when the only UI option was generated
I just made a PR to the customize docs to clarify the option
Hi! What's the current go-to-method for a simple HTML parser sensor? I need to get the percentage out of this: https://zenit-auslastung.labor.byteways.de (<input type="hidden" id="auslastung" value="36">)
@lone rain What about this? https://www.home-assistant.io/integrations/scrape/
It lets you scrape a page, specify a selector (and even an attribute, as you've requested), and then template the response along with an optional unit of measurement.
And a tip: Googling 'home assistant x' usually does a good job of finding 'x' that works with Home Assistant. 'home assistant screen scraping' and 'home assistant parse html' both return that link as the first result.
Hi, I am novice by Home Assistant. I need help for simple comparison. I have two temperature sensor temp1 and temp2, I need third measurement which show smalest measuremet from temp1 and temp2
You want this https://www.home-assistant.io/integrations/min_max/
Hmm. thanks I test ๐
thx @ivory delta I use several json rest sensors but I never needed to get an attribute and somehow recalled there were html parsing changes lately. I had hoped for an easier solution to the scrape integration since my HA needs >2 min for startup
2 minutes? I don't see your point - how often are you restarting it? You only have to restart when you change certain things.
And you want an easier solution than adding a few lines to your configuration.yaml and forgetting about it?
Well, it might be a 10 second job for web developers but I sure need to restart HA at least 10 times to get it right. If it was the only attribute on that tag or if it was named uniquely I'd not be asking. Thanks for making me feel even more stupid.
Presumably you just want something like this: https://hastebin.com/xikixujijo.cs
And I'd hope the element is unique since it's using the id attribute. It's considered terrible in web development to have more than one element with the same id. So setting attribute: "value" should get the right thing every time.
A lot of things in HA are trial and error. Not many people know it all (especially not me, I only started a few weeks ago). Don't worry about getting things wrong a few times while you're learning ๐
I'll try now. I would have thought this would return 0 though as I need the hidden value before
From what I can see on that page, the hidden value isn't important. The script reads from it and then sets the progress bar based on that value.
Either way... it looks like the value=26 in both cases when I view it.
Take the value fromselect: "#progress" or select: "#auslastung" ๐
wow, you were really helpful! Just needed to fix the typo in "unit_of_measurement" and now it works ๐ This hopefully helps to keep a few people corona-free.
I can be helpful sometimes when I'm not a dick ๐
But seriously... even the best developers still make mistakes. Don't be afraid to get things wrong while you're learning ๐
Problem is: the homematic integration is no really robust and might trigger some timing induced errors for the RS485 bus components on startup which in turn leads to the company building's alarm system going off (sabotage alert). You become too careful if you burn your hands more than once ๐
Does anyone know of a way to access general information (like temperature_unit, time_zone and internal_url) within template tags?
@unkempt pollen What are you trying to do?
- id: doorbell_activated
alias: Doorbell Activated
trigger:
- entity_id: binary_sensor.xiaomi_open_close_3
from: 'off'
platform: state
to: 'on'
action:
- service: media_player.play_media
data_template:
entity_id: media_player.family_room_speaker
media_content_id: '{{ states.var.internal_url.state }}/local/audio/doorbell-001.mp3'
media_content_type: music
my current workaround for internal_url is to set it using a rest API call to /api/discovery_info
Where's the benefit in pulling out a static value to be used alongside another static value?
If my internal_url ever changes, which it could, I don't want everything to break.
Currently it's an assigned static IP, but that could change if I switch routers.
That seems like a very infrequent possibility with an easy find and replace solution.
But no, I don't think the internal_url is accessible the way you want.
You can get information about things like version numbers but only because there's a built-in sensor exposing it.
Okay, thanks!
I have a couple of binary sensors for my Abode security system, I'm trying to get them to announce if a door was left open using the entities friendly name..
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
Then you forgot something
If I remove the template it fires
not sure if its a limitation in the Alexa TTS service
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
Show us what you're doing
ah maybe I need to use data_template
out of what exactly?
Got my answer.
{{ state_attr('image_processing.person_detector_front','summary') | regex_findall_index('\d') }}
basically in the screenshow i was getting ('car': 8)
wanted to get only the number
ah... now i see it ๐ ok then
@jovial rain
{{ state_attr('image_processing.person_detector_front', 'summary')['car'] }}
Or .car as another option
hey guys; hoping someone can point out what i am doing wrong here
{% if is_state('sensor.blueirisactiveprofilesensor', 'signal=1 profile=3 lock=0') %}
Night (Run)
{% elif is_state('sensor.blueirisactiveprofilesensor', 'signal=1 profile=1 lock=0') %}
Day (Run)
{% elif is_state('sensor.blueirisactiveprofilesensor', 'signal=1 profile=2 lock=1') %}
No Alerts (Temp)
{% endif %}
sensor.blueirisactiveprofilesensor has a state of signal=1 profile=3 lock=0
Just a string like that?
yea, i copy pasted it
That's obnoxious
its from blueiris
That's what states(sensor.your_sensor) says?
where can i test that? i tried in the templates tab
states(sensor.blueirisactiveprofilesensor)
Wrap it in {{}}
sorry; yea just wrapped it
{{ states('sensor.blueirisactiveprofilesensor') }}
signal=1
profile=3
lock=0
It outputs in multiple lines?
yea, multiple lines
That's probably why your check isn't working
I'm not sure what the newline char would be
hmm tough one
Could try states().split('/n') and see what comes out
{{ states('sensor.blueirisactiveprofilesensor').split('/n') }}
['signal=1\nprofile=3\nlock=0\n']
states().split('/n')
did i key it in correct?
{{ states('sensor.blueirisactiveprofilesensor').split('\n') }}
gives me this now
['signal=1', 'profile=3', 'lock=0', '']
Depends on what youโre trying to do
Adding [0] or 1 or 2 will give you individual items
i am trying to get it going in a if statement
value_template: >-
{% if is_state('sensor.blueirisactiveprofilesensor', 'signal=1 profile=3 lock=0') %}
Night (Run)
{% elif is_state('sensor.blueirisactiveprofilesensor', 'signal=1 profile=1 lock=0') %}
Day (Run)
{% elif is_state('sensor.blueirisactiveprofilesensor', 'signal=1 profile=2 lock=1') %}
No Alerts (Temp)
{% endif %}
states().replace(โ\nโ, โ โ)
is there any info on which lovelace cards support templates?
wow, thanks guys!!
i can use a template in the markdown card. any others?
sorry guys.. one more thing; how would i now make this into a if statement. I have tried this
{% if states('sensor.blueirisactiveprofilesensor').replace('\n',' '), 'signal=1 profile=3 lock=0') %}
{% if states('sensor.blueirisactiveprofilesensor').replace('\n',' ') == 'signal=1 profile=3 lock=0') %}
Night (Run)
states('sensor.blueirisactiveprofilesensor').replace('\n',' ') == "xxxx"
shoot; missed that - i removed it, no error but it still is not showing "Night"
{% if states('sensor.blueirisactiveprofilesensor').replace('\n',' ') == "signal=1 profile=3 lock=0" %}
Night
the output is exactly signal=1 profile=3 lock=0
output of what?
ok i just removed the space in ('\n',' ') to ('\n','')
and changed the == to "signal=1profile=3lock=0"
it caught it now
that'll work too. maybe the spaces were screwing it up somehow
yea, perhaps - but thank you so very much
np. this is really mostly just python, so targeted Google searches can help
got it!
Or, prior to the if check do
{% set status = states('sensor.blah').replace('\n','') %}
And then {% if status == whatever %}
@worn cloud
That way you're not having to copy paste that logic as many times. Makes things cleaner
Hello everyone, is there a way to use JSONPath in a value of a template sensor? How do i combine value_json with the following JSONpath search expression $.results[?(@.mac == "mac_addr")].some_value
I can do that with two sensors, first using json_attributes_path, the other extracting the attribute value, but was hoping for something more elegant
.topic @keen crater
@keen crater Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find the docs at https://www.home-assistant.io/docs/automation/templating/ - and don't forget rule #1! Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs
hi :)
i have a mqtt light who always throw error when updated
i've been looking and i didn't find from what automation or template this error could be from.
Any clue to find it quickly ?
Need to look at your templates
i've been without luck looking at every file. i'll do another pass :)
This will likely be in an automation
especially in the condition section - where you may have a template conditions
so, i gave up on finding the line, and removed all automation include from my config file. still the error.
I've been throught all template switch ... it's not that either
Hello! I just posted this shout for help in the Formum. I'ts probably a long issue for the chat. https://community.home-assistant.io/t/yet-another-template-question-for-combining-home-connect-sensors/200864
But I have a chat question. Does anybody know I its' possible to combine multiple entities (like 4 or 5) to create an outcome based on their combined status? I have Home Connect oven that generates an entity for every part of the machine wich kind annoying if you want to have "its status" seen in 1 enity and not a screen full of entity's. So the question is can you combine them in a template. Because I read a quote on google that templating like this with AND IF AND OR between entitites is only possible with one entity. Is that true?
Hmm maybe nobody is here. We'll if you know the answer please reply to my quest on the forum ๐ Thanks!
maybe nobody is here
Try giving people more than 2 minutes to respond ๐
Yes... you can use templates to 'merge' other values/states into one value/state. But you need to describe what you're trying to do in more specific terms.
It's difficult to see who's here ๐
So be patient.
@static pilot posted a code wall, it is moved here --> https://paste.ubuntu.com/p/4nrbTmKhc8/
~rule6 @thorny snow
@static pilot Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, codewalls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
I was afraid of that...
Sounds like you want an input_select
Nice. And after already linking to the forum post with the same text...
mono asked to be more specific
Then turn the brain on, and pay attention to the rules
Coding experience is not a prerequisite for reading rules
And it's taken me this long to realise that your name is now green ๐ฎ
?
I normally wouldn't suggest this... but maybe #node-red-archived is easier?
@arctic sorrel do you mind taking a look at the post. i'm not shure what to put @ {% else %} {% endif %}
Please don't ping people randomly to ask for help
I normally wouldn't suggest this... but maybe #node-red-archived is easier?
@ivory delta If this doesn't work out that would probably be a solution.
PONG!
Oops, wrong command
Discord isn't like IRC, you don't have to tag people on every response. Keep in mind that every time you tag somebody, they get a notification ping. That can very quickly become annoying and people may block you.
or more fittingly
Generally, don't tag people to ask for help - it comes across as bad manners, youโre demanding somebody answers you. Itโs different if youโre thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.
Similarly, please donโt DM (direct message) people asking for help. It also comes across as demanding, and means that others canโt learn from what you do.
Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on).
No, I wanted the one that said it can 'become annoying and people may block you' ๐
I did do something wrong again?
Yes, read what the bot said.
Oh. woops
@thorny snow You've already had at least one suggestion for what to fix, not sure I can add more without just given you the final answer and avoiding you learning anything
Yes, I'm very busy running it trought the /developer-tools/template meganism. Thanks!
Trying to find out how it works.
The template docs should also give some hints (or a blatant answer)
Well, the thing that 123 pointed out is a simple logic flow thing
I'm try to understand what elif is. The outcome of the formula is stil ...
whith those docs...
Basically, you need to construct a logic flow
Remember that as soon as the logic is true, that block and only that block is run
So if you first check for x > 1 then later check x >50 that later check will never happen
Hi all
I created a very simple template, syntax check is ok, but it's not created. I must miss something obvious but I cannot see the mistake
If you're having problems with your updates to your configuration:
- Check the troubleshooting steps
- Check your log file - remembering you may need to set logger to
infoordebug - Explain what the problem you're having is - sharing configuration, errors, and logs
Also - did you restart HA?
yes of course
And you ran the command line config check?
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
thank you all. couldnt figure it out today. need to go sleep. bye
found the mistake: I use split config and sensor file was not ending with "yaml" but with "yami"
very stupid error ๐ฆ
hey, it happens
would be nice if config validator will list ignored files
Hi guys! Anyone here can help me with templating? I actually try to get something like
It is (Weekday), the 31. of May`
I tried a few things like
now().weekday`
but get only
``built-in method weekday of datetime.datetime object at 0x5ebce660> Mai`
this is a snippet of the whole block
## {{ now().day }} Januar
{% elif now().month in (2,) %}
## {{ now().day }} Februar ```
Well that's certainly an interesting way to get around the spam detection...
Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, codewalls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
.share @analog crag
@analog crag Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
Wasnยดt my intention to spam. Just had issues remembering the amount of backticks and just wanted to have it readable. Sorry if I violated the rules
The formatting was fine. It was the overall length of the post that can be annoying to some users (especially on mobile devices).
This should help you with your question: https://community.home-assistant.io/t/weekday-and-month-sensor/45678/6?u=mono
Further down the thread, someone else suggests this:
Today is {{ ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'][now().weekday()] }}
Way shorter and easier to understand.
Perfect. Thank you. Looks good just need to allign it with the format
And translate to Deutsch? ๐
The only thing which is still open how I get the "german" format "31. Mai"
:D...yes. When it works ๐
I don't understand. What 'format' do you want?
just use ```
Today is {{ now().strftime('%A') }}
Currentyl itยดs showing 31 Mai. I need a Dot in between the day and the month
Assuming strftime returns things based on your local settings, then something like this would give dd.mmm:
{{ now().strftime("%d.%B") }}
The same is true for skalavala's suggestion ๐
So the whole thing can be one short template...
If you want it precisely, use ordinal filter.
Guys this is going into the right direction...but it seems my local settings are wrong
{{now().strftime('%A') + " " + now().strftime('%d') |int| ordinal + " " + now().strftime('%B') }}
``` โ๏ธ gives you `Sunday 31st May`
But we want Sonntag 31.Mai ๐
local language setting should change the text appropriately
Yeah, so that's Baum's next problem
Well the best would be "Sonntag, der 31. Mai"
The thing is now...my language is set to german and the timezone is euope/berlin
You've set your language in your user profile?
yes
what does that template show you in the template editor?
you can customize to whatever you want - it is just a formatted string at this point
I've changed to German and I'm seeing English text from strftime...
Looks like the Python library doesn't care about your user language settings when it comes to templates.
@queen meteor 31. May Mai
I know that "Mai" is because its a duplicate which I can sort out.
ok...
Well...at least with ## {{ now().strftime("%d.%B") }} I can kill the whole codeblock ๐
nice!
the question now is: how to get this freaking dot and set the local to german ๐
๐คทโโ๏ธ
you already got the dot... didn't you?
I can't see any issues (open or closed) about languages and strftime.
@queen meteor Nope. I used now the second code you posted and get Es ist Sunday 31st May
@ivory delta I have the feeling I need to change the Pi locale
Yeah, maybe. And if that doesn't work, log a bug.
Want to see what issues are open (or were open and are now closed)?
Check issues for the backend, issues for the UI, and issues for the documentation.
Maybe if this is done the dot appears automatically.
There was no dot in the template skalavala gave you but it's a simple change to add it.
How can I do it? As you might found out these are my first steps in templating and it looks more like mandarin to me for now ๐
In skalavala's example, the spaces in your text are coming from the space between the double quotes " ":
{{now().strftime('%A') + " " + now().strftime('%d') |int| ordinal + " " + now().strftime('%B') }}
Instead, you want to replace one space with a full stop:
{{now().strftime('%A') + " " + now().strftime('%d') |int| ordinal + "." + now().strftime('%B') }}
If it's not in quotes, it's code. If it's in quotes, it's a string ('ordinary' text).
Ahhh!
And voila: There is the dot! Thanks a lot @ivory delta and @queen meteor ๐
Now to find a solution for the locale issue ๐ maybe the guys in another channel can help
hello happy people .. sorry I posted in the wrong room earlier.. I wanna have a sync between my "dummy" climate and the real climate. Therefor I listen to all state changes and want to apply those to the "real" climate.
ac_bedroom_operation_mode_controller:
alias: 'AC Bedroom Control Sync Operation Mode'
trigger:
platform: state
entity_id: climate.bedroom_ac_control
action:
service: climate.set_hvac_mode
data_template:
entity_id: climate.air_conditioner_bedroom
operation_mode: '{{ trigger.to_state.climate.bedroom_ac_control }}'
this fail ๐
there's a component called climate group but it does not work for me as there is no fan_mode inclused for the moment.. anyone here willing to help me to sync thse two entities?
Can a cover template for a garage door be assigned to an area? if yes how?
@ivory delta I think i found something. It seems that Templates are using always the english format. I need to setup a list again.
Template entities generally can't be assigned to an area as they do not have devices associated and only devices can be aligned to areas
@steep lodge posted a code wall, it is moved here --> https://paste.ubuntu.com/p/McX4RRvRVH/
~codewall @steep lodge
@steep lodge Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
Hi All,
I'm struggling to get the state of an MQTT switch from some JSON. Below is the switch YAML and the JSON from the device. When the switch is turned on, the JSON from the device is updated i.e. temperatureLock = true but the switch switches back off a second later. Obviously I want the switch to stay on while tempLock is true
Thanks in advance
state_topic: "hottub/state/status"
value_template: "{{ value_json.temperatureLock }}"
{
"temperatureLock": true,
}
@buoyant pine did not work ๐ฆ
but it must be possible to read out a state / attribute and "copy" it to a service call ?
jampez - you usually don't update a 'status' topic to control something. Status is for polling, so you can determine the, uh, status of the device.
Your device will usually either listen on something like cmnd (common for Tasmota) or its own topic, but I doubt it's /status. Check the documentation for your device to be sure.
ThUnD3r - lots of people use states/attributes in service calls. That's what templates are for ๐
jampez - you usually don't update a 'status' topic to control something. Status is for polling, so you can determine the, uh, status of the device.
@ivory delta thanks! put me in the right direction and now problems have been vanquished.
Is there a way to use friendly names in alexa intent scripts? This is what I am currently using:
ActivateSwitchonIntent:
action:
service: switch.turn_on
data_template:
entity_id: switch.{{ Switch | replace(" ", "_") | replace("light", "switch") }}
speech:
type: plain
text: !include alexa_confirm.yaml
@olive moth logs?
Oh, and it's climate.set_hvac_mode, not climate.set_operation_mode
The log would basically tell you that. That's also why it's important to share error messages when you're having trouble with something
I have a sensor from openMQTT reporting home/not_home, is it possible to change him to device_tracker for use in Person?
.device_tracker.mqtt @rotund hazel
I've got this in one of my automations:
value_template: '{% if now().strftime(''%j'')|int % 2 != 0 %}True{% else %}False{%endif%}'
I'm trying to use it in the Dev->Template page but I get this error:
Error rendering template: TemplateSyntaxError: expected token ',', got 'string'
Can someone tell me how to correct this so that it works in the live template page?
It works fine in the automation, btw
You need mixed quotes...
@ivory delta thanks, that what I was searching!
If you use single quotes around the template, use double quotes inside (or vice versa) ๐
{% if now().strftime(''%j'')|int % 2 != 0 %}True{% else %}False{%endif%}
This is what I'm trying in the web gui. Are you saying to change it to "%j" ?
Got it. Weird. Thank you
Also, you'll get the strings True and False out of that template
value_template: '{{ now().strftime("%j")|int % 2 != 0 }}'
``` is what I'd suggest if you want a boolean true/false
Thanks. I'll give that a try
So this report device_tracker: {"id":"d1:00:00:03:92:92","rssi":-77,"distance":7.119795,"servicedata":"01070100d10000039292","servicedatauuid":"0000fe33-0000-1000-8000-00805f9b34fb"}instead of home, so what payload_home template to make with so many data? payload_not_home was easy, because reports: unknown
What are you using? monitor?
I've had no issues, but ๐คท
Then, probably you'll need to use the rssi or distance values
Since it doesn't report home/not_home as you'd said ๐
this is the last one i tried: payload_home: "{{ value_json['rssi'] }}"
no, the same all data json
yes, but I need a template. I have it for payload_not_home: unknown
I know you need one, but the integration doesn't accept them
You'd need to use your payload above, and have an automation that uses a template to parse it and then update another topic with home or not_home
ah so ๐ , thanks
Is there a way to write this template sensor in a better way? https://paste.ubuntu.com/p/xwpqrCYM8j/
The idea is to give 1 if any of the sensors listed have a state that is not 0. Maybe could be done with some kind of a loop?
Put them all in a group and check the status of that group?
By default when any member of a group is on then the group will also be on.
@solid storm โ๏ธ
Well that sounds wise, then I don't even need the template sensor. Never used groups before, thanks ๐
Groups are neat for all kinds of reasons... but your use case of 'is at least one thing on?' is a prime example.
And also for is everything on
@arctic sorrel What? Do you mean OFF?
Hi there. Anyone here who witred to "sync" entites ?
wanna sync my climate entities . Background I have a Beco Thermostat sucessfully working via mqtt and now i want this climate component controlls the AC cliate entity. Therefore I must sync the both vise versa. Any idea how to archieve that?
Are these two separate HA systems, or ... what?
this is the error : 2020-06-01 20:44:06 ERROR (MainThread) [homeassistant.components.automation] AC Sync Bedroom: Error executing script. Invalid data for call_service at pos 1: required key not provided @ data['hvac_mode']
this is the automatin:
ac_bedroom_hvac_mode_controller:
alias: 'AC Bedroom Control Sync hvac Mode'
trigger:
- platform: state
entity_id: climate.bedroom_ac_control
action:
- service: climate.set_hvac_mode
entity_id: climate.air_conditioner_bedroom
data_template:
hvac_mode: "{{ trigger.to_state }}"
@arctic sorrel nope but the beco thermostat is not wired but controlled via mqtt.. now i need to somehow bridge those two climate entities
@arctic sorrel there's also a climate group custom componnent but there's aparently no fan_mode integrated. Opened an issue for this: https://github.com/daenny/climate_group/issues/27 BUt I don't know when this is fixed an I wanna test the WAF ๐ and integrate it also without this custom componnent
~irc @olive moth
@olive moth Discord isn't like IRC, you don't have to tag people on every response. Keep in mind that every time you tag somebody, they get a notification ping. That can very quickly become annoying and people may block you.
~tagging @olive moth
@olive moth Generally, don't tag people to ask for help - it comes across as bad manners, youโre demanding somebody answers you. Itโs different if youโre thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.
Similarly, please donโt DM (direct message) people asking for help. It also comes across as demanding, and means that others canโt learn from what you do.
Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on).
Try stuff, see what works...
I tagged u as u answered to my quesstion.. but OK.. no tagging .. and no worries I don't PM people just to ask for help ๐
Well, I asked you one question for clarification
That wasn't a hint to tag me on everything you posted about after that ๐
got that!
๐
i searched the forum and was wondering why nobody never face this issue.. Climate group does not work unfortunately for me for the moment.
@olive moth I answered you earlier
You corrected the service call but didn't use the template I provided
@buoyant pine thanks but it won't work. I tried:
ac_bedroom_operation_mode_controller:
alias: 'AC Bedroom Control Sync Operation Mode'
trigger:
platform: state
entity_id: climate.bedroom_ac_control
action:
service: climate.set_hvac_mode
data_template:
entity_id: climate.air_conditioner_bedroom
climate.set_hvac_mode: "{{ state_attr(trigger.to_state.climate.bedroom_ac_control, 'hvac_mode') }}"
also
ac_bedroom_operation_mode_controller:
alias: 'AC Bedroom Control Sync Operation Mode'
trigger:
platform: state
entity_id: climate.bedroom_ac_control
action:
service: climate.set_hvac_mode
data_template:
entity_id: climate.air_conditioner_bedroom
climate.set_hvac_mode: "{{ state_attr(trigger.to_state.entiy_id, 'hvac_mode') }}"
Have you run a config check on that? It should tell you what's wrong
2020-06-01 23:26:24 ERROR (MainThread) [homeassistant.components.automation] AC Sync Bedroom: Error executing script. Invalid data for call_service at pos 1: required key not provided @ data['hvac_mode']
config check says everything is ok
Okay, well that error is telling you what's wrong
@olive moth climate.set_hvac_mode: under data_template: needs to be hvac_mode:
(data_template:)
lol thanks
also this
"{{ state_attr(trigger.to_state.entiy_id, 'hvac_mode') }}"
``` should be
"{{ state_attr(trigger.to_state.entity_id, 'hvac_mode') }}"
so final should be:
ac_bedroom_operation_mode_controller:
alias: 'AC Bedroom Control Sync Operation Mode'
trigger:
platform: state
entity_id: climate.bedroom_ac_control
action:
service: climate.set_hvac_mode
data_template:
entity_id: climate.air_conditioner_bedroom
hvac_mode: "{{ state_attr(trigger.to_state.entity_id, 'hvac_mode') }}"
looks good
looks good .. is not good ๐ฆ
2020-06-01 23:37:44 ERROR (MainThread) [homeassistant.components.automation] AC Sync Bedroom: Error executing script. Invalid data for call_service at pos 1: required key not provided @ data['hvac_mode']
i don't nderstand why hvac_mode: "{{ trigger.to_state.state }}"
because it's not a state change, it's a state attribute that you're wanting to match
does not work as well .. or something like {{ states.climate.air_conditioner_bedroom.state }}
nope is a state
hvac_mode is a state attribute
you are right.. and how would i then change the hvac_mode accordingly to the state of the dummy?
but in dev-tools it is exactly this. your service data is hvac_mode
totally weirdo for me
oh wait... the state of a climate entity is the same thing as the hvac_mode attribute. but hang on, you said dummy. does climate.bedroom_ac_control exist?
the goal is if i change on the thermostat the hvac mode /temperature or fan_mode for example . I need the climate entity of my AC be changed
climate.bedroom_ac_control cool hvac_modes: heat, cool, auto, fan_only, off
min_temp: 16
max_temp: 32
target_temp_step: 1
fan_modes: auto, low, medium, high
preset_modes: none, away
current_temperature: 23.5
temperature: 19.5
fan_mode: auto
hvac_action: cooling
preset_mode: null
friendly_name: Bedroom AC Control
supported_features: 25
ja it does
this is the beco thermostat which I added as MQTT climate
ac_bedroom_hvac_mode_controller:
alias: 'AC Bedroom Control Sync hvac Mode'
trigger:
platform: state
entity_id: climate.bedroom_ac_control
action:
service: climate.set_hvac_mode
entity_id: climate.air_conditioner_bedroom
data_template:
hvac_mode: "{{ trigger.to_state.state }}"
you know what, that's my bad. hvac_mode isn't a state attribute. i think operation_mode used to be, but then in 0.96 the climate integration was reworked so that the state of the climate entity is the hvac mode
that's what I came up ut it throws the same error
in dev-tools you have the servie climate.set_hvac_mode
so yeah, hvac_mode: "{{ trigger.to_state.state }}" should work as long as the state of the climate entity in the trigger is a valid hvac mode for the target entity
but as you can see my hvac_modes are exaclty.. is the order of those hvac_modes important?
they both have heat, cool, fan_only and off
try this:
- service: climate.set_hvac_mode
entity_id: climate.air_conditioner_bedroom
data_template:
hvac_mode: "{{ trigger.to_state.state }}"
oh wait. you said you tried that already?
yes i did
WAIT. is this a script or an automation?
ac_bedroom_hvac_mode_controller:
alias: 'AC Bedroom Control Sync hvac Mode'
``` makes me think it's a script, but you have a trigger
2020-06-01 23:50:15 ERROR (MainThread) [homeassistant.components.automation] AC Sync Bedroom: Error executing script. Invalid data for call_service at pos 1: required key not provided @ data['hvac_mode']
automation
ok. are you manually triggering this or actually changing the state of the trigger entity?
I am with a ..... shit what i am doing there ๐ using script layout for automation? ๐ let mec change it
yep, i wasn't paying attention enough earlier. i knew something was up
LOL that was it.. now i need the temperature.. this is maybe almost the same.. let me try.. are u around a bit if i need help
Ffs, can't believe it took me that long to realize that
Well, temperature is a state attribute, so keep that in mind
ok.. now i have a biig issue .. if i make it the other way around.. let's say i change the hvac_mode in my air conditioner and want it to be synched in my dummy i get into a race conditon i think ๐
it turn off and for example cool all the time ๐ฆ
trigger:
platform: state
entity_id: climate.air_conditioner_bedroom
action:
service: climate.set_hvac_mode
entity_id: climate.bedroom_ac_control
data_template:
hvac_mode: "{{ trigger.to_state.state }}"```
this is the other way around
because i also control the ac with my phone or dashboard.. when both automation are actiates then it changes all the time between off and hvac_mode
If you put both entities in the trigger and in the action they should sync fine. When one changes, the other will change. It will trigger a second time but that shouldn't cause issues
I have a template sensor that I change the icon with "icon_template" and it works perfectly. I decided I also wanted to change the color and figured I could just add in another line with "icon_color" into the same logic statement that I had to change the icon like this: https://paste.ubuntu.com/p/SJZpDktPPq/
But it's not working as expected. I assume I either have the syntax wrong for icon_color or I can't change the icon color in the config and I need to do that in customize.yaml. Can anyone explain (or point me towards some documentation for icon_color)?
I posted this to #frontend-archived by mistake.
Sensor, or switch?
Either way, where did you see icon_color in the template docs?
It's not in https://www.home-assistant.io/integrations/switch.template or https://www.home-assistant.io/integrations/template, so I'm guessing you made it up?
Switch. I found "icon_color" searching through examples. It was in the Internet, so it must be true!!! Well, that explains the lack of documentation.
So the solution is to use customize.yaml?
Or we can't change icon color based on state.
https://www.home-assistant.io/docs/configuration/customizing-devices/ ๐ have a read and see what's supported there
Things like what colour a thing is is a #frontend-archived thing handled by style sheets and CSS
Got it. I'll find a solution in lovelace.๐
HACS: customer button card made my life easy ๐
hey can someone help me with the markdown card?
Don't ask to ask, just ask your question. Then people can answer when they're around.
When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:
- What version of the Home Assistant are you running? (remember, last isn't a version)
- What exactly are you trying to do that won't work?
- Is the problem uniform or erratic?
- What's the exact error message?
- When did it arise?
- What exactly don't you "get"?
- Can you share sample code, ideally with line errors where the error occurs?
@lavish jacinth posted a code wall, it is moved here --> https://paste.ubuntu.com/p/bMC88bw8vw/
can anyone help with this issue: I have a TPlink smart Switch that I use to control 2 Feit smart bulbs. I am having an issue where, if I turn off the lights using the switch, the feit bulbs loose power and can't be control/turn back on using the lights. The light bulbs work fine if it is turned on/off using the light entity. If I turn off the bulb using the light entity, then the switch doesnt work. From my research, it looks like using template would work, but have no idea how to start
~codewall @lavish jacinth
@lavish jacinth Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.
Please take the time now to review all of the rules and references in #rules.
~crosspost @cloud frigate
@cloud frigate Please DO NOT cross post. Read the channel description, post it and wait for folks to respond.
You'd asked in the right channel initially @cloud frigate
how do i get the attributes state within markdown
Standard templating ๐
{{states('sensor.hot_water_state.attributes.Now')}}
``` won't work, because `sensor.hot_water_state.attributes.Now` isn't an entity
{{state_attr('sensor.hot_water_state','Now')}}
``` however...
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)
my man ๐
thanks working now!
if there a place where i can find a list of these calls for templating
Jinja Template Designer Documentation
For more examples and samples, visit see this page
It's even linked from the channel topic ๐
@arctic sorrel repo is closed?
Repository unavailable due to DMCA takedown.
sorry to tag again but what does that mean?
I have no idea what you're referring to...
Should I update it?
Hello, I have a little question and I hope this is the right channel to post this.
I want to have an input field to put in a time, when an automation should start, but then I noticed something weird.
{{now().timestamp() | timestamp_custom("%H:%M:%S", true)}}
Returns the right time. But for example if I put 18:00 in the input field and then I try to "read" it with:
{{state_attr('input_datetime.lights_on_time', 'timestamp') | timestamp_custom("%H:%M:%S", true)}}
I get 19:00:00 instead of 18:00:00. My timezone is UTC+1, but I think it might also could have something to do with the daylight savings time. Am I doing something wrong? Or could it be a bug?
@merry fable It's not a bug. Do you have a date attached to the datetime? If the answer is no, then you want to use timestamp_custom("%H:%M:%S", false) because without a date, the timestamp is in relation to midnight your local time. I.e. it's already local, don't convert it to local again. If you have a date attached, then it's in relation to January first 1970
example: Timestamp in relation to midnight: 64800. Timestamp in relation to 1970: 1591135200. Both are 18:00:00.
@buoyant pine : like this: - alias: 'AC_bedroom_controller' trigger: - platform: state entity_id: climate.bedroom_ac_control - platform: state entity_id: climate.air_conditioner_bedroom action: - service: climate.set_hvac_mode entity_id: climate.air_conditioner_bedroom data_template: hvac_mode: "{{ trigger.to_state.state }}" - service: climate.set_hvac_mode entity_id: climate.bedroom_ac_control data_template: hvac_mode: "{{ trigger.to_state.state }}"
?
this example wil turn off and cool for example all the time .. like a race condition ๐ฆ
hey if you show temp and hum on 1 line can you still have graph of them if you click on it ?
so i want to show in ยฐC and hum in %
@olive moth it should be fine. Let's say 1 is off and 2 is off. You change 1 to cool, which will trigger the automation and change 1 to cool (no state change) and 2 to cool. This will trigger the automation again and will change 1 to cool (no state change) and 2 to cool (no state change). It'll then stop there
You could even add a template condition checking that both thermostats don't have the same state which will prevent it from firing a second time
You can also list multiple entity IDs in the trigger and service call instead of doing separate triggers and service calls
can anyone help me ? :p
As in, the state of whatever entity you're talking about is a string containing the temp and humidity? No
hm ok
if i could put this on a line maybe the graph could work for temp and hum?
Yeah, if the temp and humidity are separate sensors you can see a graph of them, separately