#templates-archived
1 messages · Page 150 of 1
IIRC the parent_id should match an ID for an automation
the user_id should match the user as long as it was called from the UI (or from a api like alexa if you logged in via it's own cridentials)
I have created several input_booleans and other configurations successfully in my configuration.yaml but for some reason none of the sensors I specify show up in the web UI.
Good morning everyone, quick template question: Is there a proper way / built in function to check if entity "x" belongs to domain "y", something like is_domain("x", "y") returning true or false?
Or do i simply put "{{ "y." in "x" }}?
There's no is_domain, but the last one should work
Or this {{ states.sensor.something.domain }} gives sensor
So {{ states.sensor.something.domain == 'sensor'}}
I like that, seems "cleaner" than the string comparison, thx
And entities changed by the script, will have the same context as the script itself, right?
No wait, that's not right I guess
If I have script 1 and in that script I start script2, and perform some state changes, both the entities changed, and script2 will have the same context
Okay, so this seems to work for me, it will show all cast entities which are changed by my script
{% set context = states.script.test_script.context %}
{{ context in expand(integration_entities('cast')) | map(attribute='context') | list }}
{%- set ns = namespace(context = []) %}
{%- for p in expand(integration_entities('cast')) %}
{%- if p.context == context %}
{%- set ns.context = ns.context + [p.entity_id] %}
{%- endif %}
{%- endfor %}
{{ ns.context }}
script1, script2 and the entities changed by the script all have the same context (until the entities are changed again by something else, eg volume change on the device)
The 2nd line will be used in a wait_template to ensure the actions are performed. I might add a repeat after that to add more entities in case there are more service calls with a delay in between or something like that
Well, I have something to do now 🙂
(besides working for my boss)
you should be able to use generators for that
{{ expand(integration_entities('cast')) | selectattr('context','eq', context) | map(attribute='context') | list }}
just keep in mind that probably won't work during execution as the context object will be the momentary version with a user_id or parent_id attached
at that point you can just compare the ID that you care about
{{ expand(integration_entities('cast')) | selectattr('context.user_id','eq', context.user_id) | map(attribute='context') | list }}
Ah, yes, the loop is not needed, I was thinking to difficult
I’ve never looked at the context isequal override. It mighty just compare the ids or have some intelligence to it, so it may work.
With our matching the ids in the select*
Without*
I actually don't want the user_id, I want to link it to the specific script activation, as it can run multiple times in parallel
But I think this will work 🙂 Thanks a lot
That would be the parent_id then
Well, with the template above, and running a simple script just playing an mp3 on some speakers, and this template:
{% set context = states.script.test_script.context %}
{{ context in expand(integration_entities('cast')) | map(attribute='context') | list }}
{{ expand(integration_entities('cast')) | selectattr('context','eq', context) | map(attribute='entity_id') | list }}
{{ context }}
I get this:
True
['media_player.beneden_groep', 'media_player.floris_mini', 'media_player.pepijn_mini', 'media_player.slaapkamer_hub']
Context(user_id='24c8260fb51f4fb995e5aeaaaa3edd1b', parent_id=None, id='ec6b9ac1e1b00333f43de6970883217e')
The list of entities is correct, those are the ones I targeted, but there is no parent_id
Maybe it’s just Id then
I haven’t played with context and scripts called from an automation. Something has to point to it though
Ah
Ok, I know the behavior now
The state machine does contain the last context for each script
so you can search the state machine for the origin
so what you have makes sense, and the entire context object matches
FYI it is the ID
not the parent_id
and the context object doesn't tell you the origin, which is opposite what I thought.
it tells you which objects have that context
So, typically, if an automation has a context object, and it matches a bunch of entity_id's, that's most likely the origin
How do I ignore deactivated devices in this template? https://pastebin.com/HmhMekzy
Hmm.. it's probably the translation then. How about 'disabled'?
If I click on an entity I can 'deactivate' it or perhaps disable it
if entities are disabled, they aren't in the state machine
i.e. they won't show up in any templates
"Disabled by Config entry. Disabled entities will not be added to Home Assistant."
exactly, so see my previous response
That's what I thought... lemme check again
an entity being removed won't update the state of that template BTW
so that's probably what you're seeing
reload your templates after removing the entity
Looks like I needed a restart of HA. Reloading just template entities didn't help. Oh well, fixed now. Thanks.
the state object was probably still in the state machine then
reloading the integration that created the disabled entities would have worked then
Unsure of which channel is correct but i'll try here first. Do tell me if my request should go somewhere else.
I have the following sensor: https://pastebin.com/NfiBP90R
It seems to turn on and off as expected. My issue is that i can't seem to figure out if it loads the json attributes. I've triggered the sensor and checked the trace of an automation (https://pastebin.com/0KtZdNXP) but it doesn't list the attributes that are supposed to be picked up. I've verified that the data is available in the broker
Hiya! I noticed template shorthand notation could be a little more consistent. When in a condition-action, the syntax is - condition: "{{ true }}" while when in a regular automation condition, that syntax isn't allowed and I have to use - "{{ true }}" instead.
The problem might be me, but that has me look up the correct syntax every time I use it.
Now, should I open an issue or a feature request (or is this old news and already being worked on?) 😅
That’s yaml, not templates
got me. post there now?
There is no yaml channel, but what you're talking about is yaml being picky not templates
the condition field expects a list
Yes, absolutely.
I thought of ```
conditions:
- condition: "{{ ...
- condition: "{{ ...
shorthand notation is just:
or is that a bad Idea
Yes 😅
longhand:
- condition: template
value_template: "{{ }}"
shorthand:
- "{{ }}"
nothing between
Yeah I wanted to ask whether I should open an issue or a feature request if I wanted to suggest adding this: ```
conditions:
- condition: "{{ ...
- condition: "{{ ...
that would be feature request, but why would you want that
the whole point of templates is to put your entire condition in the template
so you woudln't have multiple, hence the singular - "{{ }}"
okay. I think its easier to remember but I might be alone on that one 😅
because condition-action uses this syntax already (obviously, because its an action)
okay, not sure if I really understand, but if you say it makes the most sense the way it is, I'll discard my idea 😅
I don't like shorthand, I use longhand
because it makes the most sense to me. You're welcome to put in any FR you want
ohh I understand. Well I dont put ALL templates into one template, because its easier to understand when I look at it a few months after writing 😅
Make it multiline?
Also good. I might make a FR and see what the votes say 😅
One of my favorite comments ever on a FR is "if I could give this negative votes, I would"
🤣 🤣 🤣
Sounds like me
After seeing THAT feature request, I am DEFINITELY shooting my shot...
The conditions field in a choose also expects a list, but there you can directly add a shorthand condition.
I think that is also adding to the confusion.
I’m sure it is, it wouldn’t be hard to add that stuff everywhere. It’s funny it’s not consistent everywhere
Hey! I want to make a sensor that shows my heat pumps current target temp. Cant make a code work, do anyone know what a working code should look like?
is your heat pumps target temp an attribute of another entity?
Shouldnt this show the current target temp:
- platform: template
sensors:
temperature:
friendly_name: "Daking Target Temp"
value_template: "{{ state_attr('climate.daikinap42587', 'temperature') }}"
No it doesnt have its on Entity
its only in the "attribute" of the core entity
Here you can see all its attributes:
https://ibb.co/Tq7nk5k
Cant I make a sensor of some of them and track them in a chart to see the attribute change during the day?
Looks fine to me, assuming the correct indentation was lost in the process of posting here. Elaborate on 'code doesnt work' 🤔
it give me green check, but check config give me:
Invalid config for [sensor.template]: expected dictionary for dictionary value @ data['sensors']. Got None
extra keys not allowed @ data['friendly_name']. Got 'Daking Target Temp'
extra keys not allowed @ data['temperature']. Got None
extra keys not allowed @ data['value_template']. Got "{{ state_attr('climate.daikinap42587', 'temperature') }}". (See ?, line ?).
Not sure, (I'm not a pro) but looks like wrong indentation?
You should use the modern configuration format anyway, instead of legacy format.
in configuration.yaml:
template:
- sensor:
- name: "Daking Target Temp"
unit_of_measurement: "°C"
state: "{{ state_attr('climate.daikinap42587', 'temperature') }}"
hm ok I get error... guess the rest of my configuration.yaml is messed up lol
since I laready have tempplate and sensor
do I need to add that again?
I don't know what you mean exactly.
The code I sent is a replacement to yours, and it goes into configuration.yaml instead of sensors.yaml.
seemed to went trough now, awesome! lets see what the sensor show
found this site, do it write your code in the right way if you're unsure, or what? http://www.yamllint.com/
That tool is only to check integrity of YAML, not whether your yaml does what you want it to do or not.
yeha I mean me as a newbie probably dont know all the "-" and spacings etc to get it right and that one at least give me that right?
Yes and no. For example, your yaml passed the check, because its valid yaml. But your yaml doesn't do what you want. 😅
but in my configuration file now I have the code you cave me... will All the new sensor I do go under that "template" or do I need to re write it again if I want another sensor?
for more sensors you'd do:
template:
- sensor:
- name: "Daking Target Temp"
unit_of_measurement: "°C"
state: "{{ state_attr('climate.daikinap42587', 'temperature') }}"
- sensor:
- name: "New Sensor"
unit_of_measurement: "°C"
state: "{{ ... }}"
- sensor:
- name: "Even Newer Sensor"
unit_of_measurement: "°C"
state: "{{ ... }}"
sorry, formatting was off. fixed now
Cool then I get it! Thanks! I did add a sensor some days ago from GitHub, and just copy and pasted the code. And under the code you gave me I now have that sensor in this way:
sensor:
- platform: greenely
email: XXXX
password: XXX
usage: true
prices: true
that "-" is there infront of the platform, hm
Or just
template:
- sensor:
- name: "Daking Target Temp"
unit_of_measurement: "°C"
state: "{{ state_attr('climate.daikinap42587', 'temperature') }}"
- name: "New Sensor"
unit_of_measurement: "°C"
state: "{{ ... }}"
Ah cool ! Thanks !
Assuming both of those are sensors and not another type like binary sensor
nice!
how do I get dem fancy colours? 🤯
```yaml
thanks!
last newbie question 😛
So this is a Template - Sensor then?
But the greenely thing I mentioned is coded
Sensor
-platform
Whats the diffrence?
One is the old format and one is the new one. Both are described on the docs page
Ok so I could rewrite them with this new way?
Nope, the greenly sensor isn't a template sensor.
Hm right! Yeha that one required some files to be added etc
Oh, right
There goes my New Year's resolution about not jumping into the middle of a conversation
haha I feel that
What decides what entitys is created when adding a new device?
why wasnt this target temp created for example? but some other was
haha I know I always ask the best questions 😛
The integration decides which sensors it adds automatically. If you want more, you need to make your own. 💁
Fair enough 😄
Hi guys, may I request a bit of help ? I do have an Awtrix display (DIY) and I'm trying to integrate it in HA. I'm almost there except for the "state" which is giving me headaches...(MQTT)
Sorry if I'm not in the correct place
Hi all, I am trying to build a URL string with a template for the REST integration. I need to insert today's date in the URL. The following works as expected in the template panel of the developer tool but not in the configuration.yaml file.
{%- set my_string = 'https://api.tidesandcurrents.noaa.gov/api/prod/datagetter?product=predictions&application=NOS.COOPS.TAC.WL&begin_date=' %}
{%- set my_string = my_string ~ now().timestamp() | timestamp_custom('%Y%m%d' ) ~ '' %}
{%- set my_string = my_string ~ '&end_date=' %}
{%- set my_string = my_string ~ (now() + timedelta( days = 1)).timestamp() | timestamp_custom('%Y%m%d') ~ '' %}
{%- set my_string = my_string ~ '&datum=MLLW&station=9410840&time_zone=lst_ldt&units=english&interval=hilo&format=json' ~ '' %}
{{ my_string }}
It actually looks like the integration looks for a leading "http" string and fails when it ends up being a jinja bracket instead.
Did you introduce the multi line template with >- and use resource_template?
Any thoughts on why I would be unable to change a Lutron switch into a light with the usual-
light:
- platform: switch
name: Switch Name - Light
entity_id: switch.lutron_switch_id
I’m changing a tasmota outlet into a light in the same manner with no issues
if you're adding another light: in your config, that's why
I’m only using light: once
- platform: switch
name: Switch Name - Tasmota
entity_id: switch.tasmota_switch_id
- platform: switch
name: Switch Name - Light
entity_id: switch.lutron_switch_id ```
Also if I only use the Lutron one it still does not create the light
Check the log
This is not templates related, #integrations-archived would be a better match
is attribute data now showed in trace?
How do you mean?
not*
"id": "0",
"idx": "0",
"platform": "device",
"entity_id": "binary_sensor.blueiris_driveway_motion",
"from_state": {
"entity_id": "binary_sensor.blueiris_driveway_motion",
"state": "off",
"attributes": {
"friendly_name": "BlueIris Driveway Motion",
"device_class": "motion"
},```
this is from a trace
the attributes are missing. it just says friendly name and device class. not the json attributes
I'm not sure which attributes are missing, but if the entity does have more attributes, I guess they will show if you use a state trigger instead of a device trigger
Ok i'll try flipping it to state instead
Maybe anyone could say, if thats an error or not.
I defined a couple of template binary sensors like described here: https://www.home-assistant.io/integrations/template
So, setting up a unique_id should set the entity-id to binary_sensor.unique_id, right?
This one works:
- sensor:
- name: "Leistung für Überschussladen"
unique_id: charging_current
device_class: power
unit_of_measurement: "W"
state: >-
{% set charging = is_state('switch.superb_iv_charging','on') %}
{% set offset = states('input_number.current_offset') %}
{% set generated = states('sensor.senec_solar_generated_power') %}
{% set housepower = states('sensor.senec_house_power') %}
{% set current = generated|float - housepower|float - offset|int %}
{{ '%.2f' % current|float if current|float > 0.00 or charging else 0.00 }}
This on not:
- binary_sensor:
- name: "Abreiseplanung 1: Wiederkehrend"
unique_id: deptimer1_recurring
state: >-
{{ true if is_state_attr('switch.superb_iv_departure_timer_1','timerFrequency','cyclic') else false }}
First ones entity-id is sensor.charging_current as expected.
Second one has binary_sensor.abreiseplanung_1_wiederkehrend instead of binary_sensor.deptimer1_recurring.
Maybe the ":" cause this?
The entity_id will be based on the name not on the unique_id
But if you provide a unique_id, you can change the entity_id in the GUI
Did you convert sensor.charging_current from the old style to the new style? That would be the only way the entity_id would keep that. The other option is that you named it Charging Current, reloaded your template, then changed it to leistung.. then reloaded.
no
Yes. First one was converted from legacy to modern with the same unique_id. Maybe thats the reason the entity-id has been kept.
It’s not a maybe, that is the reason
OK thanks. So unique id will never be used in UI?
In old style templating there was friendly_name. That was easier
Name was entity_id, friedly_name was for the UI.
Now I have to set name to get some thing friendly for the UI and change the entity_id later. Not very smart.
You can set only the unique_id, and not the name, and then set a friendly_name attribute
So, the json attributes do not show even if it’s state instead of device
Hello, someone knows about json, I would like to extract multiple data at once from an api.. I would like to extract the name and the schedules.
Here is the answer in json.
Is this possible? (as_timestamp(today_at("18:00")))
I don't see why not. did you try it?
here: {{ (as_timestamp(today_at("18:00"))) }} -> 1645063200
ah thanks, was using it in something bigger and got an error
-> Templates is your friend here
How can I do after {{ (as_timestamp(states("sensor.motorola_one_hyper_next_alarm" )) - 1800) }} in the template manager?
so if set my alarm, minus 30 minutes that time, after that it should be true
{{ states("sensor.motorola_one_hyper_next_alarm" ) | as_datetime | as_local - timedelta(minutes=30) > now() }}
Seems to be always true
Are you past the alarm time - 30 minutes?
Current time is 18:45, setting alarm to 16:00 = true, and to 20:00 = true
Ok, then it’ll be true because now is past the alarm time - 30 minutes
It should be false >31 minutes before the alarm time.
18:45 > 15:30
You set the alarm time to 1600
18:45 is past that no matter what. Not sure what you expect
Doesnt matter if I set it to 18:10, 18:35, 19:00, its always true
What’s the state of your sensor
2022-02-17T16:40:00+00:00
Remove the as_local
{{ states("sensor.motorola_one_hyper_next_alarm" ) | as_datetime - timedelta(minutes=30) > now() }}
Yes
Meh
The problem is that after the alarm went off it forgets
It cannot calculate -30 minutes anymore.
Which is fine
Hmm
Build that into your template
Now its never true anymore
No clue what you’re using at this point, based on your sensor state, the one you posted should work.
So what does it need to do:
It has to always be true after 09:00
It needs to be true 30 minutes before the alarm goes off (So the lights are bright if I'm out of bed before the alarm)
It should be false after sun.sun elevation is above 4 (which I now handle with a different numeric_state condition)
So this does most of the above, however it becomes false again after the alarm went off before 09:00
{{ as_timestamp(states("sensor.date_time").replace(",","")) >=
(as_timestamp(states("sensor.motorola_one_hyper_next_alarm" )) -
1800) or now().hour >= 9 }}
Because I think after the alarm went off it switches to the next upcoming alarm, which will then be in 24 hours.
You won’t be able to make that template if the sensor wipes out it’s data after the alarm is hit. It’s impossible
Maybe an if statement that checks if the alarm is set for today if so it converts it to just the time.
Either it has to keep the data or you have to use a different method like turning on an input boolean or a trigger based template sensor.
Hmm, what do you suggest I use?
Whatever you want to get the job done
Either way, a single template won’t work.
To me, it seems odd that you want it to stay on. Id just make a momentary template sensor that’s just on for the minute that the alarm should go off. Then trigger off that.
Well I want it to stay on until 09:00, until this picks it up: or now().hour >= 9
I feel like we've been discussing this same problem for like a week 🙂
Make a template that works off a trigger then. On when the sensor = the current time, off when the its 9
Yep, still struggling to come up with a solution, but I believe the input boolean could work
template that works of a trigger,
Should it be an external automation?
It cannot be done through the GUI?
correct
- trigger:
- platform: state
entitiy_id: sensor.motorola_one_hyper_next_alarm
sensor:
- name: "Alarm"
state: '{{ as_timestamp(states("sensor.date_time").replace(",","")) >= (as_timestamp(states("sensor.motorola_one_hyper_next_alarm" )) - 3600) }}'
This also goes to false when the alarm went off, so it does exactly the same as in the automation :S
And the trigger-based-template-sensors does not have the options the automation Template trigger has.
As I explained before, your trigger on needs to be the template, your trigger off needs to be an @9. Your state template needs to be based on the triggers, not the value of your sensor
I don't know why you keep going back to the as_timestamp either
- trigger:
- id: "on"
platform: template
value_template: "{{ now() >= states("sensor.motorola_one_hyper_next_alarm" ) | as_datetime - timedelta(minutes=30) }}"
- id: "off"
platform: time
at: "09:00:00"
sensor:
- name: "Alarm"
state: "{{ trigger.id == 'on' }}"
or make an automation that does this with an input boolean
Oops, just did
So: To recap: You cannot use a template as your state. It's not possible based on how your sensor behaves.
Thanks, using a boolean which I turn on/off using 2 automations, automations also enable conditions, so I can say it should only turn on between 06:00 and 10:00
I know this is classic, but I cant find the answer, sorry: {% set threshold = states('input_number.battery_alert_level')|float(0) %} {{states.sensor|selectattr('attributes.device_class','eq','battery') |rejectattr('state','in',['unknown','unavailable']) |selectattr('state','<',threshold) |map(attribute='name') |list}} needs to map the number to be able to do the comparison.. should be possible with a double mapping shouldnt it? (and not use the namespace construction, which I have)
: {% set threshold = states('input_number.battery_alert_level')|float(0) %} {{states.sensor|selectattr('attributes.device_class','eq','battery') |map(attribute='state') |map('int',default=0) |select('<',threshold) |list}}... obviously doesnt work it just returns the numbers
Yeah it’s unfortunate, I want to add something that does this but I’ve been struggling to come up with a name and method to do it easily
So I am using a template sensor to track my phone's position using the wifi bssid it is connected to in my mesh network
Is there a better way of doing this, also for multiple phones? 🤔
Yes, there is a better way
Create a dict that maps BSSID to location and then use the sensor value as the key
Can someone help. I need clear_effects: url: "http://10.0.0.10/api/command/" method: post content_type: "application/json" payload: '{"command":"Effect Stop","multisyncCommand":false,"multisyncHosts":"","args":["24"]}'
to look like
url: "http://10.0.0.10/api/command/"
method: post
content_type: "application/json"
payload: '{"command":"Effect Stop","multisyncCommand":false,"multisyncHosts":"","args":["{{ state_attr( 'sensor.nhl_sensor', 'home_score' )}}"]}'```
but that gives me yaml errors
syntax?
so there is no way to pass an attribute as a string?
a sensor value in a restful call
You're trying to put a template there. You can't do that
well how then, would i get a current dynamic value from a sensor and use it to build an restful api call.
Thanks
Have to look into how to do that. Will try
What integration are you using there? A rest_command, a sensor, what?
The problem is that you're using the same quotes both inside and outside the template
i think this is working.. set_actbackground: url: "http://10.0.0.10/api/command/" method: post content_type: "application/json" payload: "{\"command\":\"Effect Start\",\"multisyncCommand\":false,\"multisyncHosts\":\"\",\"args\":[\"{{ state_attr( 'sensor.nhl_sensor', 'away_id' ) }}\",\"\",\"true\",\"true\",\"false\"]}"
its terrible but works possibly
testing now
yup that worked
but is there a better way to write that without escaping all the quotes?
I'm way new to yaml
freaking doc z's crew made me install HA.. now i'm challenging myself.
This is all for a live scoreboard on a projector in my window
and when the team scores the goal horn goes off on my house, audio and all
i got the live scores working, and the goal detection, game state detection. now working on changing the opposing team logo dynamically on the display based on away team ID
so now thats working
good deal
i have the following error message:
Invalid config for [sensor.template]: [state_class] is an invalid option for [sensor.template]. Check: sensor.template->sensors->realtime_consumption_a->state_class. (See ?, line ?).
These are my sensors:
https://pastebin.com/sxMgBa54
i understand that it wants me to remove state_class. But state_class is required for long term statistics (and me being able to add it to the energy section of homeassistant. How do i proceed?
You're using the legacy format and you need to use the new format for your sensor
Review the template sensor docs
Is this the correct syntax? https://pastebin.com/SZqgGKFp
You're missing some colons
ah, right i see
But that's the right format
thank you! i'll give this a shot (after adding the colons)
Alright yeah that seems to work however its still not showing up in "configure grid consumption"
One more question, i should be able to use {{ state_attr( 'sensor.nhl_sensor', 'away_id' ) }} as event data in a event triggered automtation?
hmm that didn't work
i think i got it
team_id: '{{ state_attr( ''sensor.nhl_sensor'', ''away_id'' ) }}'
Could it be that i'm missing a "last_reset"?
According to the documentation it shouldn't be required
for consumption in the energy dashboard you need:
state_class: total_increasing # or total
device_clas:: energy
unit_of_measurement: kWh
Hmmm
You can convert your power (W) values to kWh using the Riemann sum integral: https://www.home-assistant.io/integrations/integration
okay, that would be better
well actually it just shows the number of total imported watts, not kwh
but it's total_increasing at least
This should work then i guess:
- name: "Neurio Total Increasing"
unit_of_measurement: kWh
device_class: energy
state_class: total_increasing
state: "{{ (state_attr('sensor.neurio_raw', 'channels')[3].eImp_Ws | int) / 1000 }}"```
simply dividing W by 1000 won't give you kWh
youre right, i'm silly. you've got the h factor in there
Use the link above to convert it
Thanks, i'll do that
Question, do i feed the current value or the total_increasing into the integration?
I would have sworn I remember you writing some sort of 'double mapper' in this channel before, where in the first step you manipulate based on A:b, and in the final step you pick a:B to return as output. but stupidly enough I didnt bookmark that (can we even do that here?)
found something else I admit not to understand... filter: template: >- {% set threshold = states('input_number.battery_alert_level')|float(0) %} {% for s in states.sensor|selectattr('attributes.device_class','eq','battery') if s.state|is_number and s.state|float < threshold %} {{s.entity_id}} {%- endfor %} works fine in an auto-entities card. The is_number is used to filter out the entities with 'Not/Charging' . If the |is_number selects s.state to be a number, why then do I still need to set s.state|float in the comparison?
i set it up like this
- name: "Neurio consumption Total"
unit_of_measurement: W
device_class: power
state: "{{ state_attr('sensor.neurio_raw', 'channels')[3].p_W }}"```
and then the sensor
- platform: integration
source: sensor.neurio_consumption_total
name: energy_spent
unit_prefix: k
unit_time: h
round: 2```
the sensor provides realtime data in W, and i'm hoping the integration will turn it into kWh
Is it possible to define global macros (jinja macros) and use them in all value templates (jinja templates) ?
@jade inlet posted a code wall, it is moved here --> https://hastebin.com/uyaromijes
No
@jade inlet this channel is intended for jinja templates, your question is better suited in #integrations-archived. Please use a code share website to share your code when you ask your question there
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
Thanks for the reply, i managed to sort it out. massive oversight, I wasn't using unique naming.
So i'm really struggling to figure out how to build something on json attributes loaded through mqtt. Why aren't they showing in the trace?
- platform: mqtt
device_class: motion
name: 'testd'
state_topic: 'BlueIris/driveway/Status'
value_template: "{{ value_json.trigger }}"
json_attributes_topic: "BlueIris/driveway/Status"
json_attributes_template: >
{
"trigger": {{ value_json.trigger}},
"object": {{ value_json.memo.split(":")[0] }},
"type": {{ value_json.type}}
}```
What’s the value of trigger? What’s the value of object? What’s the value of type? If they are strings, then your issue is that you aren’t providing valid json because they need to be in quotes
Strings need quotes numbers and bools do not
- platform: mqtt
device_class: motion
name: 'testd'
state_topic: 'BlueIris/driveway/Status'
value_template: "{{ value_json.trigger }}"
json_attributes_topic: "BlueIris/driveway/Status"
json_attributes_template: >
{
"trigger": "{{ value_json.trigger }}",
"object": "{{ value_json.memo.split(":")[0] }}",
"type": "{{ value_json.type }}"
}
I don't have a solution that uses 2 maps. The problem with it is that you have to convert back and forth from float to string in order for the select to work.
is_number simply tells you if the state is a number. It returns true or false, nothing more. So you need to still use it. It does have a benefit though... you don't have to provide default to float.
Also, I added is_number as a test in 2022.2
so you can now do...
{{ states | selectattr('state', 'is_number') | ...
thats what I thought, but I still get the error TypeError: '<' not supported between instances of 'str' and 'float' on ```
{{states.sensor|selectattr('attributes.device_class','eq','battery')
|selectattr('state', 'is_number')
|selectattr('state','<',threshold)|list}}
is_number is true/false, it does not convert the string to a number. State is still a string
is_number just tells you that the state is a number and does not contain non-numeric symbols
right, so 'does not contain non-numeric symbols' is not the same as 'is type: number' ? which is what I figured it would mean
but i see. even though {{states('sensor.back_door_battery_level')}} is type: number, when we do {{states('sensor.back_door_battery_level' ) < threshold}} we need to use {{states('sensor.back_door_battery_level')|float > threshold}}
basics....
this makes perfect sense. thank you!
"LSjleknfasyoi7.3452" | is_number will return false
"3325.342342" | is_number will return true
that's all it does
it does not take "3342324.3423243" and convert it to 3342324.3423243
yes, I see, my confusion was in the next step, that after having established the state was a number, the comparison still needs the |float on the state, even though it is a float already (but it isnt because it is a template and that always is a string) . this leaves us no other option than the for loop (or a ns construction) and the direct template is useless in this case (because we can not set |float to that state selector)
Scarpe
Exactly what I was explaining. There is no way to filter without mapping it to a float. I've been wanting to add somethign that does the float comparison, however I've been blanking on a proper name and function that works for both floats and datetimes. It would also need the blessing of the main devs as this is going into helpers/templates, which I'm not the primary maintainer for.
Well I have an idea. I Just looked at selectattr's method and I think something like this would work if I implmeneted it.
... | selectattr('state', 'compare', '<=', value)
where compare would be a test that accepts a test but coverts the comparison to the values type.
x is compare('<=', 5)
compare would convert x to an int because the value 5 is an int
the problem is, does the word 'compare' make sense or should it be something else.
hi, im trying to make 1 sensor whit value = another sensor * number
im stuck in code
value_template: "{{ states('sensor.monthly_energy_general_kwh2')"
this is like im trying to get value from other sensor, but it fails at verification
if someone could help me, thanks!
To start, you're missing the closing }}
copy fail
value_template: "{{ states('sensor.monthly_energy_general_kwh2')}}"
could u see another fail?? thx
What is the error?
I guess you said it yourself, it is numeric_compare (float compare is what you used above, but numeric_compare would be more generic imho)
Is there any way to get the most common item from a list?
['foo','foo','bar']
return: 'foo'
that wouldn't work for datetimes though
that are strings or int
well, it would mean anything you use it with would be seen as if |float or |int was mapped? as if it was type: number on both sides
yes, but it would also need to work with datetime objects
like, it would see that it's comparing to a datetime and then attempt to convert the left side to a dateime
you specifically want 1 operator? because you could also use a dedicated one for the datetime comparison?
I don't want to create 10 tests, one for each type. It would confuse users on which one to use, espeically if they don't know what they have
which is usually the case
especially with datetime.... haha. yes I guess you're right about that
'compare' would be magnificent in that case, and take care of all the background mappings. when used in a numerical situation set both to float or int, and when used on datetimes, equalize those
or, given your syntax, simply use 'operator' and the 3d argument shows what to do, a bit like auto-entities does it
🤷♂️
I referred to #templates-archived message
There's no simple way
what's the complicated way to do this in a template if I may ask?
you have to come up with it
😂 thank you 😄
Most likely will involve you creating and using namespace with 2 lists
what should they contain?
to make it more clear I want to get the most common weather forecast condition. That would be making the announce: Today's weather would be mostly < the most common condition from the weather forecast>
This probably can be condensed but this is what I mean by complicated
{% set stuff = ['foo','foo','bar'] %}
{% set targets = stuff | unique | list %}
{% set ns = namespace(values=[]) %}
{% for item in stuff %}
{% set ns.values = ns.values + [dict(value=item)] %}
{% endfor %}
{% set ret = namespace(ret=[]) %}
{% for target in targets %}
{% set kvp = dict(name=target, count=ns.values | selectattr('value','eq',target) | list | count ) %}
{% set ret.ret = ret.ret + [kvp] %}
{% endfor %}
{% set highest = ret.ret | map(attribute='count') | first %}
{{ ret.ret | selectattr('count','eq', highest) | map(attribute='name') | list | first }}
it's not error proof either
well, i'm going down to the production line so, you're on your own after this 😉
thank you!
I am moving all of my templates over to the new format, how are people creating and keeping track of unique IDs? Or is it really not necessary to use them?
I came up with this
{% set some_list = ['foo','foo','bar'] %}
{% set ns = namespace(count=[], item=[]) %}
{% for item in some_list | unique | list %}
{% set ns.count = ns.count + [ some_list | select('eq', item) | list | count ] %}
{% set ns.item = ns.item + [ item ] %}
{% endfor %}
{% set max = ns.count | max %}
{{ ns.item[ns.count.index(max)] }}
let me try yours because the other one didn't quite work
yes that worked!
the other one gave me the second most common item
That makes no sense. They must be the same number then
Either way, the other template is more concise
If there are multiple items which are all mentioned the most, it will probably select the one earliest in the day in your use case
here's the list I tested:
['partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'rainy', 'rainy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'clear-night', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'sunny', 'sunny']
the method from petro returns 'partlycloudy' and the method from TheFes returns 'cloudy'
and cloudy is the winner
Thank you both for your time! I have learned something new today 🙂
ah yes, i used count instead of max
I still don't like using separate lists
1 sort and it breaks
in this case, there is no other way... or not?
the way I made it uses a list of objects that can be sorted but it will keep the name and value together
I'm surprised that I'm maybe the first one that would like to know which condition will be the most common today 😛
I tried that first, but then didn't really know with the list with combined item names and counts
{% set stuff = ['partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'rainy', 'rainy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'clear-night', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'sunny', 'sunny'] %}
{% set targets = stuff | unique | list %}
{% set ret = namespace(ret=[]) %}
{% for target in targets %}
{% set kvp = dict(name=target, count=stuff | select('eq',target) | list | count ) %}
{% set ret.ret = ret.ret + [kvp] %}
{% endfor %}
{% set highest = ret.ret | map(attribute='count') | max %}
{{ ret.ret | selectattr('count','eq', highest) | map(attribute='name') | list | first }}
that gets the right answer
And I don't fully understand what you are doing
it's making a list of dictionaries
{% set stuff = ['partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'rainy', 'rainy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'clear-night', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'sunny', 'sunny'] %}
{% set targets = stuff | unique | list %}
{% set ret = namespace(ret=[]) %}
{% for target in targets %}
{% set kvp = dict(name=target, count=stuff | select('eq',target) | list | count ) %}
{% set ret.ret = ret.ret + [kvp] %}
{% endfor %}
{{ ret.ret }}
returns
[
{
"name": "partlycloudy",
"count": 11
},
{
"name": "cloudy",
"count": 27
},
{
"name": "rainy",
"count": 7
},
{
"name": "clear-night",
"count": 1
},
{
"name": "sunny",
"count": 2
}
]
Yep, I get it now
this would also work
{% set stuff = ['partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'rainy', 'rainy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'rainy', 'cloudy', 'cloudy', 'cloudy', 'clear-night', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'partlycloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'cloudy', 'sunny', 'sunny'] %}
{% set targets = stuff | unique | list %}
{% set ret = namespace(ret=[]) %}
{% for target in targets %}
{% set kvp = dict(name=target, count=stuff | select('eq',target) | list | count ) %}
{% set ret.ret = ret.ret + [kvp] %}
{% endfor %}
{{ (ret.ret | sort(attribute='count') | last).name }}
if you end up with that you can also make that work
but instead of dictionaries make it a tuple
I must admit I don't really know what a tuple is. I have encountered them 🙂
{{ state_attr('group.some_group', 'entity_id') }} returns a tuple, although the template editor shows it as a list, if it is the only thing showing
{% set targets = stuff | unique | list %}
{% set ret = namespace(ret=[]) %}
{% for target in targets %}
{% set ret.ret = ret.ret + [ (target, stuff | select('eq',target) | list | count ) ] %}
{% endfor %}
{{ (ret.ret | sort(attribute='1') | last)[0] }}
That was annoying when I tried to add it to a list
Yeah, I figured that out
tuples are rigid in python. in jinja tuples and lists are very similar
because jinja limits lists
{{ (ret.ret | sort(attribute='1') | last)[0] }} this is exactly what I tried to do with my first attempt, but that did not work with a dict
with a dict...
you have to do
{{ (ret.ret.items() | list | sort(attribute='1') | last)[0] }}
but that wont work with a list of dicts
Well, it didn't work with a list of dicts
which is what you had
it's gaming the system
you shouldn't be able to create dictionaries dynamically in jinja
but you can get around that using fromkeys
or dict(**items)
but that requires a dict
and if you don't understand * vs ** then gaming the system is a pain
just for playing around.. this makes a single dict
{% set targets = stuff | unique | list %}
{% set ret = namespace(ret={}) %}
{% for target in targets %}
{% set kvp = [(target, stuff | select('eq',target) | list | count )] %}
{% set ret.ret = dict.fromitems(ret.ret.items() | list + kvp) %}
{% endfor %}
{{ ret.ret }}
good to use if you want to template the entire data section of a service call dynamically
I'll make a note of this
I totally forgot about that while struggling to dynamically create a dict a few days ago
Never again!
I say that every time and then have to remember how to get past it. The best way is to create a list of Tuples with string being the first item and the value being the second. Then use dict.fromitems
In templates, when do I use state: >- vs state: >?
> is used for multiline templates. Adding the hyphen just strips the newline at the end which HA strips anyway
I'm pulling a message from a sensor message[1].details this is a wall of text and I want to look for a specific sentence in there, how can I do that?
ok, so I don;t need the hyphen then?
Nope
Thanks, trying to get my code cleaned up
.share the output of that
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
And it's what's coming after Var: part that I'm trying to compare. (var = where, btw). But really It does not matter where my sentence will be, just if it contains Nordvästra Skåne then I want it to be true
It's Swedish weather warnings and it sucks because it gives you information from all around one region, but as the text contains more information on where exactly in that region the warning is set I would simply like it to just ignore everything that does not contain it
Should be only once but if it's always at the end I'm not to sure about
as long as it only appears once (and ideally only at the end), this should work:
{% set data = message[1].details %}
{{ 'Nordvästra Skånein' in data[data.find('Var:'):] }}
``` although you'll need to tweak `message[1].details` accordingly
Thanks! It's pretty annoying as it sometimes spams out alerts for the same thing but sometimes for different days. Is the best practice to sort on date and then just always select the [0] one? Or is there any better method to fetch the "nearest" in time in a set category? If that makes sence
The full message looks like this https://www.codepile.net/pile/ZPgroYkN it's like four different events but two of them is for the same kind of event Vind
And as you can see the first Vind event is not in Var: Nordvästra Skåne and is therefore not really interesting to me at all. If I want it to only show events that contains Var: Nordvästra Skåne
Or maybe best practice is to just do a if 0 contains string elif 1 contains string and so on
I'll have to take a look later
Is it possible to create an attribute template that I can use across multiple entities? I'm creating a complex attribute for my firesticks throughout my house to show what app is currently running on each one... I'd like to create the template once and have all my media_player.firestick entities use it. Is this possible or is there a different way I should be thinking?
service: notify.discord
data:
message: >-
{{ state_attr(trigger.entity_id, 'object') }} approaching on {{
trigger.entity_id }}
target:
- 'xxxxx'
How do i access friendly_name? I can see it in the trace but {{ state_attr(trigger.from_state, 'friendly_name') }} gives an error
Also, how do i go about experimenting with templates and triggers? the template developer tool is usually so useful but now it just says "trigger is undefined"
Am I able to pull the URL hash with Jinja? Trying to get an auto-entities template to automatically fill in the "area" filter by the hash
You did one thing in the actual code and then did something else in your attempt to get the friendly_name
The first argument to state_attr is the entity id, which you're already referencing in the other statement
state_attr expects an entity_id, not the old state
Whoops, Rob already said that
You can also take it directly from the from_state
As in just like trigger.from_state.attributes.friendly_name ?
Correct
@marble jackal that gives me Error: Error rendering data template: UndefinedError: 'dict object' has no attribute 'entity_id'
service: notify.discord
data:
message: >-
{{ state_attr(trigger.entity_id, 'object') }} approaching on {{
trigger.from_state.attributes.friendly_name }}```
That error is not coming from trigger.from_state.attributes.friendly_name. It is coming from trigger.entity_id
but trigger.entity_id is already working on its own
its only when i add the from_state that it bails
Well, are not referring to entity_id in that template, so it can not cause the error that entity_id does not exist
do you have multiple triggers in your automation, and are they all state triggers?
Are you activating this automation manually to test?
yeah, i think i did
Then there is no trigger, hence not trigger.entity_id
When you refer to the trigger, there needs to be a trigger 🙂 You can add an additional trigger which you can manually trigger easily, like an input_boolean, but in this case it will not have the attribute object so that part will not work
but is should give you the friendly name
well yeah that makes sense
It will probably result in something like null approaching on Test Boolean
But at least, it will show something 🙂
I've been playing a bit with this, it does allow you to do something like this:
{% set stuff = [ 'cloudy', 'cloudy', 'sunny', 'sunny', 'partly_cloudy' ] %}
{% set targets = stuff | unique | list %}
{% set ret = namespace(ret={}) %}
{% for target in targets %}
{% set kvp = [(target, stuff | select('eq',target) | list | count )] %}
{% set ret.ret = dict.fromitems(ret.ret.items() | list + kvp) %}
{% endfor %}
{% set max = ret.ret.items() | map(attribute='1') | max %}
{% set most = ret.ret.items() | selectattr('1', 'eq', max) | map(attribute='0') | list %}
The weather tomorrow will be mostly {{'' if most | count == 1 else 'a mix of '}}{{ iif(most | count == 1, most[0], most[0:-1] | join(', ') ~ ' and ' ~ most[-1]) }}
But of course you can do the same with the list of tuples
{% set targets = stuff | unique | list %}
{% set ret = namespace(ret=[]) %}
{% for target in targets %}
{% set ret.ret = ret.ret + [ (target, stuff | select('eq',target) | list | count ) ] %}
{% endfor %}
{% set max = ret.ret | map(attribute='1') | max %}
{% set most = ret.ret | selectattr('1', 'eq', max) | map(attribute='0') | list %}
The weather tomorrow will be mostly {{'' if most | count == 1 else 'a mix of '}}{{ iif(most | count == 1, most[0], most[0:-1] | join(', ') ~ ' and ' ~ most[-1]) }}
The posts above were linked to this post 🙂
can I ask how I could use that to extract the difference between these two lists: {{states.sensor|selectattr('attributes.device_class','eq','battery') |map(attribute='entity_id')|list}} and {{expand('group.battery_sensors')|map(attribute='entity_id')|list}}?
theres a 5 number difference when counting them... 😉
You don’t need to use that for the differences, just reject the items when they are in the other list
FYI [0:-1] the zero is implied if you omit it
[:-1] means everything before the last item
found an earlier issue I had... https://community.home-assistant.io/t/how-to-evaluate-difference-between-2-lists/116397/9 and using that template doesnt work in this situation though (set a and b to the templates I posted above)
this works in its most basic form:```
{% set a = states.sensor|selectattr('attributes.device_class','eq','battery')
|map(attribute='entity_id')|list %}
{% set b = expand('group.battery_sensors')|map(attribute='entity_id')|list %}
{{ (a | reject('in', b) | list + b | reject('in', a) | list) }}``` or, with a condition:
|map(attribute='entity_id')|list %}
{% set b = expand('group.battery_sensors')|map(attribute='entity_id')|list %}
{% set difference = (a | reject('in', b) | list + b | reject('in', a) | list) %}
{% if difference|length != 0 %} {{difference}}
{% else %} No difference
{% endif %}```
why do you want this?
bcs I had a manually created group of battery sensors, that seemed no longer up to date, and then selecting the device_class battery showed it contained more (and renamed entities...) this template now spits out the differences
I want my temp sensor to round down - I have this in my value_template '{{ value | round(0) }}'
I've returned now to my auto create group on startup so it is always up to date
but I still get .4 or .2
use |int ?
Make an automation that dynamically updates that group
yep, thats what I have now. ```automation:
- alias: Create battery group
trigger:
platform: homeassistant
event: start
action:
service: group.set
data:
object_id: battery_sensors_auto
entities: >
{{states.sensor|selectattr('attributes.device_class','eq','battery')
|map(attribute='entity_id')|list}}```
I see you ve done that though
I seem to recall that at some point I had issues with that, and then created the explicit group. Its a pain to maintain though with 70+ entities
I do all my groups dynamically now. I just made a script that fires an event that updates them when I want them to update
I also recently discovered group.set but at this moment I misuse it to store entitiy_id's to be shared between scripts 🙂
Hi,
am trying to assign min value of two sensors to a virtual sensor. The code below is not working, please advice.
Thanks!
value_template: >-
{{ (min(
(states('sensor.filtered_outdoor_temperature_1') | float)
(states('sensor.filtered_outdoor_temperature_2') | float)
)) | round(1)
}}
The items you want to compare should be in a list
at one point I drastically cut the amount of groups (helped a lot by the fact we can use auto-entities to represent things in the Frontend) but now see i still have 64. Updating these groups was an issue for the backend at that time, but now I dont seems to notice any issues with that any longer.
{{ min(
[states('sensor.filtered_outdoor_temperature_1') | float,
states('sensor.filtered_outdoor_temperature_2') | float
]) | round(1)
}}
Thank you!
but you should also use defaults in your float, and maybe reject those which are not numbers
I fixed some parantheses
I am very new to HA. The issue I am trying to solve is the sun, or warm wall of the house giving higher temp values. So I installed several and just want always to see the min one.
I also use filters before, to make sure there are no spikes etc.
I would do it like this:
{% set values = [
states('sensor.filtered_outdoor_temperature_1'),
states('sensor.filtered_outdoor_temperature_2')
] | select('is_number') | list
%}
{{ values | min | round(1) if values | count > 0 else 'none available' }}
But, you could also use the min /max integration as Tinkerer suggested. https://www.home-assistant.io/integrations/min_max/
So this will solve an issue if one of the sensors is unavailable?
I mean the code you suggested
yes, it will take out those which are not a number
and if all of them are not a number, it will show none available
cool, thanks a lot. Moving to HA, from Xiaomi app, love how flexible HA is.
wondering whether using the integration would not be much heavier on the resources though, as it continuously calculates all the derived sensors too. If it is only to reject 'unknown' that could easily be added to the template
It doesn’t continuously derive anything it only updates when the sensors update
You’re missing the map to a float
Unless that’s the availability template
oh, you are right
{% set values = [
states('sensor.filtered_outdoor_temperature_1'),
states('sensor.filtered_outdoor_temperature_2')
] | select('is_number') | map('float') | list
%}
{{ values | min | round(1) if values | count > 0 else 'none available' }}
@astral turtle correction in the template above
String comparison will give the wrong result if the number of digits is different. eg min([9,10]) will give 9, but min(['9','10']) wil give 10.
So as @mighty ledge mentioned, there should have been a map to float in the template
so you can no longer pipe max and min and if so why?
yes, I understand that, but given the fact those temp sensors update real time, the min/max would also change frequently? and when doing so, calculates a lot more than simply the highest of the 2. let alone records all of that, if not excluded.
You can, as the examples show. You just need to provide the right data types if you want the comparison and result to be as you expect
yeah managed to fix it
You can, you were just using it incorrectly before
It was a fluke that it worked the way people were using it before.
so a bug that was a feature. 😅
Yes, exactly 🤣
Can I still change "friendly_name" for templates in customize: if I do not use unique_id?
for templates? I think you mean template sensors, and yes you can, but why would you want to? You can simply set it in the yaml
yes, template sensors. How can I set it in yaml? I have tried using a friendly_name attribute. That did not work
Yes, I used name, which creates the entity and friendly name it appears. I don;t always want them to be the same. Is that when I should use unique_id intead of name?
unique_id just allows you to change the names in the UI
you don't use it "instead" of name
for example, in this basic template sensor, I define name: and "Chore Spa Water" this creates binary_sensor.chore_spa_water. In the front end, I only want to show "Spa Water". I only add "chore" because that is how I do my naming conventions.
template:
- binary_sensor:
- name: "Chore Spa Water"
state: "{{ states('sensor.chore_spa_water') in ['Tomorrow', 'Today', 'Overdue'] }}"
How can I keep my entity naming structure as is but alter what shows up on the frontend?
you have a few options: choose your names to reflect how you'd like them to show up in the frontend, you can probably still create a friendly_name via customization, use a card that allows you to customize the name there
I do all three depending on what I'm doing, but I've mostly stopped using customization and rely more on the first and last
Ok. I can do it on the card side. I did try customization and it did not seem to work. I made the change and reloaded but the friendly names did not change
Doesn;t require a restart does it?
"Reload core" will reload customizations, but the entity also has to update (or you need to force an update) to see the changes reflect
I have a LOCATION & CUSTOMIZATIONS reload button under server controls
Is it possible to filter some entities if they are in an area_name?
i.e
{{ states.sensor
| selectattr('attributes.area_name','eq','Bathroom') }}
I want to use a filter and NOT to check it through a for loop like this:
{% for x in states.sensor %}
{% if area_name(x.entity_id) == 'Bathroom' %}
...
I don't think area_name is an attribute
area_name(lookup_value) returns the area name for a given device ID, entity ID, or area ID. Can also be used as a filter.
Last sentence
using it as a filter in template editor works. tried to use exactly the same template for a sensor returns " no filter name area_name " though.
but I want to filter the state object by an area_name and that's not the way to use the filter
post the template
I've changed it to use the method instead the filter. I tried it now with the filter in version 2022.2.8 and it worked. Maybe there was an issue in 2022.2.7 ?
what filter was it?
| area_name
interesting
I'm running dev, which is partly behind 2022.2.8 but also partly ahead of 2022.2.8 (it's complicated) and it works for both
it's not an issue any more... maybe it was something in 2022.2.7
but that's irrelevant in my question...
anyway thank you 😄
np, I was just curious aobut what you were using that didn't work as a filter vs a function. There are functions that are not filters
like states, state_attr, is_state_attr, etc
Anyway to get the entity_id from the friendly name?
{{ states.binary_sensor.xiaomi_motion_8_occupancy.friendly_name }}
returns "Bathroom Motion Detector" as expected
(and works with the shorthand ... occupancy.name )
How to go the other way?
Can you explain what your end goal is?
The problem with going from the friendly name to wntity_id is that you can have more than 1 entity with the same name
I'm in deep... trying to turn off an input_boolean (called bathroom_occupancy) when catching the triggering event of timer.bathroom_motion_timer switching to idle.
trigger:
- platform: state
entity_id:
- timer.bathroom_motion_timer
- timer.bedroom_motion_timer
to: "idle"
I'm stripping off the room name ('bathroom') from the trigger.
Need to use that to construct the friendly name of the motion sensor to check it's state.
Why not rename your motion sensor entity id to contain the name ?
I’m trying to generate a list from a group of devices showing which have battery level below 60%. Im running into a some problems here
I can’t figure out how to show both the name and the state (battery %) in the generated list
This is what I’ve got right now..
{{ expand(‘group.battery_levels’) | selectattr(’state’, ’lessthan’, ’60’) | map(attribute=‘name’) | list }}
Hi, i have an sensor with a date for example 25-02-2022 my goal is how many days are left to today. That the sensor shows 6 days. Is that possible ?
Template sensor: {{ (strptime(states("sensor.some_date"), "%d-%m-%Y").astimezone() - now()).days }}
This can return the friendly names but not the battery state.. how do I display both?
What is your end goal? How do you want to use this data?
i want to generate a list of my personal devices (ipad, macbook, etc) that are low battery. i want to output the list in a format that is useful to put in a telegram bot message so it will tell me in the morning when i wake up if i forgot to charge something that i need for work
so i'm hoping for something like
Macbook Pro: 18%
Iphone: 26%
ipad: 44%
You'll need a for loop then, either creating a dictionary, or these strings directly.
how can I write a template for automation that will check how long sensor was in that condition?
I want an alert if my fridge temp is above +6C for over 5 minutes
Create a binary sensor and then use that in your automation
sorry could you explain the 'for loop'? still trying to figure all this out
Not right now, I'm on mobile while walking the dog
😅
how can I write a template for automation that will check how long sensor was in that condition?
I want an alert if my fridge temp is above +6C for over 5 minutes
Can only think of creating a binary sensor with {{ states('sensor.fridge_thermometer_temperature') | float > 6 }} and using that as a state condition with time of 5 minutes. But is there a way to do the same without extra sensors? Can we use template in the state contition?
Something like this:
{% set ns = namespace(batt=[]) %}
{% for item in expand('group.battery_levels') %}
{% if item.state | is_number and item.state | float < 60 %}
{% set ns.batt = ns.batt + [ ns.name ~ ': (' ~ ns.state ~ ')'] %}
{% endif %}
{% endfor %}
You can not use templates in state conditions, you can use a template condition
so, only the new sensor that is based on the same template?
But with a numeric state I would really advice to use the template binary sensor
thanks
Hi, can anyone help me out with this ?
Im trying to make an automation that will trigger by a change in state of a sensor and that will send me a notification to TG that tells me the old and new state , do i just use state_changed as trigger ? if so what do i use for action or rather what do i put in the TG notify action ?
this is my entity
sensor.batterychargestatus
it has different kind of status, float/bulk/off
trigger:
- platform: state
entity_id: sensor.batterychargestatus
action:
- service: notify.petunia
data:
message: "The sensor was {{ trigger.from_state.state }} and is now {{ trigger.to_state.state }}"
See the docs linked from the channel topic
alias: New Automation
description: ''
trigger:
- platform: state
entity_id: sensor.batterychargestatus
condition: []
action:
- service: notify.rons_tg
data:
title: Victron Boat - Charge Status Change
data:
message: "The state was {{ trigger.from_state.state }} and is now {{ trigger.to_state.state }}"
mode: single
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
this looks ok ?
You can test out in #botspam
there
The YAML looks good
if im firing this up should it send a message ? or need a change of state first ?
It needs to change state, but you can do that manually
See the pinned message in #automations-archived
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
Triggered by the state of sensor.batterychargestatus at February 20, 2022, 12:24:03 AM
Call service notify.rons_tg
Stopped because an error was encountered at February 20, 2022, 12:24:03 AM (runtime: 0.01 seconds)
required key not provided @ data['message']
i have this in my trace
action:
- service: notify.rons_tg
data:
title: Victron Boat - Charge Status Change
message: "The state was {{ trigger.from_state.state }} and is now {{ trigger.to_state.state }}"
Try that
yayyyy
awesome!
Thanks a lot !!
so this trigger.from_state.state method, it knows to relate itself to whatever entity was in the trigger in that automation?
Yes, that's the state object
See the docs linked from the channel topic - top of the window
I'm still trying to work through an issue I have with a REST template sensor.
So, I have a URL that returns an array of JSON objects. I need to somehow parse through that array, filter it down to 1 object and then set that as the sensor state attributes. How can I do that?
I know I can filter through it to grab a certain value for the sensor value, but the same doesn't seem to be true for state attributes.
Using some code that RobC gave me, I can pair down sensor value to the correct value, but I need some additional data with that for the sensor state attributes.
You'll need to be more concrete, what is the dataset, what do you have now, and what do you need?
For a template select, does anyone know what you put in options? https://www.home-assistant.io/integrations/template/#options
It just says "Template for the select’s available options." But like how does one give multiple options? I tried these two and neither worked:
options: "{{ ['stopped', 'paused', 'running'] }}"
options:
- stopped
- paused
- running
Sure, so basically I have some code here that works: https://pastebin.com/TcQU2hLA
I can use that in value_template to get the correct value for the sensor value. The problem is I need to also grab all the other attributes and set them as state attributes for the sensor.
if I just use $.data as the json_attributes_path - I just end up with the first entry in the array as the sensor attributes, which is wrong.
ideally, I'd use a template in my json_attributes_path to make sure I got the right value, but that's apparently not supported.
Basically what I have right now - value_template will select, $data.[index of next object with date in the future], while json_attributes_path will always be $data.[0]
I guess I'm trying to figure out how to correctly slice and dice this data to be consumable by HA. I can do it with jq in a one-liner, so it must be possible with the template sensor somehow
Ah I got it. This one was right:
options: "{{ ['stopped', 'paused', 'running'] }}"
The problem is that it when you use a trigger it doesn't run that template until the trigger occurs
selectattr('state','eq','on')|
rejectattr('attributes.type','eq','browser_mod' ) | list %}```
Is there any way that I can list the entities and then return a url link to that entity?
What kind of URL are you looking for? To link to what?
Does this:
{%- elif states.binary_sensor.haboard01.attributes.battery_level <= 5 %}
become this:
{% elif is_state_attr('binary_sensor.haboard01, 'battery_level', '<= 5') %}
no
second time in about 30mins that someone tries to add logic like that
'<= 5' this needs to be a value
{% elif state_attr('binary_sensor.haboard01', 'battery_level')|float <= 5 %}
because you're not testing equality to a value
only if you care about whitespace in the output
most of the time you do not. it generally only matters if you're trying to construct a string in a loop
thanks
Is there a way to test if any member of a list is not in another list, e.g. {{ [1, 2, 3 ] not in [3, 4, 5 ] }} ?
Not really
Iterate with namespace
123 asked me to add that the other day… might do it
You can filter the list based on the other list and see if the count drops
That last bit is what I would do. Seems straightforward
{% set list1 = [1, 2, 3] %}
{% set list2 = [4, 5, 6] %}
{{ list1|reject('in', list2)|list|count != list2|count }}
{% set list1 = [1, 2, 3] %}
{% set list2 = [3, 5, 6] %}
{{ list1|reject('in', list2)|list|count != list2|count }}
False, True
Nice. Thanks folks.
Rob, should that be {{ list1|reject('in', list2)|list|count != list1|count }} for lists with unequal numbers of elements?
Yeah, you're right
Point is whether any items were rejected
Or you could use select and just check > 0
Out of curiosity... can yaml merge key <<: be used together with !include ?
Nope
Hi guys, I was told this is the proper place for this question, so here goes:
Hi guys, I believe this should be simple but just can't figure it out. So I have a template sensor -just a different representation of day/date- and would like to show year in '22 format. So how do I write ' character? I've tried with \ but no luck (with " works but ' doesn't). This is my current value: value_template: "{{ as_timestamp(now()) | timestamp_custom('%a, %d %b %y.') }}" Thanks!
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
I was given advice to try with '"'"' but doesn't seem to work
Back ticks
See the bot message, and you can test in #botspam
Indeed, see #botspam message in there
The snippet you posted:
value_template: "{{ as_timestamp(now()) | timestamp_custom('%a, %d %b %y.') }}"
does seem to work
Apparently I'm too stupid to follow a simple format example
Thanks
It does work, but it shows year as 22. and I want to show it as '22.
I miss the ' character
value_template: "{{ as_timestamp(now()) | timestamp_custom('%a, %d %b \'%y.') }}"
That's a lot more robust than the way I suggested. I think I need another cup of tea. Sheesh <embarassment>
Unfortunately still doesn't work for me (as I said not clear enough) in original post
found unknown escape character "'"
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
is the error I get
Share the whole thing using a code share site
Yes, would like to see the whole thing. I think there's more at play here from your other error in the first answer.
Ok, and .. what's the context of those three lines?
There's supposed to be more above it... what's there?
Ok, we're getting closer
What comes above
- platform: template
```?
As I said, please forgive my dumbassery and have patience 🙂

I'm trying to lead you to give us the information we need
If you don't want help, feel free to just say 😉
No no, it just takes me a while to understand what you mean to say 🙂
hopefully it's all in now
I have some other sensors so cannot simply paste all
That's enough, it's the full context, which is what's needed
Somebody who gets Jinja escaping will hopefully be able to help you
\'
From what I was able to google it should work with \ but unfortunately it doesn't
So you mean value_template: "{{ as_timestamp(now()) | timestamp_custom('%a, %d.%b \'%y.') }}"
Yep
It just doesn't, I get error
Error loading /config/configuration.yaml: while scanning a double-quoted scalar
in "/config/configuration.yaml", line 62, column 25
found unknown escape character "'"
in "/config/configuration.yaml", line 62, column 80
- platform: template
sensors:
day_date_short_eu:
friendly_name: "Day/Date short EU"
value_template: >
{{ as_timestamp(now()) | timestamp_custom("%a, %d.%b '%y.") }}
YES!!! THANKS @mighty ledge for help and @arctic sorrel for putting it down to my level!! 😃
hi all. Any idea of how to configure an Aqara vibration sensor? see this post: https://community.home-assistant.io/t/how-to-manually-configure-an-aqara-vibration-sensor/394617
hey there.
could anyone assist me with a sensor? It always shows as not available
If I change the value to states it works, but the states are switched (when it's wet it states dry and the other way around)
sensors:
regensensor:
unique_id: "123070995"
friendly_name: "Rainsensor"
device_class: moisture
value_template: >-
{{is_state('binary_sensor.rain')}}
icon_template: >-
{% if is_state('binary_sensor.rain', 'off') %}
mdi:weather-rainy
{% else %}
mdi:water-off
{% endif %}```
Try {{ is_state('binary_sensor.rain', 'on') }} for your value_template
will try that. thanks
The problem was that you didn't provide anything to compare the value to
As you did in the very next instance
that makes totally sense! Thank you guys - it is working now 🙂
👍🏼
Hi!
i want to print a list off all scripts with the entity_id that have the word effect
{{ states.script|map(attribute='entity_id')|list }}
this lists all the scripts i got but i dont know how to filter by keyword...
selectattr('entity_id', 'search', 'thingtosearchfor')
I'm close to the solution: how can I set payload_on, for a binary sensor as "vibrate" or "drop" or "tilt"? I can only set it as: payload_on: vibrate
You can use the value_template to account for that
Have it output 'on' if the vibration mode is any of those, then your payload_on is just 'on'
hoping someone could help me, I have a REST API that I'm pulling data from. It returns an array of dictionary objects. I want to use one of those dictionary objects (NOT the 0th one) for state attributes, but i can't find a way to do that.
How do you know which one? And what part of the dict do you want the state to be?
~share the output
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
value_template: >
{{ value_json["ZbReceived"]["vibrazione-1"]["AqaraVibrationMode"] in
('vibration', 'tilt', 'drop') }} ...?
The correct one should be the one with the next date after today.
Oh! I have a related question, I have an array of dictionaries and I want them all (solar forecast data from local weather service), so far I only see the first one.
(which has been plotting nicely on a sensor, but like, the next hour's forecast isn't going to get me far in the long run.)
I would use a list, but yes
It's the same thing you helped me with before and the code you wrote gets me the right value(s) for the value_template but the actual attributes are wrong.
{
data: [
{ date: '2022-01-01' }, // <--- This one gets picked because it's the 0th
{ date: '2022-02-21' }, // This is the one that SHOULD get picked
]
}
then I just have to add "payload_on: on" ?
I thought I provided a solution for that
your solution gets me the right value for the sensor value, but not the state attributes
payload_on: 'on'
thanks, let's try
you need to actually output 'on' from that template, though, and you're not
Here's your solution code
https://pastebin.com/TcQU2hLA
(more or less)
value_template: >
{{ 'on' if value_json["ZbReceived"]["vibrazione-1"]["AqaraVibrationMode"] in
('vibration', 'tilt', 'drop') else 'off' }}
you just want the same kind of thing for the attributes
I agree, but I can't use a template for json_attribute_path hence my dilemma
doesn't seem to work. Here is the complete conf:
- platform: mqtt
name: "vibrazione-1"
off_delay: 15
state_topic: "tele/tasmota_zbbridge/SENSOR"
value_template: >
{{ 'on' if value_json["ZbReceived"]["vibrazione-1"]["AqaraVibrationMode"] in
('vibration', 'tilt', 'drop') else 'off' }}
payload_on: 'on'
device_class: window
'Doesn't work' how?
I can't see the state change on lovelace. This worked, instead:
- platform: mqtt
name: "vibrazione-1"
off_delay: 15
state_topic: "tele/tasmota_zbbridge/SENSOR"
value_template: '{{ value_json["ZbReceived"]["vibrazione-1"]["AqaraVibrationMode"] }}'
payload_on: vibrate
device_class: window
only for vibrate, of course
yes
can get the json payload and test against it
how can I test it?
use some sort of MQTT explorer to see what payload you are actually getting
it's pretty straightforward
phnx I use the tasmota console. and the previous configuration works
first hint is, you used "vibration" in your "not working" example but "vibrate" in your "working" one
phnx damn you re right!
I think you should just create a template sensor based on the REST sensor. It supports templates for the attributes
All fixed! thanks to RobC and phnx
one last thing: do you know an appropriate icon for this sensor? I used device_class: window, but I remember there's a proper one, which I can't find in the list in https://www.home-assistant.io/integrations/sensor/
only you can decide what's "appropriate" 🙂
are you looking for a cube or something like that?
I remember that zha chooses a sort of ((( o ))) icon for it
but I did not take note of it. but it shows a vibration
you can look here: https://materialdesignicons.com/
Right, but how do I get the data from the rest sensor to the template sensor? Like, sure I can probably grab the single value from the rest sensor, but how would I access the rest of the data?
but they are not the HA's default icons. I need the default icon automatically used by zha for these sensors
dump all the attributes into the rest sensor and use the template sensor to pull what you want
Doesn't the rest sensor have to be a single scalar value?
the state, but I said "attributes"
Oh right, so the state attributes of that sensor is <huge array of data>?
Then I do my fancy templating stuff in the template sensor.
is it possible to make a rest switch for the flash next to the laptop webcam?
Impossible to know. Is there a service that controls that that you want to trigger?
I don't know, it's the light next to the webcam and windows has control of it so - possibly
HA just sends a REST command, so you'd need to find something that runs on the laptop that controls the flash. Not a #templates-archived
oh okay thanks
It occurs to me that you should just use a trigger-based template sensor with an MQTT trigger, rather than an MQTT sensor and separate template sensor
Normally, I use something like {{ value_json["ENERGY"]["Power"] }}' to get the value of the sensor. However, a Shelly 2.5 provides two power values in a bracket, one for the left channel and another one for the right channel. The output looks like
{"Time":"2022-02-20T18:40:01","Switch1":"ON","Switch2":"OFF","ANALOG":{"Temperature":55.6},"ENERGY":{"TotalStartTime":"2022-01-28T21:01:26","Total":0.094,"Yesterday":0.000,"Today":0.000,"Period":[0.00,0.00],"Power":[0.00,0.00],"ApparentPower":[0.00,0.00],"ReactivePower":[0.00,0.00],"Factor":[0.00,0.00],"Frequency":50,"Voltage":236.32,"Current":[0.000,0.000]},"TempUnit":"C"}
How can I modify the template to extract the first power value from the bracket?
it's a list, so {{ value_json["ENERGY"]["Power"][0] }}
{% set data = {"Time":"2022-02-20T18:40:01","Switch1":"ON","Switch2":"OFF","ANALOG":{"Temperature":55.6},"ENERGY":{"TotalStartTime":"2022-01-28T21:01:26","Total":0.094,"Yesterday":0.000,"Today":0.000,"Period":[0.00,0.00],"Power":[0.00,0.00],"ApparentPower":[0.00,0.00],"ReactivePower":[0.00,0.00],"Factor":[0.00,0.00],"Frequency":50,"Voltage":236.32,"Current":[0.000,0.000]},"TempUnit":"C"} %}
{{ data["ENERGY"]["Power"][0] }}
-> 0
@inner mesa Seems to work. Thank you very much. I thought the solution must be much more complicated.
I am getting this warning in the log for a few template sensors. How do I go about settnig a "default" to avoid this issue?
Template warning: 'float' got invalid input 'unknown' when rendering template '{{ states('sensor.qbittorent_down_speed') | float / 977 }}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1
thanks, just found that and reading through it now
selectattr('state','eq','on')| rejectattr('attributes.type','eq','browser_mod' ) | list %}```
Is there any way that I can list the entities and then return a url link to that entity?
The url will link to the device page
So it really is as simple as: '{{ states('sensor.qbittorent_down_speed') | float(0) / 977 }}'
if you want it to be zero if the entity has a non-numeric value
I have a sensor (sensor.dark_sky_precip) that returns a state of "unknown" when there is no precipitation. I have the following template binary sensor that I need to only have a state of "on or "off" because it triggers a switch based on it's state. But, when the dark_sky sensor is "unknown" so it my template binary sensor. How can I fix this?
- binary_sensor:
- name: "Snowing"
state: "{{ states('sensor.dark_sky_precip') in ['snow', 'sleet'] }}"
availability: "{{ not states('sensor.dark_sky_precip') in ['unavailable'] }}"
just remove the availability line
all that will do is sometimes make the state "unavailable"
This still results in the binary_sensor showng unknown
seems unlikely
you said this:
I have a sensor (sensor.dark_sky_precip) that returns a state of "unknown"
I don't see how that can result in binary_sensor.snowing to be "unknown", which is what you're defining here
I know but it is. It has been very difficult to figure out.
This {{ states('sensor.dark_sky_precip') }} in the template editor returns "unknown"
This {{ states('sensor.dark_sky_precip') in ['snow', 'sleet'] }} in the template editor returns "False"
But the binary sensor entity is returning "unknown"
{{ states('sensor.whatever') }}
{{ states('sensor.whatever') in ['foo', 'bar'] }}
-> unknown, False
- binary_sensor:
- name: test
state: "{{ states('sensor.whatever') in ['foo', 'bar'] }}"
-> off
cannot reproduce
I think you didn't reload templates
I have reloaded multiple times
Could it be because the sensor is actually returning the string "unknown"? Meaning the state is not not known, it is actually "unknown"? Not sure that makes sense.
I just changed sensor.dark_sky_precip to sensor.dark_sky_icon which has a state of "clear night". The binary sensor still returns "unknown"
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
- HAOS & Supervised use
ha core check - Container uses
dockercommands - Core requires you to activate the venv first
perhaps you're just looking at the wrong entity
I have nothing more to add. It works for me, 2+2=4
ok
hi all, i have an mqtt sensor that i'm using a script to update.. i have an automation that is updating an input_boolean whenever a 0 or a 1 is received but for that object, last_changed and last_updated seem to only change when the value changes (0 to 1 or 1 to 0). from what i can find, it seems duplicate values are ignored. i'm looking to send a notification if the script breaks, basically if mqtt is no longer receiving anything.
let me know if there is a better way... but i set up an input_datetime and along with updating the input_boolean mentioned above, i am also updating that input_datetime with the current datetime. so now i have an input_boolean that updates with the current datetime any time a payload is received on that mqtt topic.. this works fine, but how do i get the 'secondary info > last changed' data?
it doens't seem to like these:
"{{ states('input_datetime.garage_mqtt_updated.last_changed') }}"
"{{ state_attr('input_datetime.garage_mqtt_updated', 'last_changed') }}"
i thikn i tried that also, it gives me ""
was reading that also. it returns "" for me but i have it on my lovelace dashboard and i can see plain as day "2 seconds ago" etc..
{{ states.input_datetime.date_test.last_changed }} -> 2022-02-20 20:30:32.322301+00:00
review your entity_id, I suppose. or it's another rift in the spacetime continuum
hmm, maybe it's how i'm setting my input_datetime. is this not right?
service: input_datetime.set_datetime
data:
timestamp: '{{ now().timestamp() }}'
target:
entity_id: input_datetime.garate_mqtt_updated
test_datetime:
sequence:
service: input_datetime.set_datetime
data:
entity_id: input_datetime.date_test
timestamp: "{{ now().timestamp() }}"
works fine for me
hmm, i'll play with it. thanks
LOL nvm.. user error of course, thanks
"garate", wow. sorry about that
instead of garage
@inner mesa well, I learned my lesson and sorry for wasting your time. An additional part of my template (that I did not think was relevant - hence, learned my lesson) was delay_off of 2 hours. This means this means that when I do a restart or reload during the delay period, there are issues. I found a thread in forums and there is an issue open about it as well.
np, glad you found it
Looking for some help on pulling data from a json file into HA.
Using this json file:
https://www.nascar.com/cacher/2022/1/race_list_basic.json
How can I pull just the info from say "race_id": 5146 I can do it if I use value_json[3] since its the 3 entry. for the life of me though, I cannot figure out the proper syntax for calling it with out knowing its position in the array?
Any ideas?
Uh, I'm not using MQTT
Oh, never mind. Confused you with someone else
np
I think my syntax for json_attributes_path is wrong. When I fill in "$.data" the logs say: " JSON result was not a dictionary or list with 0th element a dictionary "
the API response looks like this:
{
status: 200,
data: [],
}
Therefore, $ should be the root object(which is a dictionary) an $.data should be a list with a 0th object.
I should point out that $.data.0 works just fine
As does $data.1, $data.2 etc.
It would be useful if there was a way to get HA to spit out exactly what it was seeing
I'm trying to store a list with dicts in a file, using the file integration. The message used for the notify service only accepts strings, so I had to wrap it in double quotes.
Now I want to use that data. I can remove the double quotes using replace and the template editor clams the result is a list, but it's still a string
Example:
{%- set dataset = "[ {'entity_id': 'media_player.beneden_groep', 'friendly_name': 'Beneden groep', 'state': 'off', 'media_content_id': 'no media_content', 'media_title': 'no title', 'media_artist': 'no artist', 'media_content_type': 'no type', 'app_name': 'no app', 'entity_picture': 'no pic', 'volume_level': 'no volume', 'media_position': 86399, 'data_source': 'event_script'}, {'entity_id': 'media_player.boven_groep', 'friendly_name': 'Boven groep', 'state': 'off', 'media_content_id': 'no media_content', 'media_title': 'no title', 'media_artist': 'no artist', 'media_content_type': 'no type', 'app_name': 'no app', 'entity_picture': 'no pic', 'volume_level': 'no volume', 'media_position': 86399, 'data_source': 'event_script'} ]".replace('"','') %}
{{ dataset[0] }}
results in [
Is there a way to get this working?
{%- set dataset = "[ {'entity_id': 'media_player.beneden_groep', 'friendly_name': 'Beneden groep', 'state': 'off', 'media_content_id': 'no media_content', 'media_title': 'no title', 'media_artist': 'no artist', 'media_content_type': 'no type', 'app_name': 'no app', 'entity_picture': 'no pic', 'volume_level': 'no volume', 'media_position': 86399, 'data_source': 'event_script'}, {'entity_id': 'media_player.boven_groep', 'friendly_name': 'Boven groep', 'state': 'off', 'media_content_id': 'no media_content', 'media_title': 'no title', 'media_artist': 'no artist', 'media_content_type': 'no type', 'app_name': 'no app', 'entity_picture': 'no pic', 'volume_level': 'no volume', 'media_position': 86399, 'data_source': 'event_script'} ]" | to_json %}
{{ dataset[0] }}
Gives me ", also if I leave the replace in
ah, got it. I need to use from_json, but for that to work, I need double quotes inside
This probably can be done more efficient, but for now it works:
{%- set dataset = "[ {'entity_id': 'media_player.beneden_groep', 'friendly_name': 'Beneden groep', 'state': 'off', 'media_content_id': 'no media_content', 'media_title': 'no title', 'media_artist': 'no artist', 'media_content_type': 'no type', 'app_name': 'no app', 'entity_picture': 'no pic', 'volume_level': 'no volume', 'media_position': 86399, 'data_source': 'event_script'}, {'entity_id': 'media_player.boven_groep', 'friendly_name': 'Boven groep', 'state': 'off', 'media_content_id': 'no media_content', 'media_title': 'no title', 'media_artist': 'no artist', 'media_content_type': 'no type', 'app_name': 'no app', 'entity_picture': 'no pic', 'volume_level': 'no volume', 'media_position': 86399, 'data_source': 'event_script'} ]".replace('"', '').replace("'", "|").replace('|','"') | from_json %}
{{ dataset[0] }}
cool
Had to rewrite the dataset to a ordered dict though, to be able to retreive it from the file using json_attributes. But thanks to the experts here I knew how to do that 🙂 (below only a part becuase of the line limit
{%- set ns = namespace(info={}) %}
{%- for entity in expand(integration_entities('cast')) %}
{%- set data = { entity.entity_id:
{ 'friendly_name':entity.attributes.friendly_name,
'state': entity.state,
'media_content_id': entity.attributes.get('media_content_id', 'no media_content'),
'media_content_type': entity.attributes.get('media_content_type', 'no type')}
}
%}
{%- set ns.info = dict(ns.info, **data) %}
{%- endfor %}
Shouldn't have marked the code as yaml 😛
I have a value template that is giving me the correct temperature, but I am generating an error in the logs. Works fine in the developers tools.
friendly_name: High_Forecast
unit_of_measurement: '°F'
value_template: "{{ state_attr('weather.17_seaview_avenue', 'forecast') [0].temperature}}"```
None has no element 0 in the logs.
I only get that if I use the wrong entity_id
so I don't see how it can both return the right value and give that error in the log
does it only happen on startup?
yes
{% set forcast = state_attr('weather.17_seaview_avenue', 'forecast') %}
{% if forcast is not none %}
{{ forcast[0].temperature }}
{% endif %}
Thanks. I got it. I'll reboot and see if it fixes the error. Rebooted and this error is fix. I have a couple of more that are similar that should be easy to follow your example. I do see some other start up errors due to integration not ready. Are these bugs are working as designed?
you can also use the |default option
Is it possible to combine 2 ikea blinds as "one" unit ?
something like {{ (state_attr('weather.17_seaview_avenue', 'forecast')|default('NA') }} should work @amber hull
and mabye change the device type name: roller blind to curtains
@strange geode you can create a group
Okay cool, and is is possible to set the "device type" ?
Thank you so much, so in cutomize, i will define the class type right ?
- Do i have to put other informations here to have the same functions ?
sorry im new to HA
if you create a cover group, it will have all the cover functions
Okay thank you i will try that..
@fast vigil I get TemplateSyntaxError: unexpected '}', expected ')' in the template editor.
there is one more closing parentheses required
{{ (state_attr('weather.17_seaview_avenue', 'forecast'))|default('NA') }}
Also this gives all the values, not the "0" temperature I am looking for.
I try difference options so I can try and understand templates better
because forecast is not empty
see my post
I understood what the code does with Petro.
{{ state_attr('weather.17_seaview_avenue', 'forecast')|default(['NA'])[0] }}
TemplateSyntaxError: expected token 'end of print statement', got '['
{{ (state_attr('weather.17_seaview_avenue', 'forecast')|default(['NA']))[0] }}
back to all the values
yes, that is because forecast is not empty
I'm out, feel free to chew on that
the |default(['NA']))[0] part is only used when forecast is none
value_template: "{% set forecast = state_attr('weather.17_seaview_avenue', 'forecast') %}{% if forecast is not none %}{{ forecast[0].temperature }} {% endif %}" give me one
like in petro's code
I'll stay with this until I have time to figure out what each of your options are doing. Thanks as always for teaching me different ways of doing things
{{ (state_attr('weather.17_seaview_avenue', 'forecast')[0]|default(['NA']))[0] }}
this should work
ha
I avoid default because it's not smart enough for what I want it to do
{{ (state_attr('weather.wf_udp', 'forecast')|default([{'temperature':'NA'}], True))[0].temperature }}
gotta add the , True to get it to recognize null
yah, that's probably the best way to get a 1 liner
you can also use... selectattr
but not sure if selectattr will bitch if it's fed a None
{{ state_attr('weather.wf_udp', 'forecast') | map(attribute='temperature') | first }}
something like that
probably would need a default too after first
Can a template be used with delay_off when using minutes? I am not been able to get it to work with:
delay_off:
minutes: "{{ template }}"
do...the docs say it is?
I'm just going to look it up there
well, taking that back, it does seem to hate that
but this does work:
- binary_sensor:
- name: test
state: "{{ states('input_text.test') in ['foo', 'bar'] }}"
delay_off: "{{ '00:05:00' }}"
"00:{{ template if template | int >= 10 else '0' ~ template }}:00"
Something like this maybe?
yes, but it's way more complicated and the docs are ambiguous
the docs imply that delay: xxx works the same way
delay_off: "{{ template | int * 60 }}"
Good know that I did not miss anything. The only examples I found in the docs were seconds-based. I just converted my minutes to seconds and did it that way.
hello