#templates-archived
1 messages Β· Page 119 of 1
Here you have the returned xml file from GET request to the camera
And my template
If it helps, the error:
Logger: homeassistant.helpers.entity
Source: helpers/template.py:1214
Update for switch.cam_piscina_mail fails
@copper seal expand the error by clicking on it to reveal the full error.
Can I add a pic of full error?
You can just copy / paste the error?
@copper seal posted a code wall, it is moved here --> https://paste.ubuntu.com/p/C3wNxsWNbZ/
You have to add a check to validate that you actually have information in value
it's erroring out because the regex is failing on an empty string
{% if value %}
{% set status = value | regex_findall_index('(?<=id>).*?(?=<\/id>)') %}
{% if status == "email" -%}
true
{%- else -%}
false
{%- endif %}
{% else %}
false
{% endif %}
It also helps if you properly indent so you can see your logic
{% if value %}
{% set status = value | regex_findall_index('(?<=id>).*?(?=<\/id>)') %}
{% if status == "email" -%}
true
{%- else -%}
false
{%- endif %}
{% else %}
false
{% endif %}
Then the contents contain other information and regex is not finding a result
Is there a way to check the content on HA? On win cmd using curl I get that xml code
Hi all. Unsure if this is the right channel but here goes. On my current system I have some logic to "record" today max / min values (for a temperature sensor), 7 days history rainfall, and so on. I use this, e.g. to decide whether I need to turn on the sprinklers. E.g. if today temperature was above > say 28 then water the grass no mater what. I also know each m2 of grass needs Xm3 of water per Y days so based on rainfall history I can decide if the grass needs to be watered or not...anyway was trying to understand what's the best way to store this data. I was thinking about custom attributes but for what I could gather I'd need to manually create these attributes on every device I'd want to monitor plus would also need to create an automation per device to update the attributes accordingly. Is there anyway to just create a "template" for every temperature sensor for example that would automagically do this?
I also found this https://www.home-assistant.io/integrations/statistics which seems to be the "official" way of gathering statistics although if I understood correctly what it does is to create a new device with the statistics?
if the <id>email</id> is not guaranteed to be in the string, then you should use regex_search instead
then your template would just be:
{{ value | regex_search('(?<=id>)email(?=<\/id>)') }}
that returns true/false if <id>email</id> exists or not.
hey I'm trying to figure out how to get the datetime units here converted to int so i can do <= & >=. Any hints?: {% set start = (now().timestamp() * 1000) | int %}
{% set end = start + 86400000 %}
{{ state_attr('weather.openweathermap', 'forecast') | selectattr('datetime', '>=', start) | selectattr('datetime','<=', end) | map(attribute='temperature') | list | max }}
i know there's an as_timestamp function, but not sure how it would fit in here
there are hundreds of ways to compare times, you don't really need to use int's anymore. What's the end goal?
Hi everyone, how can I check if a timestamt (attribute of an entity) is two days older than now() ?
@mighty ledge was trying to replicate this template from Tom7320: https://community.home-assistant.io/t/how-to-automate-based-on-weather-temperature-forcast-for-current-day/193749/14
and that doesn't work out of the box?
seems like 'datetime' would be a string
yeah doesn't work in the template tester, says: TypeError: '>=' not supported between instances of 'datetime.datetime' and 'float'
just make start now() and call it a day
then you'd be comparing 2 datetimes
set end to now() + timedelta(days=5) or whatever
That is a good hint, I need something like
strptime(state_attr('sensor.some_sensor','timestamp'), "%d-%m-%Y").timedelta(days=2)
But this returns: UndefinedError: 'str object' has no attribute 'timedelta'
you'd need to know the actual value of that attribute
The value is set by the integration, it is e.g. "2021-02-09 09:07:37.356957"
it might already be a datetime
do state_attr().day
if that returns something you can skip the strptime stuff and just use it directly
It returns UndefinedError: 'str object' has no attribute 'timedelta'
that's not what i asked you to do
correct
It doesn't work for my sensor: UndefinedError: 'str object' has no attribute 'date'
then you need to do a proper strptime() then
aha thanks @dreamy sinew
@strong idol '%Y-%m-%d %H:%M:%S.%f'
you have the parse the entire thing even if you don't need all of it. otherwise it doesn't know what you are doing
This time it works: {{ strptime(state_attr('sensor.some_sensor','timestamp'), '%Y-%m-%d %H:%M:%S.%f').date() }}
This is returning the date correctly
yep because now you have a proper datetime object
without the .date() you can do timedelta now as i showed in my example
how to put it right: - conditions: - '{{ event == 1002 }}' - '{{ is_state('media_player.spotify_stefan', "playing") }}'
Ok, let me try
when I remove single quotes from media_player.spotify_stefan I have an erorr in my logs
you're mixing quotes
Error during template condition: UndefinedError: 'media_player' is undefined
Now I am getting UndefinedError: 'datetime.datetime object' has no attribute 'timedelta' π©
because that's not how i used it in my example
Almost there ... can I somehow only get y-m-d from now()?
same idea. .date()
but you should do the comparisons with the full objects
they have actual numerical handling if you compare them directly. If you convert to the strings you're at the mercy of string math
Still not there π Feels like this is impossible to solve.
I am using: {{ (strptime(state_attr('sensor.some_sensor','timestamp'), '%Y-%m-%d %H:%M:%S.%f')) < (now() + timedelta(days=-2)) }}
to check, if the first timestamp is older than now() minus two days.
This returns: TypeError: can't compare offset-naive and offset-aware datetimes
Still getting the same error, also with utcnow()
this works
{{ sensor < (utcnow().replace(tzinfo=None) + timedelta(days=-2)) }}```
should probably still use utcnow() though
depending on what the sensor actually uses
@strong idol
This works! π₯³ Thank you so much!!
Is it a bad idea to put everytthing in one line, like:
{{ (strptime(state_attr('sensor.some_sensor','timestamp'), '%Y-%m-%d %H:%M:%S.%f')) < (utcnow().replace(tzinfo=None) + timedelta(days=-2)) }}
not really. just makes it harder to read
Ok, sounds good. Thanks a lot - I am gonna put this to use now. π
@novel crystal posted a code wall, it is moved here --> https://paste.ubuntu.com/p/KJzJnR69jv/
that "template" is being treated as text and not rendered so clearly I'm missing the point
No, you have to create a template sensor
there's no way to change states of things without creating new entities
thank you @mighty ledge. so much to learn!
trying to figure out what's the best way to, for example, keep track of daily max / min temperature readings for all temperature sensors
Hello all, is there a way to apply wildcard to the entity_id in a service data template? Ie. apply the service to all entities in the light domain that include the number 1 in their id. I have tried using a light group but some of the special light attributes do not pass through a group.
OR , can I use a condition to choose which entities are applied?
{{ states.light|map(attribute='entity_id') }}
Anybody got a good video on templates they would recommend
Videos are great to watch but are usually out of date QUICK.... Best to read the DOCS
in this case
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
but also check the HA docs for templates
there are a few HA specific extensions that are exposed
In a template sensor, is there a way to keep the existing value of the sensor on a if/else branch?
I'm using a unifi controller to do some room presence detection, and when a phone isn't connected to an AP, I'd like the ap sensor to just retain the last AP
value_template: >-
{% if state_attr('device_tracker.pixel4a', 'ap_mac') == '74:ac:b8:82:05:e9' %}
living
{% elif state_attr('device_tracker.pixel4a', 'ap_mac') == '74:ac:b8:82:04:40' %}
studio
{% elif state_attr('device_tracker.pixel4a', 'ap_mac') == '74:ac:b8:82:06:c2' %}
garage
{% else %}
none
{% endif %}
When I remove the "{% else %} none", it blanks the template sensor, instead of keeping the last living/studio/garage value
{% set map = {'74:ac:b8:82:05:e9': 'living', '74:ac:b8:82:04:40': 'studio', '74:ac:b8:82:06:c2': 'garage'} %}
{{ map.get(state_attr('device_tracker.pixel4a', 'ap_mac'), 'none') }}
probably not though. this will update whenever that attribute updates
you'd need to enable an automation to set an input bool to store previous values
OK, i see a solution with two entities
and then you can replace the 'none' with states('input_bool.ap_store')
sub in that entity id for whatever it actually is
Thanks for the dictionary idea, much cleaner.
yeah, i'm a fan of those
and you only have to pull the value of the attribute once
though you could set it to a var and run your checks that way if you wanted
fun little tricks where the python pokes through the jinja
Yep, I was struggling a lot with jinja until I found the dev tools template editor, helps a lot with wrapping python
I wonder if a self reference will work, can't try it until later, but:
{{ map.get(state_attr('device_tracker.pixel4a', 'ap_mac'), states('sensor.pixel4a_ap')) }}
where sensor.pixe4a_ap is the template sensor itself
Circular reference will not work
Right. Maybe I just drop the template sensor entirely for this. Automation triggering on attribute change, updating an input_text instead.
Probably for the best
Cool, thanks for your help!
Can anyone help me create a template sensor to parse data from a CSV file?
can't seem to find any helpful docs
data looks like this
If you use a File sensor, you will only have access to the last line of the file (that you can parse afterward with a template sensor). I don't think you will be able to store the entire file in an entity. If you want some specific value in the files, you can use a command line sensor, and in the command you can get what you want with tools like cut, tail, head, ...
ah so what you're saying is if there are 18 records in there I'll only be able to look at that last line with a record with a file sensor?
Only the last line of the file is used
btw the state of an entity is limited to 255 characters
for an event that has one of the data entries is an array how do i traverse the array after this trigger.event.data.args?
that's kinda a broad question, what do you want to do with the data, use it as a condition, send it to a notification, something else?
ok here is the data component of the event:
"data": {
"device_ieee": "",
"unique_id": "",
"device_id": "",
"endpoint_id": 1,
"cluster_id": 8,
"command": "move",
"args": [
0,
84
]
}
the first arg specifies the button pressed. so to use it as a trigger or condition i need to filter for that value. how would i do that?
Hello all, I have a template sensor that calculates a number out of two sensors. It works great, but as it has to do with solar power production i want it to behave different then it does atm. Now it reports the same number from when the inverter goes offline, till it goes online again. Is there a option to add a comparison and a reset at midnight inside the template ?
Templates don't 'reset'. They are evaluated whenever any of the entities they reference change.
Hello, I try to display my router upload/download per day in "GB" my router display it in bytes, my template sensor value_template: "{{ (states.sensor.fritz_netmonitor.attributes.bytes_sent|float / 1073741824 | round (2)) }}" It displays me 1,1402727728709600 GB
Can you tell me whats wrong here? I only want to see "1,14 GB"
how would i go about mapping a 0-100% range to a 255 brightness value?
Ah I found it my self ... "value_template: "{{ (states.sensor.fritz_netmonitor.attributes.bytes_sent|float / 1073741824) | round (2) }}"
Is there a way to make it calculate for 24h then?
if this helps,,,u can set a sensor to keep your template....and have an automation running just before your 24h expire and to store that data
What's the secret to getting zwavejs2mqtt updates to a light entity created via light (platform: mqtt)? The topic (both state, command and availability) comes through ok if I subscribe to them in hass, but my light entity just doesn't update..
name: 'Hallway-Lamp2'
state_topic: 'zwave/Hallway/Lamp/37/0/currentValue'
command_topic: 'zwave/Hallway/Lamp/37/0/targetValue/set'
availability_topic: 'zwave/Hallway/Lamp/status'
#availability:
# payload_available: 'true'
# payload_not_available: 'false'
# topic: 'zwave/Hallway/Lamp/status'
payload_on: 'true'
payload_off: 'false'
#optimistic: false
#qos: 0
retain: true```
Do you have a example for that? I wouldn't know where to start tbh π
well...i try to write something meaningfull in text then send to you
cool, thanks! I can send you the two calculation templates in pvt if that is helpfull ?
I think i can follow all the sections so that is a good start ! π
@dreamy sinew thanks ... ill give it a try
@glossy viper That doesn't change anything. I think i have to change my calculation all together.
The problem i have is that one of the two sensors keeps the last known number. So even when the other sensor resets at midnight (which it does, it comes out of our smartmeter) it starts calculating with the old number π
I want to replace the "1" in "background: rgba(0, 165, 0, 1)" with the **size **of a state array.
Uh... why? The alpha channel is a percentage. It goes from 0-1. What's your goal?
it could also check if array site is at least 1 and print 1, but everything above 1 is equal to 1 anyway π
but that seems more complicated, so I tried to do the easiest solution (for now). just can't get to work to replace that little number
@fossil hearth posted a code wall, it is moved here --> https://paste.ubuntu.com/p/KcXjby36Y4/
I'm desperate trying to figure out how to count the size of an array.
Single
{% elif '0006!01' in my_test_json.SW1 or 'Double' in my_test_json.SW1 %}
Double
{% elif '0006!00' in my_test_json.SW1 or 'Long' in my_test_json.SW1 %}
Long
{% endif %}
Solved
So almost what Tinkerer suggested:
{{ state_attr('sensor.seventeentrack_packages_delivered','packages') | length }}
they both seem to work
to access the previous state, I have to combine this with trigger.from_state and trigger.to_state somehow (and thus can't test it with templates anymore, is that correct?).
I think it's something for another day, brain is sad I keep feeding him
Of course you can use templates. That's why I suggested them.
The page I linked in the other channel was about templates in automations... they explicitly show uses of trigger.
{{ states.sensor.seventeentrack_packages_delivered.attributes.packages | length }}
also works. isn't this like the new way?
ok π
Avoid using states.sensor.temperature.state, instead use states('sensor.temperature'). It is strongly advised to use the states(), is_state(), state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isnβt ready yet (e.g., during Home Assistant startup).
it just looks cleaner π
That's... debatable...
{{ ((state_attr('trigger.from_state','packages') | length) - (state_attr('trigger.to_state','packages') | length)) > 0 }}
should it look something like this (if sensor.seventeentrack_packages_delivered is the trigger) ? can't test that anymore in the template tab
you're mixing things
I completely agree π
in this case you do need to use the hard access
it protects against the main concern by having to actually exist to do the trigger
trigger.to_state.attributes.packages
is there a state missing after to_state? (my example from docs shows that)
if I got it right (won't be the case I guess), I can use it even as value template in the trigger itself.
value_template: "{{ trigger.from_state.state.attributes.packages | length) - (trigger.to_state.state.attributes.packages | length) }}" above: 0
it's my last try for today, new day brings new hope I guess
No. trigger.to_state already represents a state object.
You want the attributes of that state object, you acces trigger.to_state.attributes
value_template: "{{ (trigger.from_state.attributes.packages | length) - (trigger.to_state.attributes.packages | length) }}" above: 0
that could work? hard to test, I don't even know how often seventeentrack sensors updates
it doesn't. thanks for your help so far! have to give up for today
damn I could not give up yet. I'm afraid I will never finish it if not now. I guess I just wanted to force it into a value_template but trigger.from_sate and to_state are probably not available in the trigger section. As I was told before to do that in the condition section and fixed my math this works now:
{{ (trigger.to_state.attributes.packages | length) - (trigger.from_state.attributes.packages | length) > 0 }}
is there a way to assign a template sensor to an area?
maybe by adding an attribute via 'entity customizations'?
setting area_id to the value shown in core.area_registry didn't work: https://imgur.com/a/DseGoK1
assigning unique_id lets me assign area
trigger:
- platform: template
value_template: "{{ trigger.event.data.args[0] == 0 }}"
should work I believe.
thanks
to have sensors from entity states i must have template for every state, isn't it ?
States are already easy to access. Do you mean attributes?
It depends what you're trying to do with them and where you want to use them.
in a card to have direct view
Some custom cards might let you access attributes. Otherwise, make a template sensor.
'BMI' != 'bmi'
oh..case sensitive...still not returning {{ state_attr("bodyscale.adrian","BMI") }}
sorry...i'm....guilty
and this is output op
-> states?
yes
so dumb that wasn't paying attention to entity called bodymiscale
now returned the attribute
i can name the same template sensor ? because i will have 2 sets of same attributes, for different entities
Could somebody help me out with a shell_command template please. I'd like to delete some camera image files older then X days. The X is stored in an input_number. Here is the code copied and modified from a working command_line switch: 'find /config/www/camera_images/ -maxdepth 2 -type f -mtime +{{ states("input_number.kamera_fenykepek_lejarati_ido") }} -exec rm {} -f ;'
This one gives an error: Error running command: ..... return code: 1 NoneType: None
if you put {{ states("input_number.kamera_fenykepek_lejarati_ido") }} in
-> template, what output do you get
no, entity names must be unique
then i have to use customize to have the same name for different entities attributes
The entity state returns 1 I've verified that. That is OK.
shell_command:
somecommand: "find /config/www/camera_images/ -maxdepth 2 -type f -mtime +{{ states('input_number.kamera_fenykepek_lejarati_ido') }} -exec rm {} -f ;"
that's how it looks in your config?
{% set value_json=
{"step":"10",
"light":"light.test",
}
%}
{{(state_attr([value_json.light],'brightness')|int(0)/255|int(0)*100)|round(0)-[value_json.step]}}```AttributeError: 'list' object has no attribute 'lower'
Hi all, how do I access device data in a device trigger automation?
I want to fire an event with some data about the device
Yes exactly, but still got the same error.
{% set value_json=
{"step":10,
"light":"light.test",
}
%}
{{(state_attr(value_json.light,'brightness')|int(0)/255|int(0)*100)|round(0)-value_json.step}}```
That can be simplified without all the int casts and using int division.
{{ state_attr(value_json.light,'brightness') | int // 255 * 100 - value_json.step }}
true, just fixed the error(s)
Hello. Is there a way to get "trigger.to_state.state != trigger.from_state.state" for two entities?
I have the following trigger in an automation:
- platform: state
entity_id:
- device_tracker.aaa
- device_tracker.bbb
If the state from one of this device_tracker changes, the automation fires. Can I add a condition, that the automation only fires if the state is different?
different how? if the two device trackers are different, or if the previous state of one tracker is different from the new state?
Yes. The automation should only fire if the previous state of one tracker is different from the new state.
Not sure if this is needed, I believe they should always be different to begin with
condition:
condition: template
value_template: "{{ trigger.from_state.state != trigger.to_state.state }}"
This is not working.
I tried this already.
The automation fires every time, one of this device.tracker is changing his state.
If device_tracker.aaa is home and device_tracker.bbb change his state from home to not_home, the automation should fire. If device_tracker.aaa change his state also to not_home, the automation should not fire.
ah! so only if device aaa is different from device bbb
condition:
condition: template
value_template: "{{ states('device_tracker.aaa') != states('device_tracker.bbb') }}"
If I use {{ states('device_tracke.aaa') and states('device_tracker.bbb') }} in the template editor I have the behavior what I want. For this I am trying to get "trigger.to_state.state != trigger.from_state.state"
I think the easiest way is to create a group from this two device_trackers. But I am searching for a the without to create a group.
the to state will never match the from state otherwise it wouldn't even trigger with your trigger def
your trigger def says "when either of these change"
Magie's solution will work. Group would be easier to manage
how do i get a lights color using a template
Hello.How can the weather sensor convert km / h to m / s and pressure hPa to mm Hg?
Just make a new template sensor to do the math. Let's say a is your speed in km/h, your template for m/s would just be this:
{{ a * 1000 / 3600 }}
And I don't know the conversion for hPa to mm Hg but it's going to be a similar solution with different numbers.
hpa to mm hg is 0.7....wait for my ha to start
@thorny snow {{state_attr("light.some_color_light_you_have_deployed", "rgb_color")}}
hpa *0.75006156130264 = mmHg
that might be a few sig digits past your sensor resolution π
sure...my formula includes a parse int
should |round instead
where?
if you're casting to int you should round instead
otherwise you're just chopping of the decimals
well..no
${parseInt(stateObj.attributes.pressure*0.75006156130264)}
<span class="unit">
mmHg
:)))))))
well...is a customa animated card made by a green guy
but hpa doesn't mean anything for me
and he helped to covert that
why is a delay option not a thing for template sensors yet?
Huh? What would you delay inside a template?
But why? What are you trying to do?
i have a dryer connected to a power monitoring plug
i want to be sure in which state the dryer is so a delay is neccesary
this works great with binary sensors but i want to monitor a standby state
this would work with an automation, but i want to keep everything inside the sensor
i want to be sure in which state the dryer is so a delay is neccesary
Why?
It takes some time so you know it's on standby instead of a short pause in a cycle?
announcement if dryer is finished
if the dryer is in the standby state it is not emptied and i want to be announced again
Well that's just automations...
You need to use an automation to send the notification anyway.
Templates won't do what you want. Templates are moment-in-time things. They have no history.
yea but i want to use this in other scenarios aswell
Any scenario where you want to do something based on a sensor is an automation. Automations are the tool that handle delays or checking how long something's been in a particular state.
Templates can't do what you're asking, nor am I sure there's actually any point.
so questions about template sensors, switches etc belog to #automations-archived ?
No
Questions about automations belong there. You can't do what you're asking with a template sensor alone. Templates don't have history.
they dont need to monitor history
For a template to have an internal delay, it would need a history...
Well if you think other types of template sensors should... either log a feature request on the forum or create a pull request on GitHub.
mhhh i might do that, as is dont see the reason why this should not exist
Hi does someone know how I can have the friendly name change based on the value of a sensor? I am trying to use it in Bitfocus Companion but it doesn't support states (yet) and it currently uses the (friendly) name so I need to change that to the value of a sensor
So basically value_template but for friendly name
Oh... I'm a bit blind, apparently ' friendly_name_template' is a thing
Hello, this will need some skills ! Can someone tell me how to create a filtered list of all entities that are present in 2 groups. I see some codes as below but would appreciate some help joining the dots to make it happen.
This for example gives me a list of the entities in a group_3.
{{- entity_id }}
{% endfor %}```
I then tried this but think I need an iteration within an iteration to make it actually work?
```{% set group_entities = expand('light.group_3.attributes.entity_id') %}
{% set wled_entities = expand('light.group_wled.attributes.entity_id') %}
{% for entity_name in group_entities if entity_name == wled_entities %}
{%- if not loop.first %}, {% endif -%}
{{- entity_name -}}
{% endfor %}```
I hope someone understands and can give me a the best solution here. Thanks!
.... im now seeing intersect() as a better way?
I don't think you can use set.intersection() in the sandbox that templates run in.
Use filters, selectattr will do the job
expand('group.x') | selectattr('entity_id', 'in', expand('group.y') | map(attribute='entity_id') | list)
One day we'll have to schedule a competitive templating event between petro and phnx.
I love that template. Taking it a bit further (and making it a little uglier)... this actually returns the entity ID's:
{{ expand('group.x') | selectattr('entity_id', 'in', expand('group.y') | map(attribute='entity_id')) | list | map(attribute='entity_id') | list }}
The nesting there almost sent me cross-eyed π
Yeah Iβm texting this from my phone so i didnβt feel like adding that extra crap π
I figured from your mispost π
Not trying to take the credit, your solution is brilliant.
Iβm sure thereβs a better way and simpler
This might work
expand('group.x') | select('in', expand('group.y'))
Nah. I don't think it likes comparing the state objects.
Depends on generators
That was my first guess before you came in with selectattr.
Returns an empty list for me when I compare a group against itself:
{{ expand('group.everyone') | select('in', expand('group.everyone')) | list }}
thanks,,, but i get and empty list. ( i replaced group.x with light.group_wled and group.y with light.group_3, and tried vice versa)
Works here π€·ββοΈ
Use the same group in both places for now, you should get everything in that group:
{{ expand('light.group_wled') | selectattr('entity_id', 'in', expand('light.group_wled') | map(attribute='entity_id')) | list | map(attribute='entity_id') | list }}
thanks... for me the template editor only returns : ['light.group_wled']
Aha... light.group isn't a group π
It's a grouping of lights but it's not actually a group.
It just looks like a single light.
oh i see ... nicely spotted
I guess if you want to do that, you'll have to switch for a regular group.
I've caught the Jinja bug now. Remembered macros... who said we don't have intersection? π€£
{{ expand(list1) | selectattr('entity_id', 'in', expand(list2) | map(attribute='entity_id')) | list | map(attribute='entity_id') | list }}
{%- endmacro %}
{{ intersection('group.x', 'group.y') }}```
Is there a way to share macros around to have them accessible throughout HA?
Never mind. Found petro answering the same question on the forums π€£ #
nice , but so i don't waste your times guys, if we can take a step or three back,
.. im basically trying to have a service data template apply to multiple entities, and wonder if the list will even be accepted this way by HA.?
(If I just write the entities with a comma seperation it does work)
data_template:
entity_id: {{ the list we are trying to create comparing 2 groups for matching entities}}```
Sure, it'll work.
cheers....
Just pass in lists instead of expanding groups.
got it it think ... {{ states.light.group_3.attributes.entity_id | list }}
How do I make a sensor that shows whether a device is on or off based on a state of a sensor? (Humidifier plugged into smart plug that can measure power draw)
I have the states('sensor.sonoff01_watts')|int > 20 part
But I am unsure how to set state on/off and for the icon and what not
I think i figured it out, i should be using binary sensor, not sensor
what's the idiom for testing whether a value (state) is defined/truthy in a template?
you can test an entity with {{states('light.unknown') == 'unknown'}}
or rather != as you want to know it is defined π
thanks that works (though I compared with None)
hi is there a template that can get text from a file? i want to send the learned broadlink code as a notification. can i use some sort of template to get the code and display it in the notification?
/config/.storage/broadlink_remote_780f775acae6_codes the code is in this file
the part i want is the b64 part
"version": 1,
"key": "broadlink_remote_780f775acae6_codes",
"data": {
"Learn": {
"Code": "JgBQAAABJ5URFBMSEzYUERQRFBETEhMSETgUNhEUETgRORE5ETgRORQRExITNhQRFBEUERM2EhMUNhE5ExEUNhQ2ETgRFBE5EQAFKQABKUkRAA0FAAAAAAAAAAA="
}
}
}```
the broadlink learn command used to do what i want to achieve, but when it was updated it no longer shows you the leared code. i am just looking for an easy way to display the learned code
i want to use the persistance_notification service to display the learned code
Good day,
I have a thermostat called climate.thermostat and it supports preset_modes (I can set these via a service call).
I'm trying to make a binary_sensor for each of the preset modes (climate.thermostat.preset_mode).
I have the following, but they always show off even though in Developer Tools I can see the correct preset_mode as an attribute.
# Create binary sensors for thermostat programs
binary_sensor:
- platform: template
sensors:
thermostat_program_away:
value_template: "{{ is_state('climate.thermostat.preset_mode', 'away') }}"
thermostat_program_home:
value_template: "{{ is_state('climate.thermostat.preset_mode', 'home')}}"
thermostat_program_comfort:
value_template: "{{ is_state('climate.thermostat.preset_mode', 'comfort') }}"
thermostat_program_sleep:
value_template: "{{ is_state('climate.thermostat.preset_mode', 'sleep') }}"
This is not working though, any help will be appreciated
Edit : I installed Attributes Extractor in HACS, made a sensor for climate.thermostat.preset_mode and then made my binary_sensors based on the new sensor.thermostat_preset_mode entity's state (which is now equals to the preset_mode) and this works like a charm.
If there is another way to do this (without the HACS Integration), I really would like to know.
i have tried using a file sensor but the state is showing state "unknown"
- platform: file
name: test sensor
file_path: /config/.storage/broadlink_remote_780f775acae6_codes
value_template: '{{ value_json.data.Learn.Code }}'```
@wicked gazelle , you file sensor can't work. The file sensor only retrieve the last line of the file. [edit]maybe the last line is good for you, but reading from a storage file is not really pretty π
for your binary sensor, you are doing it wrong. The preset mode is an attribute, not a state
so you should use : is_state_attr('climate.thermostat', 'preset_mode', 'away')
If you really want to get something out of the storage file, I recommend a https://www.home-assistant.io/integrations/sensor.command_line/
the command would be cat $pathToStorage/broadlink_remote_780f775acae6_codes | jq -r '.data.Learn.Code'
and if you don't have jq, cat $pathToStorage/broadlink_remote_780f775acae6_codes | sed -E '/"Code"/ s/^.*: "(.*)".*$/\1/ p'
@deft timber the sensor.command works perfectly. Thank you. the first command worked
@deft timber fyi it was @next haven that was asking about the climate
Oups π
for your binary sensor, you are doing it wrong. The preset mode is an attribute, not a state
so you should use : is_state_attr('climate.thermostat', 'preset_mode', 'away')
https://www.home-assistant.io/docs/configuration/templating/#states
Thank you so much! Really appreciate it, it works now π
Hello, is there a way to define a template macro in a "global" way, to be used by every template sensor?
I'm finding myself repeating alot of code and would be nice to centralize some common pieces in macros
Nop
hey , got some help with comparing entities in groups but wanted to know is it possible to compare just lists (not the array created by using expand).
Simply put, can I create a List C which is composed of all matched items between List A and List B ?
List A and B are generated as follows:
{{ states.light.group_B.attributes.entity_id }}```
[note. because its a LIGHT group, the group is treated in HA as an entity itself so expand wont work, so instead we can get a list of entities as shown above.
@dreamy sinew that doesn't work with state objects
have to use selectattr
& entity_id
just showing an example
i don't have any groups so this is as close as i can get without spending extra effort
I have the "Meteorologisk institutt (Met.no)" integration set to give me weather data for the area near my house. I'm trying to figure out how to pull the templow value out of the first forecast day, but i can't figure out how to dig down that far as it were... how do I get data out of a collection with a template?
in the template tester start with pulling the attribute and work your way down from there
@mighty ledge isn; the output of .entity_id on a light.group a list of entity_ids? or are they state objects themselves?
yes it is, but they'd want to use expand
even though he incorrectly states that expand will not work on a light group. Unless they changed expand
I think there was a change to expand because it no longer breaks out properly on a circular referenced group
I have to look at the source
https://i.imgur.com/nIEGiuA.png I'd like to be able to use the first listed templow I just don't know how to get that far "down" the tree
- platform: template
sensors:
templowhere:
value_template: >
{{ state_attr("weather.home","templow") }}
{{ state_attr('weather.thermostat', 'forecast')[0].templow}}
i do have one of those
oh..didn't see branch
another option
state_attr('weather.thermostat', 'forecast')|map(attribute='templow')|first
Yes you are right, expand does work with light.groups , but for example:
{{ expand('light.group_A') }}
returns all the attributes of the group, of which there is a List Attribute called 'entity_id' but when you try to select it, only the groups own id is returned. hope that makes sense
Yes, its a list of state objects
{{ states.weather.home.attributes["forecast"][0].templow }} worked! Thank you!
What are you trying to do with the resulting list? Just get the entity_ids or check to see if they are on or something?
@mighty ledge thanks for showing some interest and helping.
I have different capability/brand lights with different extra attributes that the light group cannot forward or customise onward to the groups entities. So I have made automations to cope with those. The below is just and example but there are many more choose options dealing with wled_services , mqtt_services , presets , night modes .. etc.
data_template:
entity_id: {{ the list i am trying to create by comparing 2 light.groups for matching entities}}```
if you just want the list then do what @dreamy sinew suggested
you don't need to use expand
unless you want to only turn whats on, off.
or vice versa
cheers... is this on the right track?
{% set B = {{ states.light.group_B.attributes.entity_id }} |list %}
{{ A |select('in', B)|list }}```
nope
Templates do not go inside templates
the entire line is a template
you do not need {{ }} to extract info inside a template
and you can drop the |list on the first 2
{% set B = states.light.group_B.attributes.entity_id %}
{{ A |select('in', B)|list }}```
yep
{{ }} print/output statements
{% %} logic statements
thanks @dreamy sinew and @mighty ledge ... its so much easier with help π
I'm having some trouble with a template fan.
https://paste.ubuntu.com/p/XdfDbMc9dp/
It'll turn on and off fine, and it'll display the speed (mostly just '3' if the fan is at full blast) but when I select other speeds, it isn't adjusting the fan level at all.
The fan controller is a Z-Wave Leviton VRF01. I can adjust the speed just fine through light.turn_on in Developer Tools>Services
The following attributes seems to work ok:
{{ states.weather.home.attributes["forecast"][0].templow }} {{ states.weather.home.attributes["forecast"][0].wind_speed }} {{ states.weather.home.attributes["forecast"][0].wind_bearing }} {{ states.weather.home.attributes["forecast"][0].temperature }} {{ states.weather.home.attributes["forecast"][0].condition }} {{ states.weather.home.attributes["forecast"][0].precipitation_probability }} {{ states.weather.home.attributes["forecast"][0].datetime }}
But for some reason temperature and humidity does not produce a result.
The number [0] is the number of days into the future the forecast is done - up to 4 days maximum.
put your entity_id inside the data_template. Also, I'd remove the quotes around all your speeds. Then use mapper[speed | int] in the set_speed service
what's the [0] object look like?
Changes made, although still doesn't seem to modify the level of light.living_room_fan_level
https://paste.ubuntu.com/p/yHD3xn4fbC/
aer you getting errors?
[0] is today [1] is toorrow [2] is day after tomorrow... and so on
-10.0
7.9
204.0
-2.2
cloudy
29.4
2021-02-13T11:00:00+00:00
that's missing the keys
Fromtop down the list
Actually, now that I'm looking, it seems that it's not that it's not changing, but instead it's always changing the speed value to '3' whenever I make a change. Let me change it to low/med/high and see if it's still doing that.
That will happen when because your speed template is based on your light's setting
if the light isn't changing, the speed won't update
You need to look in the logs and see if there is errors
Logger: homeassistant.components.template.fan
Source: components/template/fan.py:377
Integration: template (documentation, issues)
First occurred: 2:10:19 PM (3 occurrences)
Last logged: 2:13:02 PM
Received invalid speed: . Expected: ['1', '2', '3']
Alright, well there you go, it needs to be strings. So revert back to what you had but with the entity_id inside the data template
also, it appears as if your turn_on might need to select the speed
I have an almost identical fan template working for a different kind of Z-Wave fan controller
right but this is not the same because it's not working
clearly π
Received invalid speed: . Expected: ['1', '2', '3']
that tells us that it receive an empty string when trying to set the speed
Received invalid speed: . would normally read Received invalid speed: "something".
I actually get the same error on the other fan's template, but only upon starting HA
which, I didn't look to see if this was the case here
Then that's not the error that we should be loooking at
I've restarted it so much troubleshooting this
But it's the only error for the template in the logs
OK, confirmed, it does trigger that error when changing the level. I switched everything back to 'low', 'medium', 'high'
and the error is
Received invalid speed: . Expected: ['low', 'medium', 'high']
Which fits that it is receiving an empty string for the fan speed
The entity details show speeds of low, medium, and high
When setting any of them, it changes the fan to brightness: 255
actually, now that it's low medium and high, it seems to be defaulting to 'medium', which would be the last item alphabetically...?
How can I clamp the upper value to avoid erraneous numbers on this line?
value_template: "{{ (states('sensor.dehumidifier_volts') | float / 230) | round(3) }}"
voltage should never be over 250, but i think the smart plug freaks out occasionally
which im reading it from
Sorry, was driving. What's y our current brightness when you turn on the light?
{% set v = states('sensor.dehumidifier_volts') | float %}
{% set v = v if v <= 250 else 250 %}
{{ (v / 230) | round(3) }}
What's this? π
{% set v = v if v <= 250 else 250 %}
Why not min? π
{% [v, 250] | min %}
same shit, different way of writing it
It's not like you to do things the long way π
iterating over a list is slower than an if statement π
Maybe
Reminds me of every time I try to optimise code at work... only for another dev to remind me that we wouldn't be using JavaScript if we wanted it to be fast π€£
always try to keep collection iteration to a minimum tho, thats 101
min definitely has to iterate across the whole list
Indeed. I reduced something from O(n2) to O(n) once at work. The other dev was wondering why a script was taking 15min+ to run. I got it to 10 seconds.
Meanwhile, my manager had no idea how much time I'd saved everyone π¦
thanks for your help so far isolating the issue, unfortunately going to have to come back around to it later. I was trying different brightnesses on the light entity, and it would stay at that level until I tried to change it from the fan template entity, at which point it would go to medium. I was listening to the event bus, and was seeing that if changing the fan speed turned on the fan, I'd get a change event for light., fan., and zwave. entities. (It would always say the old state is null and the new state is 'medium', no matter what I had set it to. It would also set the fan to the medium level.) If I tried changing the speed while the fan was already on, I only got a change event for the zwave. entity, not the fan or light entities.
lol, that's why you don't tell anyone and keep it for yourself. 15 minutes of twiddling your fingers
Hi again, trying to finish off something you guys helped with earlier but stuck. Can you take a look my entity_id entry in my data template ?
this works:
speed: "{{[(state_attr('light.light_'+trigger.topic.split('/')[4], 'speed') + 28), 255] | min }}"
entity_id: "{{'light.light_'+trigger.topic.split('/')[1]}}"```
and this works:
``` entity_id:
"{% set A = states.light.group_1.attributes.entity_id %}
{% set B = states.light.group_2.attributes.entity_id %}
{{ A |select('in', B)|list }}"```
but trying to combine both doesn't.
``` entity_id:
"{% set A = states.light.group_1.attributes.entity_id %}
{% set B = 'states.light.group'+trigger.topic.split('/')[1]+'.attributes.entity_id' %}
{{ A |select('in', B)|list }}"```
I've tried various combinations for set B but think it may be an issue of nested variable , rather than syntax.
Either way any ideas would be nice. Cheers
What does trigger.topic.split('/') give you?
Also, use ~ to join things so you don't have to worry about casting.
entity_id: >
{% set A = state_attr('light.group_1', 'entity_id') | default([]) %}
{% set B = expand('light.group'+trigger.topic.split('/')[1]) | map(attribute='entity_id') | list %}
{{ A |select('in', B)|list }}
too fast π @ivory delta... was just about to edit that bit in .. Its gives a number from an mqtt topic (i think its a string of a number an not an actual integer)
What error do you get?
thanks .. let me try it ... but expand didnt work well on light.groups last time .
it's not possible to concatenate a states object and a string, so you have to pass the entity_id to a function
it could also be done like this
And I think I'd still do it like this (even if I don't know exactly what the difference is):
expand('light.group'~trigger.topic.split('/')[1])
entity_id: >
{% set A = state_attr('light.group_1', 'entity_id') | default([]) %}
{% set B = state_attr('light.group' + trigger.topic.split('/')[1], 'entity_id') | default([]) %}
{{ A |select('in', B)|list }}
the ~ vs the + just makes sure they are both strings, it is safer
@mighty ledge you always get it right! works great !!
i notice this issue before and now i know why too .. thanks
I can't seem to get templates to work with a rest_command... Docs suggest it should work, but the data is not being passed into the parameters.
Edit, nevermind, I think I got it now, yay!
hello I have an error which says that Error during template condition: UndefinedError: 'tts' is undefined
here is the script https://paste.ubuntu.com/p/4S33t4QyXt/
so I have a choose statement and then two separate conditions if my variable platform is tts.google_translate_say do that branch of the automation, else if tts.cloud_say do other branch..
I checked in my templates tab {% set platform = 'tts.cloud_say' %} {{ platform == 'tts.cloud_say'}} and it returns true
do you see something that I missed maybe?
You missed telling us how you're calling the script.
entity_id: script.play_notification
data:
variables:
speaker: "media_player.bathroom_ceiling_speaker"
source: "Primary Chromecast"
volume: "0.4"
custom_message: "Dobro doΕ‘li u kupatilo."
platform: "tts.cloud_say"```
this is the call
but I think its working now..
im still testing..
Thank you
Got a question I'm hoping someone knows the answer to. I can get today's date using "now()" but how can I create a date using the known month, day, and year integers? Is there something like "date(2,13,2021)"? Ultimately, I'd like to create a custom date value and get the weekday() value of it to know the day of the week of a custom date.
To get a date object from a string, you'll need to use strptime (https://www.tutorialspoint.com/python/time_strptime.htm). Then just use .weekday() to get the day of the week (it's a zero-indexed value).
Thank you!
This returns the correct result but fails on with .weekday() -- strptime('{2}-{0}-{1}'.format(dateinfo.month,dateinfo.day,dateinfo.year),"%y-%m-%d") -- result: UndefinedError: 'str object' has no attribute 'weekday'
Try this instead (substituting in your own values):
{{ now().replace(day=21).replace(month=2).replace(year=2020).weekday() }}
That doesn't zero out hours or below.
This works too, so it must be something to do with your .format:
{{ strptime('20-02-21', '%y-%m-%d').weekday() }}
Any way around the .format?
You can use it, you're just making a mistake somewhere. Check that the values make sense in the positions you're inserting them.
This works too:
{{ strptime('{0}-{1}-{2}'.format(20,2,21), '%y-%m-%d').weekday() }}
It'll be human error.
story of my life lol
Thanks ill work on it
This ended up working for me: {{now().replace(day=dateinfo.day).replace(month=dateinfo.month).replace(year=dateinfo.year).weekday() }}
It doesnt like passing a variable into strptime
This fails:
{% set dateinfo={
"day": now().day ,
"month": now().month,
"year": now().year,
"dow": now().weekday(),
}
%}
{{ strptime('{0}-{1}-{2}'.format(dateinfo.year,2,21), '%y-%m-%d').weekday() }}
Variables work fine:
{{ strptime('{0}-{1}-{2}'.format(year,2,21), '%y-%m-%d').weekday() }}```
Check what now().year gives you π
What does it give you? You're telling strptime to expect a 2 digit year...
Yea brain fartssss
Always build things up in steps, or you'll miss details like that.
Its been a hot second since I used python, ive been missing a lot of details lately lol
Yeah, I'm not familiar with Python either. What little I know, I've picked up from watching this channel.
Appreciate the help!
How can I add another if statement which ignores power_w if the value is over 20000, can i nest them?
value_template: > {% if value_json.id == 51600 %} {{ value_json.power_W }} {% else %} {{ states('sensor.owl_watts') }} {% endif %}
also could i just replace that if statement with value_template: "{{ value_json.power_W | is_defined }}"
Is this valid?
value_template: > {% if value_json.id == 51600 %} {% if value_json.power_W <= 12500 %} {{ value_json.power_W }} {% else %} {{ states('sensor.owl_watts') }} {% endif %}
I think you need another {% endif%} to close out the 2nd if statement for that one
I did add that and it broke
but you could do this value_template: > {% if value_json.id == 51600 and value_json.power_W <= 12500 %} {{ value_json.power_W }} {% else %} {{ states('sensor.owl_watts') }} {% endif %}
I did think about that, I'll do that if this way causes any oddities
ah you're quite right the endif was needed, last time I tried and it failed I must not have saved my config
how to get last_changed attribute from a switch
Im trying this: {{ state_attr('switch.bathroom_light', 'last_changed') }}
I'm not the expert here, but since it's not listed under "attributes" under developer tools, I think you can only access it with the hardcoded: {{ states.switch.bathroom_light.last_changed }} . if you need it only for front end, you can access it directly there with secondary info.
Hello again. Im working on an integration via MQTT Auto Discovery, which is working so far.
The only issue i have left is converting a string value to float. I know this can be done by | float. But my key : value pair is not a json. so i tried {{ value | float }}, but this doesnt seem to work.
My state topic is basically the key entry. Trying to convert the value to float.
The config entry includes ["value_template"] = "{{ value | float }}. And the value is shown in the gui, but it seems to be a string instead of the float.
tnx @austere relic
I managed to retrieve last_changed attribute
but now I have an error
here is the script
Invalid config for [automation]: invalid template (TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.) for dictionary value @
dunno if it's the space missing after {%
Whitespace doesn't matter inside the templates.
Probably doesn't help that the if block isn't actually doing anything.
yup, just old habit.. to have else part
no you also dont have an action after the if π
oh I found it entity_id is misspelled π
how do you mean? I have choose statement, and after condition I have sequence..
so if the condition met, it should jump into sequence
{%else%}
#DoNothing
{%endif%}```
The if does nothing...
It returns nothing.
You should also simplify it all...
{{ 3 > time_diff > 0 }}```
hm, honestly I didnt test it, I will do now, but how? I have just the scope if two switches turns on in 3 seconds timeframe?
If you're using a condition as a template, the template needs to return True for you to proceed.
Currently, you return nothing when it passes (so it will stop your sequence) and you return something when it fails (so it will continue).
I've edited my last post... that's what you need to return.
The important thing is that {{ 3 > time_diff > 0 }} returns a boolean.
I get it..my if statement does not returns boolean always
It might be considered a boolean but it'll be backwards.
An empty string is 'False', a non-empty string is 'True'.
it works π thanks mono
Anyone please? Any ideas?
States are always strings. Templates always return strings. If an integration needs a different data type, it will attempt to convert it.
Hi i need some help,
Im trying to create a template for my temp sensor and im writing this to pull its state
Im getting a
invalid key: "OrderedDict([('states.sensor.151_temperature', None)])" in "/config/configuration.yaml", line 46, column 0
error
But if i plug the same thing in dev tools>template editor it works and i get the temperature
It sounds like the problem is the way you're configuring your integration, not the template itself.
Over to #integrations-archived π
i just came from thereπ
Share the whole thing...
- platform: template
sensors:
sensor.151_temperature:
friendly_name: "TempSensor"
unique_id: "z2f3035e0e8d4bd098c03ffb1b1e0926"
unit_of_measurement: "Β°C"
value_template: '{{states("sensor.151_temperature")}}'
This is a temperature sensor that works with tellstick add-on. It does not have unique_id so im trying to make one with a template
Because i need to add my entities into areas and i cant do that now...
sensor.151_temperature:```
π€
I don't think you can pull data in a template from the same device
First, you don't put sensor. in front, it does that for you.
Second, never start an entity name with a number.
Third... what Magie said. Circular references are stupid.
And... your problem is the integration, not the template.
if the original is calles 151_temperature, call this something else
I didnt call it 151_temperature, when i integrated it first it was called like that
You just showed us where you typed that name...
Line 3.
Back to #integrations-archived.
a template sensor is it's own entity, you';re not changing the original one
I can change name and do a bunch of stuff to all of my entities that are pulled from my phone, because they have a unique_id right, but this temp sensor that works with a tellstick doesnt have one
This entity ("sensor.151_temperature") does not have a unique ID, therefore its settings cannot be managed from the UI. See the documentation for more detail.
in my yaml i only have
sensor:
- platform: tesllstick
thats it. How can i add my temp sensor to a area for example the same way i can with my phone entities?
Everything you're posting is #integrations-archived. Continue this in the right channel, thank you.
Quick feedback to my issue with the wrong data format. It was actually not related to the value_template, but to the unit_of_measurement key. Setting a unit_of_measurement made the data be displayed as floats.
i'm trying to merge a smart light switch and a smart bulb. anyone ever have success with this? https://paste.ubuntu.com/p/wmtDbSWt8T/
You have errors in level_template and value_template. "{{states('light.zb_office_ceiling1.brightness') | int }}" is not correct. If you want to access an attribute, use "{{state_attr('light.zb_office_ceiling1', 'brightness') }}" (it is already a number so no need to cast)
when you call set_level, you set a parameter value, instead of brightness
BTW, use data: and not data_template:, which is deprecated
@hollow cloud π
how to configure a template sensor to survive restarts without effecting the last changed time stamp π ?
is there any way to apply an icon template to a helper variable created via UI? I want the helper icon to change based on state (on/off)
Not possible. All sensors/devices are updated. Think there was a github issue on this
Hello there. I'm not sure if this question needs to be under templates or automations...
I'm trying to set up an automation based off an event from my Camera system. The event triggers on motion and includes detail about which camera, which object detected as well as a direct link to what I suspect is a gif of the motion recorded....
I've used a data_template to pick up the specific camera '{{ trigger.event.data.desc }}' and further down in the automation I'm trying to do a push notification to my iPhone with the category "camera" and then I try to do the same thing to define the camera: entity_id: 'camera.{{ trigger.event.data.desc }}_camera'
Whenever I include the stuff about the camera, I get an error which my talents are not adequate in troubleshooting: voluptuous.error.MultipleInvalid: extra keys not allowed @ data['attachment']
Anyone able to help me understand this? π
maybe if you post the whole automation, and if longer then 15 lines, please use https://paste.ubuntu.com/
I'd like to split out my Utility Meters in a separate folder but how can I know if I should use !include_dir_merge_named or !include_dir_merge_list ?
Depends on the integration. It's also not a topic for #templates-archived π
hehe... I always post in the wrong channel!!
I'm trying to pull some data from API endpoints which require bearer authorization, and the issue i have is that my token keeps changing. I can't store it and update it in secrets.yaml because it takes a restart to affect the change, is this something i could somehow achieve with a template and some sort of variable somewhere?
I havn't yet worked out -how- i'm going to keep getting the new token, but it's kinda academic if I can't -use- the new token without restarting HA
@thin vine I've tried and tried, here is my code: https://paste.ubuntu.com/p/sSF5F73gHf/ - It fails with: NEW Notify Motion: Error executing script. Invalid data for call_service at pos 2: extra keys not allowed @ data['attachment']
NEW Notify Motion: Error executing script. Invalid data for call_service at pos 2: extra keys not allowed @ data['push']
NEW Notify Motion: Error executing script. Invalid data for call_service at pos 2: extra keys not allowed @ data['data_template']
I'm not sure what I'm doing wrong :/
First part of the script works fine, it starts going to shit when I add on the 2nd part with the attachment, push stuff
I'm no expert and don't use iOS, but what's the "push" bit for? If you're attaching an image isn't it just done with data: > Image ?
Hmmm, it may be @fading bear - I picked it up in a YouTube tutorial at some point...I have something set up in a different way where it works like this...I don't think it's data_template tho, but only data:
edit: it's "attachment" on iOS, not image
it's worth noting that if the goal is to send a snapshot of the camera with the notification, the way i do it is to have 2 actions - the first saves a snapshot and the second creates the notification with the attachment
In the same automation I have an action that snapshots the camera that triggered an event, this works fine. I then have another action that is to notify my mobile phone...it works fine just sending me a message with some content from the event, but if I try to include the image then it messes up
trying to make it so it includes a snapshot and then a long press = live stream...but first things first, snapshot :p
https://paste.ubuntu.com/p/mnyXfCT2J5/ <-- this is my example with an android notification
the order of things is a bit messed up because it's created by the editor
ok...I do need data_template to use {{ data tho right?
I have this: https://paste.ubuntu.com/p/J2pf35XKRt/ setup, and it works just fine, giving me a live stream of the cam
forgive me, but if that works, what doesn't? π
no problem...it's another thing I'm trying to achieve. I'm trying to get the info from the event and then via that "select" which camera to show me...
The last one I posted is from another way of doing it where I have something called DOODS do the analysis of the image to detect humans and the new thing I'm trying to do is to use what's called a Camect to do that detection
ah i see
The Camect device is better at detecting objects but I've had a hard time figuring out to integrate it into HA
So I just went another way at some point...but now I'm a bit stubborn :p
probably going a bit beyond me in that case. You might be able to do something weird with actionable notifications, where each action pings you back with a different stream
?
seems clunky in my head but i'm a bad coder π
hehe, likewise...I cut, paste and modify quite a bit...can't quite understand this one tho...
and the error code I'm not able to troubleshoot on my own
Seems to be that it has a problem with you using "push" inside data, so maybe try it as its own group, but we're well into "just try moving the yaml about" now
I think the issue is in some way this data_template inside another data_template, but I don't know
Yeah...hope someone has the magic touch to help me on my way
thanks for giving it a try tho π
here with my own problems, just trying to give back π
Sounds like a perfect use case for writing an integration that handles refreshing the key.
There are already several integrations that do exactly that. If you want to go down that path, ask in #devs_core-archived
Your sunny optimism at my skill is as uplifting as a dog in a costume, but i fear it may be misplaced π
what? that does't make sense
all sections of data can be templates
not anymore, data_template is deprecated
If I had a guess, replacing data_template with data should work, as long as 'camera.{{ trigger.event.data.cam_name }}_camect_jpg' is a valid camera entity
I would first try to make it work without the template, then insert the template part
@thin vine Thanks! I'll give that a shot at once
@thin vine It's better...another obstacle but something I think I can manage now. Thanks a bunch! π
how to configure a template sensor to survive restarts without effecting the last changed time stamp π ?
is the tempalte result a number?
yes
how do I do this, template derives it's value from another entity
I just want a place to store a set point
then you maybe satisfied when you put a statistics sensor on top of the template result
I want to use node red to call a service that sets a value that is read only from GUI
there is no service to set values of a template sensor
as long as you don't touch it in gui/automations/scripts it doesn't matter if it's r/o or r/w
sure, but that's janky
i wish HA had a generic variable service
or ability to make inputs read only
maybe there is a custom lovelace card to do what I want...
janky? ok π€·
i'm surprised that such a basic feature is missing
there is a switch services that does exactly this for booleans, why don't we have an analog_service
i'll just use the input_number for now and hope my wife doesn't touch it...
now we get to the point, yes ACL is missing in HA
I come from factory and industrial automation, so making internal and user variables is common place
do you have industrial grade switches and sensors at home?
i don't see how that relates to being able to create program variables in node red
and displaying them on the UI
#node-red-archived for node red, you talked about industrial standards
thanks. i'll give it a try.
@clever sedge the input_x "helpers" are in fact intended to use like you suggest. if you have a number to stash, input_number is a place you can stash it.
i've also been abusing the MQTT number: https://www.home-assistant.io/integrations/number.mqtt/ as a helper object, but one which i am able to create from within a blueprint or automation
@deft timber thanks! It's looking like it works!! I might run into some edge cases but this is looking great!
blueprints cannot (yet) create helper objects, but they can publish MQTT messages, so if you're sure the users of your blueprint have MQTT available, you can do things like publish a discovery message to create something like an MQTT sensor, push changes to it via MQTT messages, and read those settings back via templates.
I'm using input_number, its just annoying that some internally calculated value can be overwritten by user from UI
there is no way to disable that
just don't show that entity in your ui
or feed the number to a sensor with the api
Don't use the auto generated UI. Take control and it won't show up in your UI. But you'll have to manage everything you want to show in your UI.
I want to display it. I made my own HVAC controller for a zwave thermostat. the node red flows evaluate a lot of conditions to decide what is the heating/cooling target
i need to show these targets on the UI because the climate UI isn't very smart/has problems
make a template sensor to display
yes, that is the only other solution, but it's a bit ridiculous to make a template sensor just to make a "read only" variable in the UI
it is a solution, though
sensors are the only things that are read only in HA. Input_x aren't read only because something is writing to them
template sensors are really handy, they provide a kinda-read-only way to stash structured data
as long as you can get it from somewhere that already has it π
and again, if you have MQTT, you can write to it via MQTT without giving the user any way to make those same sorts of cahnges
I'm not using MQTT, HA is complicated enough as it is lol
is there a way to refresh config and get my new template sensors without reboot?
you never need to reboot, just restart the HA service
template.reload service
developer tools -> services tab -> template.reload without any args
does this look correct
- platform: template sensors: climate_sys_heating_target: value_template: '{{ state_attr("input_number.climate_sys_heating_target") }}' #unit_of_measurement: 'F' friendly_name: Heat Target device_class: temperature
states() not state_attr()
Also, if you want it to show up in the correct history graph, include the degree symbol
nope, because it doesn't know if it's C or F
Sets the class of the device, changing the device state and icon that is displayed on the UI (see below). It does not set the unit_of_measurement
device_class only sets the icon btw
it also does some fancy shit for timestamps
but we don't need to talk about that
you need the symbol
Β°F
no idea why i have committed this to memory, but it's alt-248
too much time writing templates π
@iron peak posted a code wall, it is moved here --> https://paste.ubuntu.com/p/QBPsJsNRX5/
Hi everyone. I have some smart blinds, that are integrated with HA via rest_commands.
I'm using the covers template, but I'd like to avoid repeating the same code 14 times.
Is it possible to use Jinja2 template somehow in the configuration.yaml, something like this:
?
Try it and see
this is just pseudo code, to explain what I'm trying to do
the jinja2 template throws an error, if I try it like this
I was trying to use "customize" and "customize_glob" but that does not help much, as the open_cover and close_cover sections have to be repeated
unless there is a way to reference the attributes of the entity without defining the entity name
something like .friendly_name or self.friendly_name would help, but it looks like there is no such thing
you'll have to copy-paste
Write the code in the template editor and copy/paste the result into your yaml file.
Add the code to your yaml and comment it out so you don't need to reinvent the wheel everytime you need to add one.
Thanks @mighty ledge , this is what I've been doing. (I took it a step further, and wrote a simple python script to generate a yaml file, by rendering the Jinja2 template, and I only need to run that if the template part changes. I was just thinking that there has to be a standard solution for this π
Nope, jinja is only applied on fields
is it possible to reference a parent key in the yaml config somehow?
something like this:
friendly_name: blind_name
open_cover:
service: rest_command.blind_setpos
data:
position: 0
name: ../../friendly_name
?
that would allow me to define it once and use the customize module to simplify my code
but I have not seen any examples, where there is a reference to a parent key, so I suspect it's not possible
π
Afternoon all, i have a tracker on my motorcycle that is connected through traccar to Home Assistant, one of the data fields it reports is power (ie. the voltage of the bike battery, how do i ctreate a template sensor that pull that into it's own sensor? the device is called device_tracker.thundercat and the attribute is power.
value_template: "{{ state_attr('device_tracker.thundercat', 'power') }}"
@iron peak to the best of my knowledge your suspicions are correct
Thank tom, I assume that goes into sensors, is that correct?
Got it! Cheers tom!
I have CLI sensor, "esi-rika-online" which I have working pulling json attributes into its attributes successfully.
name: esi_rika_online
json_attributes:
- last_login
- last_logout
- logins
- online
value_template: "{{ value_json.esi_rika_online }}"
What do i need to change to properly set one of these attributes as the "state" of the sensor? Currently it just says "unknown"
I copypastad the bulk of this, so I figure i need to change the value_template bit but not sure what i'm doing at this point
Hi guys. Can I disable unavailable state for one sensor?
no
@fading bear need to set your value template correctly. to do that, you need to know what data you're actually working with
the attribute i'd like to become the main state of the sensor is "online"
which is either true or false
Hi all. I want to set attribute templates based on the new state of a sensor. Is that possible?
@glad geode need more details
Neo: then adjust your value template to pull that value
if you want the state to be something other than true/false you'll need to do some more template magic to convert it
So within an attribute_template of a template binary sensor I'm trying to reference the current state of the sensor with states('binary_sensor.this') but it gets the previous state rather than the current
don't do circular references
I wouldn't call it circular as such. The value_template doesn't reference the attributes
so.. value_template: "{{ value_json.esi_rika_online['online'] }}" ?
i suck at templating, it never seems to sink in
that would work
https://github.com/home-assistant/core/issues/39932 this is pretty much what I'm talking about
But with attribute_templates rather than icon_template
I set the template like that, but the main state of the sensor still seems to be "Unknown"
any ideas?
did you restart/reload your templates after making the change?
anything in the logs?
nothing i can see
.share the full then and a example of the payload
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
try:
{{ 'Online' if value_json.online else 'Offline' }}
restarting now to test
that seems to have done it, won't know until the account goes offline to see if it changes, but it's reading "Online" now int he state. - cheers @dreamy sinew
I suppose this should be a binary sensor, but can they contain attributes too?
they should, if there is a binary version of this platform
alright, future me problem
cheers
using home automation to spot game disconnects.. what a world
lol
Hello everyone! Is there any way to get the value of a mqtt topic into dev tools/template editor without making a sensor out of it?
I want to see exactly how payload_json works and the output of a certain attribute
if its not in a sensor its not in HA's state machine
or rather, if its not in an entity
I am trying to do just that,
So I am not sure how to find out the value
I made many sensors and binary sensors manually configured
probably through some sort of mqtt explorer tool
but I am having issues with one in particular.
If value_json is something like ("value"=heat,) I can make a sensor with "{{ value_json.value }}"
BUT, if value_json is ("value"="heat",) it will not work. I have tried with something like ```
value_template: >-
{{ value_json.value | replace('"','') }}
And of ocourese it will not wirk with a simple "{{ value_json.value }}"
no, just the part I am interested in π
Let me see
{
"anti_scaling": "ON",
"away_mode": "OFF",
"battery_low": false,
"child_lock": "LOCKED",
"current_heating_setpoint": "30.0",
"frost_detection": "ON",
"linkquality": 18,
"local_temperature": "24.7",
"local_temperature_calibration": 0,
"preset_mode": "none",
"system_mode": "heat",
"window_detection": "OFF"
}```
system_mode is what I am interested in
This is what I see in mqtt explorer and also in zigbee2mqtt state page of the device
value_json.system_mode would be what you want then
It does not work,
I have the exact same thing done for my other clkimate component and it is working
make sure you're pulling the correct topic then
if it works on another it would work here
is this ok https://pastebin.ubuntu.com/p/BYtWcvvFwP/ ?
i want to see only specific mails
Looks like there is a problem with my mqtt sensors. The ones from windows do work, but the ones from mqtt climate entities do not work. Neither does. One just stays on all the time.
managed to create sensors but main sensor is unknown state and of course templates are unavailable : https://pastebin.ubuntu.com/p/MtF9RFB3Ss/
would this round to two decimal places? value_template : "{{ state_attr('device_tracker.thundercat', 'power')|round(2) }}"
EDIT. Just found the template in config tools to test, and it works. Thanks.
Hi all. How can I merge two sensor values that are json strings?
Right, a slightly different tack. Is there a filter to merge 2 dicts?
There's a link in the pins to the available filters.
https://pastebin.ubuntu.com/p/FN7J5qxstS/ checked if credentials are available. but seems to not want search operator
No, there is no such filter
Ok, I'm drawing a blank on ways to do what I want to do. I have a json defined set of light profiles for rooms which I'm reading in from a command_line sensor that sets json_attributes. I want to merge the room profile over the default profile. Obviously in any standard language this would be trivial, but in jinja2 I'm struggling:
{% set profile = 'night' %}
{% set room = 'lounge' %}
{% set defaults = state_attr('sensor.settings', 'profiles').default[profile] %}
{% set data = state_attr('sensor.settings', 'profiles')[rm][profile] %}
What next?
I suppose I could use an sql sensor and COALESCE...
Hi there ... I need help with a scrape sensor. This sites output is a simple text, no json:
https://tgftp.nws.noaa.gov/data/observations/metar/stations/EDDM.TXT
Output:
2021/02/17 12:20
EDDM 171220Z 26010KT 9999 FEW025 09/03 Q1021 NOSIG
I tried this:
- platform: scrape
resource: https://tgftp.nws.noaa.gov/data/observations/metar/stations/EDDM.TXT
name: MUCWX
select: ""
value_template: '{{ value.split(" ")[1] }}'
but it shows an error.
SelectorSyntaxError(
soupsieve.util.SelectorSyntaxError: Expected a selector at position 0
But this site has no selector like .div or <a> or something, just plain text
it seems to be embedded in a <pre> tag:
<pre style="word-wrap: break-word; white-space: pre-wrap;">2021/02/17 12:50
EDDM 171250Z 27011KT 240V300 9999 FEW030 10/03 Q1021 NOSIG
</pre>
So I would say select: "pre"
Let me try ...
π₯ command_line sensor with jq '({} + .default.{{states('sensor.current_light_profile_name')}}) * ({} + .room.default) * ({} + .room.{{states('sensor.current_light_profile_name')}})' /config/light_profiles.json
Hm ... still not correct:
I tried this:
- platform: scrape
resource: https://tgftp.nws.noaa.gov/data/observations/metar/stations/EDDM.TXT
name: MUCWX
select: "pre"
Shows 'unkown' ... so how do I get just this line:
EDDM 171250Z 27011KT 240V300 9999 FEW030 10/03 Q1021 NOSIG
?
"body > pre"
The link seems down to me.
weird, link works for me.
unkown is also weird, I would think it to be unknown... I wonder where that typo is π
anyway, at the moment however, it doesn't seem to be template issue, so I would move the discussion to #integrations-archived and see if someone has experience with the scraper
Okay, so should I post the problem there?
That is what I ended up with:
- platform: rest name: MUCWX scan_interval: 300 resource: https://tgftp.nws.noaa.gov/data/observations/metar/stations/EDDM.TXT value_template: '{{ value.split("\n")[1] }}'
The desired output is: EDDM 171220Z 26010KT 9999 FEW025 09/03 Q1021 NOSIG
Thanks for your help. π
My next issue, I'm trying to create a command line sensor which is essentially the sum total of lots of json objects returned by an API call, and frankly im not even sure where to start... https://paste.ubuntu.com/p/rfZsQy5cCR/ is an example of the data to be returned, but the number of objects and length of the response is variable
I want my eventual sensor to simply be the sum total of all of the "quantity" values
Did you check the pins?
discord tells me this channel has no pins π¦
I mean, let's not be one of those people that tells other people what they can see
If you're running in docker then the container already has jq installed
If not....install jq
Or... just use the existing Jinja filters π€·ββοΈ
Well as with my issue earlier jinja doesn't always have the answer you're looking for
When they do, use it.
if it has this answer though, i'll take it over installing something else
i'll take a look, might need help making it work though - is there a way of giving the template editor some sample output to work with for testing stuff like this?
{% set my_test_json = {
"temperature": 25,
"unit": "Β°C"
} %}
The template editor has an example.
this bit?
Yes
excellent
finally got this working, cheers @ivory delta
where u are master of templates? :)))
https://pastebin.ubuntu.com/p/FN7J5qxstS/ some magician needed π
Can someone help? I've got a window sensor that's having some problems. It keeps reporting open/closed suddenly. I think it may be weather related. I'm wanting to have it only turn on if it has been on for at least two seconds. I've tried adding this:
master_window:
friendly_name: 'Master Windows'
value_template: >-
{{ 'open' if is_state('binary_sensor.master_windows', 'on') else 'closed' }}
delay_on:
seconds: 2
icon_template: >-
{% if is_state('binary_sensor.master_windows', 'on') %}
mdi:window-open
{% else %}
mdi:window-closed
{% endif %}
I think I may be missing the whole boat on this though, right?
I want to check that binary_sensor.master_windows is on for two seconds
Okay so this works in the gui at dev->template:
{{ 'open' if is_state('binary_sensor.master_windows', 'on') and (states.binary_sensor.master_windows.last_changed < (now() - timedelta(seconds=2))) else 'closed' }}
but I'm getting an error when I add it to my config above like this:
ha.. Talking to myself. Solved. Would not have happened if I had not come here and posted. Thanks for listening. π
Hi everyone, came here a few days ago for this code and it worked fine. Unfortunately, it stopped working and home assistant now returns TypeError: '<' not supported between instances of 'NoneType' and 'datetime.datetime' Any idea on how to fix this? π
Seems like your {% set sensor part isn't working. It sets it to None.
If it works in /developer-tools/template it may be a " vs ' issue.
It does not work in /developer-tools/template (anymore). But it used to work there ten days ago.
hello , i have one zigbee button, which have not entities and when i do automations I use event and describe event data. Is it possible to do some template to have somehow friendly named entity for that ?
hello is there a shortcut to get the current sensor's state in the value_template?
What 'current sensor'? π€
current sensor = the current that's value is currently processing while the template is running
in OOP it would be something like this.state
I think you're confused...
where the this referes to the current object and the state is the value of the state
Templates aren't a general thing that exist everywhere. Templates are used in scripts/sensors/etc.
Depending on where you use them, they'll look different.
yes, but I don't want to write always the entity id out to get the current state value if the mqtt message doesn't contain it
If there was a magical this.state, you'd be asking for the state of the script/automation/whatever.
Explain what you're trying to do.
Not how you're trying to do it.
I have a device that sends mqtt messages, I've wrote a custom template to extract one value from the message
however, sometimes this value is not there, in that case I want to keep the current, instead of update it to undefined/none
and for that I need to refer for the current state (value) of the sensor
Well, no, you don't. Use an automation instead to update something.
Only update it when you know the value.
o_O
The template won't know what entity it should give you the state of if you don't give it an entity ID. So either type the whole template out properly or find another way.
then I guess I will write out the full id of the entity, coz writing that amount of automation to update entity states will be too much to do
just it would be better if the template knows the context
Forget what you know about other programming languages. this requires you having a reference to the current object in scope. You don't have that.
now I would have easier job
If you think there's a better way to do it, submit a pull request with the improved functionality.
yeah, first I need to take care about phyton
the context is the entire state machine
automation get additional context of trigger
Hence the need to specify which part of the state machine you want.
Or use scripts to avoid updating something when the value is unknown.
just uses states('xxx.xxx') with the current template sensors entity_id. Templates in general have no idea about their current scope
beware circular references though
i think there was some protection added recently but that could definitely behave in unexpected ways
it doesn't, never really did. They just have a warning
heh ok
I think the warning is there if you're trying to average all sensors or something
like, you don't want to include yourself in your calculation
i thought i saw something for recursion
well, there is an issue with recursion & groups
like group a contains items from group b and group b includes a, there is protection for that
with expand
its like a 3 second timeout
oops
my general view on sensors is "they deal with what is not what was." and that holds true for template sensors
Yeah, I don't disagree. Just offering up work arounds if your saucy enough
https://pastebin.ubuntu.com/p/WJ5rgQvy44/ trying to find the right way for search operators and templates
Then you need to explain:
- what you're trying to do
- what the problem is
i'm trying to extract and view the body of a certain e-mail .
i tested imap connection and works, but i am not sure how to filter with template only certain mail
because the energy guys are sending more mails from same address
and i want to be retained only the mail containing 'Emitere factura' in subject
after this is retained, the i should get energy consumed and total value of invoice
problem: 1. not sure if value template for subject is ok
- search oeprators from and subject are not ok according to docs it should be
You could always consider other options for better scanning of mail: https://github.com/DubhAd/Home-AssistantConfig/blob/57960a56e0b1af0ec6dec4d71e031e948db09246/README.md#other-things
holly molly....need translator for those
It's a bash script. They look crazy but they're powerful.
so ...i should set some python reader in ha ?
Maybe it's not the option you want but it's an option.
No, it's not Python. bash is used by Linux.
It's a shell script.
oh..out-of-scope linux
maybe if the ram that arrived today help me have 8gb and make another vm with 2 gb...way to complicated
Hello, anyone have idea why this config file have a strange execution ? I dont understand why
https://pastebin.com/M727UJu2
Oh i cant send picture
Normaly the config file make a lot of switch named tv_voo , tv_appletv, tv_switch, ... but not really
He make a switch named tv_voo_2 for the tv voo, and switch tv_voo for tv apple tv ...
Its strange reaction
Harmony now creates switches
I have disabled the integration for manualy configure
But my configuration have strange reaction :/ i dont understand why
The first declaration of switch tv_voo are remplaced by tv_voo_2... realy#ly strange
And tv_appletv is remplaced by tv_voo... second switch dΓ©clarationπ€
i am trying to create a generic thermostat using https://www.home-assistant.io/integrations/generic_thermostat/
can i define target_sensor: value based on another entity attributes?
something like this: target_sensor: {{state_attr('climate.mco', 'current_temperature')}}
or do i have to create a sensor out of climate.mco attributes and then use that sensor as the value for target_sensor ?
That should work
if i use target_sensor: {{state_attr('climate.mco', 'current_temperature')}} when i press check configuration in settings >server controls i get the following error message
Error loading /config/configuration.yaml: while parsing a flow mapping
in "/config/configuration.yaml", line 451, column 22
expected ',' or '}', but got '<scalar>'
in "/config/configuration.yaml", line 451, column 84
ok, i added double quotes
now i get another error
Invalid config for [climate.generic_thermostat]: Entity ID {{state_attr('climate.mco_sonia_climate', 'current_temperature')}} is an invalid entity id for dictionary value @ data['target_sensor']. Got "{{state_attr('climate.mco_sonia_climate', 'current_temperature')}}". (See ?, line ?).
Sounds like target_sensor doesn't want to take a template, so yeah; make a template sensor to give the value you want
Writing my first template (well, copying). Does it go into config.yaml?
typically
the templates docs don't really say
they can go in automation.yaml or scripts.yaml if you have them
but it depends on what you're trying to do
nub question.. is there another alternative adding + 2hours instead +7200 seconds ? tq
https://paste.ubuntu.com/p/m2brfC2Drm/
Can someone help me with templating? I'm trying to set value as float and use the value in numeric_state trigger, but the value is string instead of float. what am I doing wrong?
https://paste.ubuntu.com/p/2SKH4jqpgx/
States are always strings, and you are applying the float filter in the wrong places. https://paste.ubuntu.com/p/TvS4FJT4Wm/
okay, thanks! :)
so I should do automations like this instead?
trigger:
- platform: template
value_template: "{{ states('sensor.xiaomi_airhumidifier_depth')|float <= 25 }}"
If it is an integer or you don't care about the fractional part. Otherwise use |float
The main issues were in your sensor. Make sure to fix that too.
yeah, I did :)
No, timestamps are in seconds.
If you want to visualise that it's hours, do the math...
somenumber + (2 * 60 * 60)
With simple multiples like 3600, it's easy to remember that's an hour... but when you want 12.5 hours?
Thanks Tom. Thanks mono i will try it. Looks beautiful than +7200. Prayer time always change time to time, this is to turn on water pump 1 hour before and 2 hrs afterπ
Hi guys i have a motion sensor that i have integrated trough tellstick but its a switch and is not reacting in HA when i for example wave my hand. So i was thinking about making a binary sensor with template this is my code:
binary_sensor:
- platform: template
switches:
switch.motion_sensor_10981222:
movement:
device_class: motion
value_template: "{{ states('switch.motion_sensor_10981222') }}"
But im getting a error on
Invalid config for [binary_sensor.template]: [switches] is an invalid option for [binary_sensor.template]. Check: binary_sensor.template->switches. (See /config/configuration.yaml, line 42)
Can anyone guide me in the right direction?
@gray loom check out the docs here: https://www.home-assistant.io/integrations/binary_sensor.template/#switch-as-sensor
why does it expect "sensors:" argument when the point is to make a sensor FROM a switch?
the switches: line isn't applicable here, the example linked above i think does the exact thing you're trying to accomplish (turn a switch device into a binary_sensor)
because that's how it works my man π you are creating a sensor. that line isn't talking about the source device.
binary_sensor:
- platform: template
sensors:
motion_sensor:
friendly_name: "Motion Sensor"
device_class: motion
value: template: "{{ states('switch.motion_sensor') }}```
^^^
replace motion_sensor and "Motion Sensor" with whatever entity id and name you want to use.
yaml is tweaky in general @gray loom , it can be counter-intuitive at some times. best solution is to follow the docs precisely. i've been using hass for a couple years and still have to refer back to examples like this.
just part of the fun π let us know how it works out for you!
binary_sensor:
- platform: template
sensors:
switch.motion_sensor_10981222:
friendly_name: "Motion Sensor1"
device_class: motion
value_template: "{{ states('switch.motion_sensor_10981222') }}"
changed to this and still no luck
are you sure about value:template:?
yes
switch.motion_sensor_10981222: is your problem
change that to motion_sensor.
that line is declaring the name of the new binary sensor you are creating
so, you tell it the name of the new device, down below you are telling it the name of your existing device in the template
alright, its restarting now at least π
you got this my man π
I should have phrased this as "the entity id and name of the sensor you want to create"
