#templates-archived
1 messages · Page 37 of 1
Would appreciate any advice on converting a select entity value to a time please? The values appear to be strings, with values being HH:MM:SS format.
- '00:00:00'
- '00:01:00'
- '00:02:00'
- '00:03:00'```
I'm looking to use the conversion in a binary sensor template:
```template:
- binary_sensor:
- name: "On GivEnergy Timed Charge"
state: >
{{ states('select.givtcp_ceXXX_charge_start_time_slot_1') | as_datetime | as_local <= now()
< states('select.givtcp_ceXXX_charge_end_time_slot_1') | as_datetime | as_local }}```
The above currently fails with `AttributeError: 'NoneType' object has no attribute 'tzinfo'`
today_at(states('select.bla'))
which will give issues if you compare 23:00:00 as start with 01:00:00 as end and expect it to be true
Excellent point, thank you.
Fortunately our off-peak tariff is 00:30 to 04:30 so not an issue currently.
if one starts at 00:30 the other must end at 00:30
but if it's only two tariffs, you can do the easy check
i have build an alternative template, what do you think? template:
- sensor:
- name: "BatteriespeicherProzent04"
state_class: measurement
value_template: >-
{% if states('sensor.shellyuni_e868e7f472ec_adc') | float(0) > 27.2 %}
100
{% else %}
{{ ((states('sensor.shellyuni_e868e7f472ec_adc') | float(0)-20.0) / 0.222) | round(0) }}
{% endif %}
unit_of_measurement: "%"
icon_template: "mdi:battery-charging-high"
- name: "BatteriespeicherProzent04"
it's not correct if you're using >-. Your template is not moving to the next line
also, you can set a variable instead of converting to a float twice
Also, your previous example was using the new style of template sensor, but this is kinda sorta the legacy format, as it uses value_template but is missing platform. I'd recommend using the initial way you had it w/ state
{% set adc = states('sensor.shellyuni_e868e7f472ec_adc') | float(0) %}
{{ iif(adc > 27.2, 100, (adc - 20) / 0.222) | round(0) }}
Also also, I have no idea about that formula, but it seems wildly different from your initial example. For example, if you use 27 in the equation, it results in 31.5.
I would assume the eq would be
{% set adc = states('sensor.shellyuni_e868e7f472ec_adc') | float(0) %}
{{ iif(adc > 27.2, 100, adc / 0.272) | round(0) }}
Sounds like 20 = 0 though
yes its a LifePO4 Battery. 20V meins 0% and 27,2V means 100%
Can someone help me out with icon templates? This is my code, which I can't get to work:
switch:
- platform: command_line
switches:
melody_1:
command_on: '/usr/bin/curl -sS -X GET "http://192.168.1.10/?action=command&command=melody1"'
command_off: '/usr/bin/curl -sS -X GET "http://192.168.1.10/?action=command&command=melodystop"'
command_state: '/usr/bin/curl -sS -X GET "http://192.168.1.10/?action=command&command=value_melody"'
value_template: '{{ value > "value_melody: 0" }}'
friendly_name: "Melody 1"
icon_template: >
{% if value > "value_melody: 0" %} mdi:music-note
{% else %} mdi:music-note-off
{% endif %}```
Why does the documentation show that then? https://www.home-assistant.io/integrations/switch.command_line/
Ok, color me surprised, it's one of the few that mst have it
anyways, your templates isn't correct
you're comparing greater than with 2 strings
Then the template itself might be the issue. What is wrong about it?
the "value_template" is working
ask yourself.... is a greaterthan or less than b?
The camera "command_state" is outputting: "value_melody: 0"
ok, so then parse out the 0
Somehow this works value > "value_melody: 0"
for the command_state, but not for the icon_template.
(value | split(':'))[-1].strip() | float(0) > 0
Let me try that
value_template: "{{ (value | split(':'))[-1].strip() | float(0) > 0 }}"
icon_template: mdi:music-note{{ '' (value | split(':'))[-1].strip() | float(0) > 0 else '-off' }}
This one doesn't seem to work, breaks my config.
TemplateSyntaxError: tag name expected
that error does not make any sense
post how you used it
maybe split isn't a filter
do this instead
value_template: "{{ value.split(':')[-1].strip() | float(0) > 0 }}"
icon_template: mdi:music-note{{ '' value.split(':')[-1].strip() | float(0) > 0 else '-off' }}
The system cannot restart because the configuration is not valid: Error loading /config/configuration.yaml: while parsing a block mapping in "/config/packages/cameras.yaml", line 5, column 9 expected <block end>, but found '<scalar>' in "/config/packages/cameras.yaml", line 9, column 42
can you post what you're using please
yes, one sec
@slate laurel I converted your message into a file since it's above 15 lines :+1:
You didn't copy what I wrote
you have single quotes outside your template
and single quotes inside
ah now I see it
Notice how I have double quotes outside and single quotes inside?
Yes I do now
Next error 🙂
The system cannot restart because the configuration is not valid: Invalid config for [switch.command_line]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'value') for dictionary value @ data['switches']['babycam_melody_1']['icon_template']. Got "mdi:music-note{{ '' value.split(':')[-1].strip() | float(0) > 0 else '-off' }}" invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'value') for dictionary value @ data['switches']['babycam_melody_2']['icon_template']. Got "mdi:music-note{{ '' value.split(':')[-1].strip() | float(0) > 0 else '-off' }}". (See ?, line ?).
icon_template: mdi:music-note{{ '' if value.split(':')[-1].strip() | float(0) > 0 else '-off' }}
The system cannot restart because the configuration is not valid: Invalid config for [switch.command_line]: invalid template (TemplateAssertionError: No filter named 'split'.) for dictionary value @ data['switches']['babycam_melody_1']['value_template']. Got "{{ (value | split(':'))[-1].strip() | float(0) > 0 }}" invalid template (TemplateAssertionError: No filter named 'split'.) for dictionary value @ data['switches']['babycam_melody_2']['value_template']. Got "{{ (value | split(':'))[-1].strip() | float(0) > 0 }}". (See ?, line ?).
that's an old error or you didn't update the template
split isn't being used as a filter
Did you undo a bunch of crap?
Nope, I just updated the "icon_template" that you just send me.
sorry man, but you're lying somehow
icon_template: mdi:music-note{{ '' if value.split(':')[-1].strip() | float(0) > 0 else '-off' }}```
whether you know it or not
Ok, you just posted above
value_template: '{{ value.split(':')[-1].strip() | float(0) > 0 }}'
and now you're using
value_template: "{{ (value | split(':'))[-1].strip() | float(0) > 0 }}"
so which one are you actually using in your config?
because the | is not correct,
Please just copy and paste this, do not try to type it yourself. The whole thing
value_template: "{{ value.split(':')[-1].strip() | float(0) > 0 }}"
icon_template: mdi:music-note{{ '' if value.split(':')[-1].strip() | float(0) > 0 else '-off' }}
np
Used this that error'd
Did not alter anything to it actually
The icon is still not working now
but the state changes? because that makes no sense.
The state changes indeed
oh wait
icon: hass:music-note
switch.babycam_melody_1:
icon: hass:music-note```
that was my customize.yaml
dumb me 🤣
Might have been the issue all along... it works now. Thanks for your help!
Have a slightly smoother solution now anyways.
Is there any way to buffer serial data. I am using serial integration.
- platform: serial
serial_port: /dev/ttyUSB0
baudrate: 115200
{{states('sensor.serial_sensor')}}
is working
Important need is to buffer
Buffer in regards to what? Adding a buffer won’t do anything
If you want to get technical, the baud rate is equivalent to your buffer size on the serial port
my serial device sends data at every second then i can get data {{states('sensor.serial_sensor')}}
But this {{states('sensor.serial_sensor')}} can get one data end with /n or /r
9 9 0 900 5 /n
8 1 1 100 1 /n
7 600 7293 553 352 /n
6 100 2 1 1 1 1 2 30000 0 /n
5 9900 0 30000 50 65 /n
4 15000 1000 1500 1000 800 /n
3 90 500 0 0 0 /n
But i need above these all get simultanueous.
The Attribute 'rain' is not provided when no rain is expected. Shouldn't the is defined catch that? I've also tried the new has_value() and it fails as well. The Template editor just says that 'dict object' has no attribute 'rain' (This works fine however when Rain is expected).
{% if state_attr('sensor.openweather_report', 'hourly')[1]['rain']['1h'] is defined %}
{{ ( state_attr('sensor.openweather_report', 'hourly')[1]['rain']['1h'] | float(0) / 25.4 ) | round(2) }}
{% else %}
0
{% endif %}
So when no rain is expected, the state (that's fed by this template) reports as unavailable instead of zero.
{% if state_attr('sensor.openweather_report', 'hourly')[1]['rain'] is defined %}
Ah, since rain is not defined, rain.1h can't be. Got it. Thanks!
Hi, I started with HA yesterday and a friend gave me a template for yaml to check my printer status, and now it's not working. It's returning Unknown, but when I test it on developer tools it works, can anyone help me?
If you share it and the error it produces, someone can try and help
@fiery mirage I converted your message into a file since it's above 15 lines :+1:
on my views, power returned, returns a value, but hotend temperature returns: Unknown
if I check the sensor it shows OK and on its attributes, shows all json values correctly
Looks like your unit of measure might be incorrect, but that doesn't seem like it'd cause that. What does your home-assistant.log say
I don't see anything related to it
I'm going to delete it and restart HA to check
oh I figured it out.. the problem lied elsewhere:
switch:
Voron Power Switch
- platform: rest
name: "Voron v2.4 - 200W PSU"
resource: "http://192.168.31.100:7125/machine/device_power/device?device=200W_PSU"
body_on: '{"action": "on"}'
body_off: '{"action": "off"}'
headers:
Content-Type: 'application/json'
is_on_template: >-
{{ 'result' in value_json and (value_json.result.values() | list | first == "on") }}
it seems that is breaking the rest
To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
You need a line break after >-
G'Day
I'm having problems converting this sensor to the recommended template sensor format:
`sensor:
- platform: template
sensors:
last_alexa:
entity_id:
- media_player.kitchen_echo_dot
- media_player.main_bath_echo_dot
- media_player.office_echo_dot
- media_player.lounge_echo_dot
- media_player.bedroom_echo_dot
value_template: >
{{ states.media_player | selectattr('attributes.last_called', 'eq', True) | map(attribute='entity_id') | first }}`
Because it's got a list of entity_id
I read some posts on the forum where the recommended format is supposed to automatically pick the entity_id (which works fine if it's just one) but it doesn't seem to pick multiple entity_id
Well...you don't need to list out all the media_players you wish to track, since you're already filtering through all of them in the value_template.
I tried removing the entity_id key in the new format but it didn't work
You're using a "state_based template sensor": https://www.home-assistant.io/integrations/template/#state-based-template-binary-sensors-buttons-numbers-selects-and-sensors. You may also consider more precise control with trigger-based ones.
Because you need to change the format of the whole block to the new structure. It's still using the old one.
yeah...i formatted accordingly to the new template sensor format but removed entity_id
as per the docs...I've converted all my other sensors this is the only one with a list
or maybe I fat fingered it...
That codeblock you posted above is still in the old format. Can you post what you have so far in trying to convert to the new format?
Point being...the new format can't have the entire entity_id: list in the first place. Just remove it in the new format.
- sensor:
- name: "last_alexa"
state: >
{{ states.media_player | selectattr('attributes.last_called', 'eq', True) | map(attribute='entity_id') | first }}```
son of a whore. I was hitting the "ALL YAML CONFIGURATION" button to reload but updating a template sensor appears to require a full HA restart
disregard it works fine
Hi guys any way that would make it work?
attributes: !include dictionnaries/dog_food/{{ states('input_select.dog_food_list') }}.yaml
Would be nice if the reload could tell you what isn't going to be picked up
is it possible to in to get a list of all integrations installed using templates
i know you can do the other way around
not an exhaustive list 😦
I want to convert my weather station output wind speed from m/s to knots can you please help
My information is comeing from the mqttbroker using rtl 433 esp32 bord
I was commenting out and alternating between the new and old format, I guess half the time it wasn't loading...doh
@dusk sorrel I converted your message into a file since it's above 15 lines :+1:
Hello, im trying to use smart plug sensor entity to trigger reload smart plug (binary_sensor.plug_problem reloads switch.plug using call service homeasisstant.reload_config_entity ).
Im currently using working "Choose" action with conditions in it for each plug but I wanna simplfy this with "trigger.entity_id".
How do I use templates to do "{{ switch+ 'trigger.entity_id' }}" without "_problem" in triggers name?
what is the correct yaml syntax for a template sensor? is it under sensor: - platform: template or template: - sensor?
it's platform device
trigger:
- type: problem
platform: device
entity_id: binary_sensor.test_plug_error
domain: binary_sensor
This template used to work, but now i get "statistics_not_defined":
- sensor:
name: Solar Panel Production
state_class: total_increasing
unit_of_measurement: kWh
device_class: energy
icon: mdi:solar-panel-large
state: >
{{ states("sensor.helper_envoy_current_power_production_riemann")|float }}
And also, entity not available
Both are correct, but the first one is the legacy format, I would advice to use the second one
Is "state_class: total_increasing" incorrect?
I changed it to measurement, still the same error
When using dev tools it gives the error 'float got invalid input'unknown'
However when I check the helper, it has no problems in the statistics screen
ChatGPT found the problem, float should be float(0)
why is that even a template sensor, the template is doing nothing. Same with float inside the template.
if that's just an integration sensor, just set that up properly and you don't need the template sensor.
and chatgpt bandaided the problem, if you really want that template, it only needs to be {{ states("sensor.helper_envoy_current_power_production_riemann") }}
Because the energy dashboard wont take the helper as an input
then you didn't set the helper up properly
if you set the helper up via the UI, it should just work as it will attach all the necessary attributes needed for long term stats
It does perfectly show the production in kwh
But for some reason, me and everybody else using enphase needs this template
that doesn't make any sense, as enphase isn't creating the kWh sensor
it's creating the kW or W sensor which you're integrating
Yes, and the riemann helper turns it into kwh
yes, and that would have state_class and device_class pre built into it
Can you post whatever guide you're using? because it's misleading you and everyone else using enphase
Yeah, post 93 confirms that the template is not needed if you keep reading
So if you have a power sensor, just create a integration sensor and you're done
Keep in mind that you have to wait for the integration sensor to be placed into the database (takes about an hour)
regardless, if you're dead set on using the template sensor.... just remove | float(0)
it's not needed because you're not performing math
I just checked, device class is mossing
Missing*
But i'll have a look at the integration sensor
did you add your integration sensor via the UI or yaml?
UI
does your source sensor have device_class: power?
How do I check?
same way you checked the other sensor
you just said device_class was missing on the helper
are you checking via
Open your Home Assistant instance and show your state developer tools
?
It doesnt have device class
that's probably the root of the problem, does it have a unit_of_measurement?
this is for the source sensor, not the helper
Yes, W
yeah, then it just needs a device_class and it should propagate. Personally, I'd write up an issue against your enphase integration.
Yeah, write up the issue against whichever one you're using
@dusk sorrel I converted your message into a file since it's above 15 lines :+1:
@dusk sorrel you're accessing item 6 and 7 which sometimes do not exist
if you want the last 2, use -2 and -1 instead
mmhna i am test it.
mmm same ....
@mighty ledge same result.
is that possible parsing process slow than incoming serial data?
@dusk sorrel what's teh actual error
If your array doesn't have at least two items in it, accessing -2 and -1 will probably error too.
wth is that thing around your avatar?
it costs money?
It's a Discord avatar decoration, part of nitro
@woven folio I converted your message into a file since it's above 15 lines :+1:
https://pasteboard.co/TD8zApAihQSH.png
This is the graph. Top is watts , middle is kWh, bottom is the template total
every graph has 2 lines, that are the 2 EM channels
the question is, how the missing data did mess the template totals so badly? (i can assure i never used 16k kWh since started using that Shelly EM, in fact, the real total consumption of those 2 channels, since start, is around 850kWh, as per sum of middle graph channels).
You're defaulting the value to 0 with | float(0) when the sensors are unavailable.
so when they jump from 0 to whatever they were before, that jump is added on
you should incorporate an availability template
ah
i suspected something similar
think is enough if i use one of the two channel sensor availability, because it's one shelly alone.
thanks for the help, i'll see if it works in the next days
in the same line?
yes, just need an and
{{ states('xxxx.xxx') | is_number and states('yyyy.yyy') | is_number }}
ok, i'll give it a try
thanks again
@silent seal that actually works fine
{% set t = [] %}
{{ t[-2:] }}
Results in []
Ahh, I missed the context 🙂
Wait, directly accessing -2 doesn't
Were there changes in the 2023.4x releases that changes template sensors? Several of my template sensors stopped working. They worked in beta and on the .0 release
no
seems like you're having other issues unrelated to commandline or template sensors
There is new functionality, but nothing breaking
No
Well, nothing changed with command line or template sensors and you're having issues with both
Can you give an example of a non working sensor?
sensor:
# Sensor to track available updates for supervisor & addons
- platform: command_line
name: Supervisor updates
command: 'curl http://supervisor/supervisor/info -H "Authorization: Bearer $(printenv SUPERVISOR_TOKEN)" | jq ''{"newest_version":.data.version_latest,"current_version":.data.version,"addons":[.data.addons[] | select(.version != .installed)]}'''
value_template: "{{ value_json.addons | length }}"
json_attributes:
- newest_version
- current_version
- addons
Why not use secrets in the sensor? 🤔
packages?
?
are you running packages?
Yes
are other things in those packages working?
I'll paste better info when I get home
to me, it seems like somthing changed in configuration.yaml and things are loading
because you'd have errors
Everything else works except the status of the updates
what do you mean 'status of the updates'
I changed nothing. HACS has update, version of core, etc
Can't you get all of this out of the update entities?
Don't understand
For example: https://www.home-assistant.io/integrations/hassio/
More info: https://www.home-assistant.io/integrations/update/
No. Mine would give me which HACS needed update, which addon etc
But those all have update entities?
I think there's some miss communication happening here
If you enable HACS experimental mode
I don't think he's talking about update entities
I'm talking about if a HACS integration or card update is available it would list which one and the version
that's not working?
Same with add ons, core su
Well, this can be gathered out of the update entities, which are also provided by HACS then experimental mode is activated
well, as an aside, about 4 major versions ago, HACS completely changed how update querying works
Ok. Something to learn later. Still something changed as it worked until .3 was released
it went from all the time, to every 6 hours, to every 48 hours with fancy code
FWIW, I'm on 2023.4 and all of the above are working normally
Not only HACS, but core, su and other sensors stopped as well
Wait a second, those are under sensor
right, which circling back, you have template sensors and command line sensors that are not working as well. I.e. Something major is going on and everything you're listing is a symptom of the real problem.
Template sensors should be updated and put under template
If you run a config check, what do you get out?
I'll check it when I get home
TBH it seems like your configuration isn't loading all of the integrations
and you may be in safe mode
The code above is a command line sensor
It doesn't look like safe mode.
Which is why I noted template sensors 🙂
Maybe after 10.0 release locked my system, something got hosed
No, a whole bunch of endpoints were removed from the API. https://github.com/home-assistant/core/issues/89919#issuecomment-1476210147
Any idea how I can make a sensor that counts how many of a certain sensor are over a certain value
I have this so far:
{{ states.sensor | select('search', 'plex_usage_monthly')
| selectattr('state', 'ne', '>0') | list | count }}
but something is wrong with that
there are a few things wrong
select('search', 'plex_usage_monthly') is trying to test a state object against a string
and this is using the wrong syntax: selectattr('state', 'ne', '>0')
{{ states.sensor | selectattr('object_id', 'search', 'plex_usage_monthly') | map(attribute='state')|map('float')|select('gt', 0) | list | count }}
ah I see. I tried to modify something that came up from a search where the person was counting sensors with a certain value, I guess a string in that case
TypeError: '>' not supported between instances of 'float' and 'str'
I edited it
Just got my hands into the new Jinja macros capability
Just to check though...for new macros and new .jinja files to be picked up, is a HA restart necessary?
Great, thanks for the pointer!
there is not error. Sometimes can not catch own value or sometimes can catch own value.
It can catch and parse 100% of the data coming in one second apart. However, since the data is hundreds of milliseconds apart, it can't be caught and parsed, or sometimes it can be
is it possible to get the link from "Read release announcements" via template? Rightnow, for OS update it's different than the release_url attribute
@orchid oxide where do you see that link?
this one you mean?
where the release_url attribute points to https://github.com/home-assistant/operating-system/releases/tag/10.0
and they look quite similar to me 🙂
Thanks again @orchid oxide for your hint recently. I solved it by adding a separate sensor with correct value_template for the type of waste and added both sensor (date and type) states in the automation message. 🤗
@crimson lichen I converted your message into a file since it's above 15 lines :+1:
Home Assistant Operating System Update:
|-> Installed Version: 9.5
|--> Latest Version: 10.0
|--> 11:14:43 Wednesday 19-Apr-2023
@crimson lichen I converted your message into a file since it's above 15 lines :+1:
can we also reject device_attr('manufacturer','Fibargroup')? currently I set a rather extensive ignore liste verbosely, but it would be much easier if I could simply reject these
like this in pseudocode: {{expand('group.switches_sensors_actueel') |rejectdevice_attr('manufacturer', 'Fibargroup') |map(attribute='entity_id') |list}}
you can...
| reject('is_device_attr', 'manufacturer', 'Fibargroup')
right! thx. I also forgot the order of things.... but this does what I need: {{expand('group.switches_sensors_actueel') |map(attribute='entity_id') |reject('is_device_attr', 'manufacturer', 'Fibargroup') |list}}
nice
Anyone who is wondering how I fixed this problem. Here is my Action in YAML:
service: homeassistant.reload_config_entry
data: {}
target:
entity_id: >-
{{ trigger.entity_id | replace('binary_sensor.', 'switch.') |
replace('_error', '') }}
I don't see how that would work
You need to remove the quotes around trigger.entity_id
if I remove quotes it wont work
but now it does
you can't test actions without a trigger
None of the things you're replacing are in that string
so those "test actions" buttons won't work
That too
I know I waited very long of the the day yday to test this
you also have to make sure your trigger produces an entity_id key when it triggers
but if I specify enitity in developer templates it works too only with quotes
for example, time triggers do not have entity_id
yes, because your trigger doesn't exist.
It can't 'work'. You're not actually replacing anything
I would believe 'doesn't result in an error'
hi all, I have a numeric state trigger based on a device (Dyson fan with air quality monitoring) that does a self-check or reboot every mid-night. When the device comes back online, for the first 1 minute or 2, the values are 'null' or 'fail' something like that, basically its not a numeric value. So, I get error logs everyday telling me this. How can I create a not_from to exclude ALL non-numeric values, or do I have to specifically add 'null', and/or 'fail' to this
- condition: template
value_template: "{{ trigger.from_state.state not in [none, 'unknown', 'unavailable']}}"
trigger.from_state.state | is_number
oh that makes sense! so this would also exclude none, 'unknown', 'unaviable'?
or, I would have to create a second condition
Yes, because those are not numbers
i click on this link and it takes me to the ha blog page, not the github paage. unsure what the discrepancy is there. (release_url is the github link same as yours)
Are you maybe referring to the core update? Because there the release notes are indeed the blog post
nono, the latest os update took me to a blog page
i updated since so i dont have it anymore, but im quite sure the link took me strqaight to the blog on version 10
Hmm, strange, for me both the URL in the text and the URL in the attributes are the same and send me to GitHub
odd indeed
Anybody willing to help me out with handling an error in a template? For whatever reason, Environment Canada's weather station near me is down, and so all weather entities are throwing "unavailable" which doesn't work well in a template that I'm using. I wonder if there's a way to revise my template so that while the thing is down, my template can render an integer to actually work with my automations rather than just have them error out.
Template below:
{% if ((states('sensor.weather_high_temperature')|int) -
(states('input_number.yesterday_high_temperature')|int)) > 10 %}
{{ (10 * 17.35) + 326.5 }}
{% elif ((states('sensor.weather_high_temperature')|int) -
(states('input_number.yesterday_high_temperature')|int)) < -10 %}
{{ (-10 * 17.35) + 326.5 }}
{% else %}
{{ (((states('sensor.weather_high_temperature')|int) - (states('input_number.yesterday_high_temperature')|int)) * 17.35) + 326.5 }}
{% endif %}
For your |ints you can add a default like |int(0) to use 0 as a default if the state isn't an int
or you can add a top level if something like {% if not 'sensor.weather_high_temperature' | has_value %} and do something completely different
TIL how default values work in JINJA. Thanks a ton!
Love that template - might be the first "advanced" use of HA I ever did. It sets the color_temp of a Hue bulb at the front door of our house every morning and evening. By comparing yesterday's stored high temperature with today's forecasted high temperature, it makes the bulb change colour to give the differential temperature from yesterday. So the first light I see in the morning tells me whether today's going to be warmer or colder than yesterday and by how much (+/- 10°C). Let's be honest: -10 right now feels a heckuva lot warmer than it will in say July, so I rarely care about the actual temperature forecast.
...that is, as long as HA can get a forecast for the weather.
@mighty ledge
I have something strange here. I created a macro to find the cheapest consecutive block of hours for dynamic engery prices, this works fine. The output is an isoformat() string of a datetime object.
However, if I want to convert that to a datetime again, it doesn't work
{% set d = cheapest_energy_hours('sensor.nordpool_kwh_nl_eur_3_10_021', 3) %}
{{ d }} output: 2023-04-21T12:00:00+02:00
{{ as_datetime('2023-04-21T12:00:00+02:00') }} output: 2023-04-21T12:00:00+02:00
{{ as_datetime(d) }} output: null
do you have any idea why?
as_timestamp also doesn't work on it
if you want to test it, here is the code https://github.com/TheFes/cheapest-energy-hours but you need an integration to supply the sensor of course (eg this one https://github.com/custom-components/nordpool)
It does work if you create a template sensor using the macro, and use as_datetime on the state of that sensor. So there is something strang going on with that output. However d is string returns true
Your macro most likely has extra spaces. Do this for me.
xxx
{{ cheapest_energy_hours('sensor.nordpool_kwh_nl_eur_3_10_021', 3) * 2 }}
leading spaces would be my guess
anyways, when making macros, use - at the beginning and end of every line if it's returning a datetime
jep that was it
yep, leading whitespace
so make sure all your lines that don't output code start with {%-
at a minimum
if you put the
xxx
before it, you can see the leading and trailing whitespace
TLDR: as_timestamp and as_datetime have a regex search func that uses ^ meaning leading whitespace fucks it up
Thanks a lot, I added a - everywhere now 🙂
Yep, that's what I did when I ran into this last week
{%- -%} {{- -}}
yah, I only do it on time macros though
makes mental note
well, I do it on most
lol, yup
it was a PITA to find
because the template editor removes the whitespace
that's why I've always done testing with
xxx
{{ ... }}
cause that will show you your whitespace without the editor 'cleaning it'
I have to stop making changes to the repo, like this it will never get approved 😛
what repo you working on now? Energy one?
no, the one with this macro I meant, but Ludeeus sorts on last changed and uses that to approve. So everytime I make a change, I will be back at the end of the list
Hello, I asked a question in #frontend-archived that probably was more accurate to be posted here.
To avoid duplicates, if you think you might be able to help, please check #frontend-archived message
(was unaware discord post links now did that hyperlink thing, pretty cool)
You can and conditions together
ex. {% if states('binary_sensor.occupancy_hall') == 'on' and states('binary_sensor.presence') == 'on' %}
Figured it out yeah:
blue-grey
{% elif states('input_boolean.room_hall') == 'on' and states('input_boolean.room_office') == 'off' %}
red
{% else %}
disabled
{% endif %}```
Thank you!
Is there any way to "simplify" the two "ON" line?
As in something like {% if states('input_boolean.room_hall','input_boolean.room_office') == 'on' %}
is_state('input_boolean.room_hall', 'on')
oh, wait, for the two combined
[ 'input_boolean.room_hall','input_boolean.room_office' ] | select('is_state', 'off') | list | count == 0
but I don't think that is more simple, maybe if you have 20 input booleans it is 🙂
what am I missing here:```
- unique_id: saldo_totaal_dag_energie_afname_of_levering
name: >
{% set saldo = this.attributes.saldo %}
{% set phrase = 'levering' if saldo < 0 else 'afname' %}
Saldo: {{phrase}} vandaag
state: >
{% set saldo = this.attributes.saldo %}
{{saldo if saldo > 0 else saldo|abs }}
attributes:
saldo: >
{% set saldo = expand('sensor.grid_energy_teller_1','sensor.grid_energy_teller_2')
|selectattr('state','is_number')
|map(attribute='state')
|map('float')|sum %}
{{saldo}}
I get an Error rendering name template for sensor.saldo_totaal_dag_energie_afname_of_levering: UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'saldo' but I do have that attribute??
before you ask what I am doing.... I need the net saldo to be a positive number, to be able to show it in a sankey chart.... thats why I use a template also on the name. normally returning to grid would be negative (the attribute saldo is)
Yeah I see, thank you. I don't think it's worth it since it looks so similar.
But since I'm gonna replicate it through most rooms in the UI was worth asking before doing all the heavy work.
Perhaps on the initial render, the attribute isn't actually there
yes, Ive considered that, but its a trigger template and should update each minute. wouldnt it re-render at that moment? Besides that, checking startup while all individual template are displayed on dev templates show them all available, except this composite template sensor... ive added this.attributes.saldo|float(0) now just to be sure it is not a Type issue.
Ah, didn't have the trigger section 🙂
no change. and consider this: during startup: unknown
after startup: unavailable
same result using this.attributes.get('saldo') btrw
that will probably give a different error about comparing a nonetype object againts an integer
try this.attributes.get('saldo', 0)
this does work: name: > {% set saldo = this.attributes.get('saldo')|float(0) %} {% set phrase = 'levering' if saldo < 0 else 'afname' %} Saldo: {{phrase}} vandaag state: > {% set saldo = this.attributes.get('saldo')|float(0) %} {{saldo if saldo > 0 else saldo|abs}}
a right, crossposted, sorry
this.attributes.get('saldo', 0) returns the same, so probably the better syntax when using the get function. thx
and now for the most difficult question.... what state_class would this be. it's an energy sensor, and have settled for state_class: total now? because of The state represents a total amount that can both increase and decrease, e.g. a net energy meter....
not sure if the |abs throws that logic overboard (normally it would be negative)
Hi how can I implement this python script with HA? I have tried Http request but no luck! The python script is from idigo domotics and works. import requests
payload = {"activity_uuid":"AFDF357D-23C0-45FC-8109-1E89C1B8B4B9"}
requests.post("http://192.168.1.97:47147/api/v1/runactivity", json=payload)
Hi thank you for your reply I have tried that I can’t get it to work!
You'll need to provide what you've tried along w/ the errors you're seeing to get help making it work
And hopefully you understand what the original code was doing
Im new to HA sorry for the trouble! I have added the rest command to my Yaml folder with the http url!
rest_command:
mport_requests:
url: "http://192.168.1.97:47147/api/v1/runactivity"
method: POST
payload: {"activity_uuid":"AFDF357D-23C0-45FC-8109-1E89C1B8B4B9"}
I have tried this
Never mind I’ve got it working thanks for your help
I have a date_time helper, in which I want to write the date of today or tomorrow after pressing a button. I succeeded in writing today with the following Action:
service: input_datetime.set_datetime data: date: "{{ now().strftime('%Y-%m-%d') }}" target: entity_id: - input_datetime.xxxx
My question is: how can I write the date for tomorrow?
date: "{{ (today_at('00:00') + timedelta(days=1)).strftime('%Y-%m-%d') }}" should work
awesome, much appreciated
Is it possible to have more than one rest_command in your yaml file?
That is correct!
is there a way to set an input_number in a template?
something like: {% set input_number.rain_house_last.set_value(10) %}
please don't crosspost
I'll say again - templates can't do anything, you need to use a service call
can you please say again, where I can find an example of that?
in the docs for input_number
see the examples involving input_number.set_value: https://www.home-assistant.io/integrations/input_number/#automation-examples
yea I was looking at them.. What I want to do is watch the state of a sensor (VL53L0X) for a distance value, but the sensor at times sends a -1 for unknown, and I want to grab the last known good value > -1 and store that, and if then in a template if the state of the sensor is a -1 then use the input value. if the value > -1 then use the currently sending value. am I going about this correctly?
no
that is not the best way to accomplish that
a simple template sensor like this would do it:
template:
- sensor:
- name: positive_test
state: "{{ this.state if states('input_number.test')|float < 0 else states('input_number.test') }}"
sweet thank you I will play with that
Any one got any tips on how to calculate the energy consumption of my home between 4pm and 2am 7 days ago? I do have a sensor that records live consumption so I assume I either need to read it’s history or create some kind of helper?
Check out the statistics sensor https://www.home-assistant.io/integrations/statistics/
Though tuning it to just 4pm to 2am 7 days ago specifically may be a challenge.
I currently have the following template switch for controlling a light
switch:
- platform: command_line
switches:
office_monitor_ambilight:
command_on: "curl -s -o /dev/null 'http://192.168.1.189/cmd?ledstripenabled=on'"
command_off: "curl -s -o /dev/null 'http://192.168.1.189/cmd?ledstripenabled=off'"
command_state: "curl -s 'http://192.168.1.189/ssi/toolpage.ssi' |jq -r '.ledstripenabled'"
value_template: '{{ value == "1" }}'
I want to do something almost identical but that taggles between a value of 1 and 2. IS there a better way to do that than this or is this exactly the way I should do it? what happens when the value is 2?
It will be off
in my case it would be more correct to interpret 2 as on and 1 as off.
Then test for that
but really it's a toggle between static colour and following what's on screen
more of a mode switch
has more modes but these are the only 2 i use
is there an equivalent multimode switch template?
or not really switch.. selector
if I trest for 2 won't it always be on and thus never toggle?
do I have to do if 2 then 1 and if 1 then 0 or something?
well I need 1 to be false
It's not 2
Look, test for what you want to be true and anything else will be false
That is boolean logic
so is value_template the value that will always be considered to be on/true?
I don't understand that. I will just have to see what happens
hmm.. does reloading templates not reload template switches?
how will 1 ever be false?
looks like I have to restart home assistant to relaod a switch template
That is not true
well I reloaded/restarted templates and it didn't come up
maybe it's a command line entity instead
it is
doh
Indeed
toggling doesn't appear to work
and manually setting the state also does not appear to work.. or at least it does not affect the device
I'll try directly from the command line
works from the command line
same issue whether I set the value template to 1 or 2. No idea why it doesn't work with either.
doesn't seem to be triggering the switch. that seems to be the crux of the problem
and triggering the switch by setting it's state also has no effect
works from the command line.. doesn't work in home assistant
- platform: command_line
switches:
office_monitor_ambilight_mode:
command_on: "curl -s -o /dev/null 'http://192.168.1.189/cmd?ledprofilevideo=2'"
command_off: "curl -s -o /dev/null 'http://192.168.1.189/cmd?ledprofilevideo=1'"
command_state: "curl -s 'http://192.168.1.189/ssi/toolpage.ssi' |jq -r 'ledprofilevideo'"
value_template: '{{ value == "1" }}'
so I guess it's an unsolvable mystery.. nothing to debug. just doesn't work. no errors.
Sure you aren't missing a . in your JSON path? jq -r '.ledprofilevideo'"
thanks.. looks like it.. I literallyt would have never noticed that. but it doesn't seem to have fixed the behaviour
got it to work using the dashboard.. but trying to trigger it via switch doesn't work for some reason. even though I've done it the same as all the other switches. that's a seperate problem and not to do with templates though
Well also... are your commands switched or is your template wrong? It'd make me believe from your commands that on is 2 and off is 1, but your template is testing for 1
We went through that. I agree that it's still wrong
{% set text = namespace(list=[]) %}
{% set show_pressure=true %}
{% set color_pressure = "#asdf" %}
{% set test="Hallo" %}
{%- if (show_pressure) -%}
{% set text.list = text.list + ["{ "t": "{{test}}", "c": "{{color_pressure}}" }"] %}
{%- endif -%}
{{text.list |list}}
What is wrong with this syntax?
How can i sho the value of the variables, and not the variables if self?
Remove the {{ and }} around test and color_pressure in this line {% set text.list = text.list + ["{ "t": "{{test}}", "c": "{{color_pressure}}" }"] %}
And remove the quotes before and after the dict
thanks that works
Hi! I have a little problem currently and I'm pretty sure somebody has an idea here how I can solve this 😄
I have a input_number helper with min 5 and max 100. Now I want to increase that value by automation by 10 for example which works fine with that:
data:
value: "{{ states('input_number.wrpower') | int + 10 }}"
target:
entity_id: input_number.wrpower```
UNTIL the new value would go above 100. So if it was at 95 it won't increase to 100. It stays at 95. Any idea how I could solve this?
service: input_number.set_value
data:
value: >-
{% set wrpower = states('input_number.wrpower') | int %}
{{ wrpower + 10 if wrpower <= 90 else wrpower }}
target:
entity_id: input_number.wrpower
should work
Replaced the "else wrpower" with "else 100" and it does then. Thank you very very much! 🙂
You said: So if it was at 95 it won't increase to 100
Ah no. I wasn't clear enough. I wanted it to go to 100 then. 🙂
It tried to go to 105 what of course wasn't working because the maximum value was set to 100. So it was stuck at 95 then. That was my problem 🙂
Then it could just be value: "{{ min(states('input_number.wrpower') | int, 100) }}", either will work
"{{ min(states('input_number.wrpower') | int + 10, 100) }}". Now it does. Looks even cleaner. ty again 🙂
Ah, yeah, right. Np
Hi all - I'm trying to build an automation that depends on the state of a sensor. This is the first time I've tried building an automation that uses a template, and something in my syntax isn't registering well with HA at all. The line that HA doesn't like says is_state('sensor.weatheralerts_1_alert_1_most_recent_active_alert', ['Freeze Warning', 'Severe Thunderstorm Warning'])
When I try to enter that, HA returns with " required key not provided @ data['condition'][0]['value_template']"
What I'm trying to do is test the value of that sensor so I can trigger a scene.
Can you provide the whole automation? I'd imagine your condition isn't surrounded in "s
Hmmm.... there's no actual template there
That's all I have so far. I know. It won't let me save it. 🙂
That line that I referenced above, when I try to build the automation as a "Template condition" is what throws the error.
condition:
- condition: template
value_template: "{{ is_state('sensor.weatheralerts_1_alert_1_most_recent_active_alert', ['Freeze Warning', 'Severe Thunderstorm Warning']) }}"
So in the visual editor, I needed to make sure I added the {{ at the beginning and end... that's where I was screwing this up?
(Trying to learn...)
Well, templates need to be surrounded in {{ and }} that's what makes them a template. I don't know exactly how you got to the point w/ no value_template whatsoever via the UI though
When you add a template condition via the UI, you should see the condition w/ the value_template text box. Just defaults to ""
Gotcha. My very first attempt was in the UI, and that was all kinds of wrong. I wasn't even looking at the right sensor. So, after doing some digging around and (trying) to figure this out with reading, I got to the right sensor and came up with that syntax. Evidently, though, I missed the memo on doing the {{ }} for the template.
Keep in mind, that automation you have w/ the above condition will only ever activate the scene when you start home assistant
I'd like it to be running at all times. Checking constantly for any value in that sensor.
Right, so you should move that to be a trigger instead
Also, while perfectly fine, you don't even need a template to do that, you can use a state condition/trigger
https://www.home-assistant.io/docs/automation/trigger/#state-trigger, you can provide a list under to:
👀
OK, so I've made that change (at least I think I've got it down now....)
Now I'll need to wait until that sensor changes. It's already set to "Freeze Warning" currently, so it's not going to trigger with a "change" trigger. 🙂
I appreciate all of your help.
just for the record, i know some programs will, but home assistant won't let you save an "automation in progress" unless its valid and could be run. so you cant save mid-creating a condition or action
Hi, I need help!
I am new on templates, I am trying to make a template for the fan 3 speeds + off, I copy the example in: https://www.home-assistant.io/integrations/fan.template/
but I am getting an error and do not have a clue what is talking about
Source: components/template/fan.py:393
Integration: Template (documentation, issues)
First occurred: 8:49:08 PM (1 occurrences)
Last logged: 8:49:08 PM
Received invalid percentage: None for entity fan.livingroom_fan```
littleraly I just copy and paste the last example, and only change the name from "preset_mode_fan" to "livingroom_fan"
i am using config template card, and i want to get the device name using device_attr, but error is throw that device_attr is not available, how i get the device name in JS
That example refers to an entity called fan.percentage_fan. Does that entity or an equivalent exist in your setup?
Nop.
My setup is with 433mhz fans , I have to send a code with the rf bdrige with esphome. So, basically I have a button for each spd, that’s why I want to make a template (never did before) and will love to use the tile card for fan.
I still trying ro understand them but is confusing!
That last example fan is for converting a fan that does % speeds (fan.percentage_fan) into one that does preset modes.
Does your fan natively do modes or speed numbers?
If the latter, have a look at the first example instead (helper fan).
Ok, I’ll try 1st
any idea why this wouldn't be working?
The icon isn't changing when the state changes to 'running'
template.yaml
- binary_sensor:
- name: "Dishwasher"
icon: >
{% if is_state("binary_sensor.dishwasher", "running") %}
mdi:dishwasher
{% else %}
mdi:dishwasher-off
{% endif %}
state: "{{ states('sensor.smart_plug_3_current_consumption')|float(0) > 2 }}"
device_class: running
delay_off:
minutes: 10
it seems awfully redundant here to have to do as_datetime here before as_local. is there a better way? {{{{('2023-04-23 23:34:52.973651-02:00')|as_datetime|as_local}}
state is 'on' or 'off' not 'running'
its a binary sensor, running is just the human friendly "translation" of the value
Good morning,
{% if states('light.candeeiro_cozinha') == 'on' %}
#F5C02F
{% elif states('light.lightstrip_kitchen_light') == 'on' %}
'rgba({{ (state_attr('light.lightstrip_kitchen_light', 'rgb_color') |
join(',')) }},0.1)'
{% endif %} ````
that formula works for backgrounds, but I can't seem to make it work on icon_color. What am I doing wrong?
It's a custom:mushroom-template-card
This on the background, works perfectly: {% elif is_state('light.candeeiro_cozinha', 'on') %} background: rgba(245, 192, 47, 0.1); {% endif %} }
Good morning. I'm working on a script to apply standardized logic to all my notifications. I'm trying to figure out if it's possible to template the extended data options for a notification. Something like this:
- service: notify.mobile_app_starfury data_template: title: "{{ input_title }}" message: "{{ input_message }}" data: > {% if input_priority == 'H' %} importance: high {% elif input_priority == 'C' %} ttl: 0 priority: high channel: alarm_stream {% else %} channel: "{{ input_channel }}" {% endif %} tag: "{{ input_tag }}"
What you are doing now for the additional data section won't work
You need to provide it like this:
data: >
{% if input_priority == 'H' %}
{{ { 'importance': 'high' } }}
Okay, think I get it. Was not finding that clearly in the docs. Thanks
Is there a way to pull info from Calendar Events (other than the next event) into templates? I'm trying to replace Garbage Collection with a "Home Maintenance" calendar including two different types of pickup events. I want to be able to template out how many days there are until each of those two events. I think I could do it by creating a separate calendar for each type of event, but I don't really want to do that.
im trying to create a sensor template that monitors the degree of angle of a sensor and then returns results based on that:
{% if states("vibration_sensor.garage_door_angle_z")|int(0) <= 0 %}
Closed
{% else %}
Open
{% endif %}
seems pretty simple yea? the state = -82, so it SHOULD show as closed. well it does if i use <=
BUT then it won't show open when i change to state to say 12
it makes no sense at all.
its driving me crazy
Probably should be {% if states('sensor.vibration_sensor.garage_door_angle_z')|int(0) <= 0 %}
you forgot the domain sensor.
ok, will give that a shot. thanks for the response!
thank you. i was using a 3 year old youtube for instructions. jinga has obviously evolved since then.
Oof, so has Home Assistant, quite a bit. Even things a year old can be risky
Docs are the best place to start
lesson learned. appreciate it!
seemingly unrelated to templates, but this new custom sensor doesn't trigger the icon color to change based on its state like the non-custom sensors. is that expected behavior?
I don't think that will be a valid entity_id as well, with two dots in it
can you help me in my message in fronted
frontend
Ah, right. I didn't see that extra dot in there... can't say I've seen the vibration_sensor domain
No, it was indeed already wrong
Yea that was my naming convention in an attempt to organize... Is there a better practice I should be following?
One that doesn't involve multiple '.' 🙂
Lol. Thanks and will do.
I'm looking to make a pretty complicated template for a fireplace. My skills are very limited and the closest thing I've done to this is create a simple garage door cover template. Anyone care to help me out with this? Will send all the details.
Best to share them here and if someone's able to help, they will
I am attempting to make a dumb fireplace smart. I currently have the fireplace plugged into a smart plug(for energy monitoring) and put a IR blaster inside it to make it smart. I’m wanting to make a device in HA for this that has an on/off switch(a cover that reads the energy monitoring to know if its on and off because the remote command is a toggle), a timer entity(when pressed, turns the fireplace on, and then turns heat on for a set amount of time), A flame color button(sends ir command copied from remote), flame speed button(sends ir command copied from remote), dimmer button(sends ir command copied from remote), speed button(sends ir command copied from remote), high heat button(sends ir command copied from remote), and low heat button(sends ir command copied from remote). I want it to report power, and report low or high heat(by reading energy monitoring).
I have all of the remote codes copied, but have no clue where to start with the templates.
You mentioned cover... any reason you were looking to utilize that over a switch? Would the functions of a cover (tilt/open/close) apply here? Instead, https://www.home-assistant.io/integrations/switch.template/
What I meant by that is, the only similar template I have is a garage door cover. Opens only if another sensor reads that is is closed, and vise versa. The garage door and the fireplace are both momentary.
But if I can do the same thing for this with a switch template, I’ll go that route. How would I get these separate entities into a device?
With the switch itself, that'll just allow you on and off control with the ability to detect state via your plug energy monitoring
I'm assuming the buttons you referred to above are more so #frontend-archived buttons you'll be creating?
I’d prefer the switch and all the buttons to be entity’s of the same device if possible. I have plans for front end remote, but want to finish everything before I start thinking about that.
To my knowledge, you can't go and create completely custom devices... they must be provided by an integration. So if you're wanting to do that, you'd either need to take on creating an integration or working within the confines of an existing one. I think an intermediate option would be to create your own via MQTT, but that'd be outside of the templates realm.
Hmmm, I’ll dive into that a little and see if it’s something I can figure out. Probably will just stick with templates though.
You definitely can make it "look" like a single thing on your dashboard though, even if it isn't a single device
My plans for that is to create a remote. I have it created in photoshop, just need to learn how to get that image into HA as a card and make the buttons control the entities. Thats for another day lol.
TemplateSyntaxError: Encountered unknown tag 'marco'.
this kind of spelling error is going to be the death of me
As a user of the name 'mian' I figure I'm in good company alongside 'marco' and 'defalut' and similar 😆
lmaoo
is there any difference between
- conditions: {{template}}
and
value_template: {{template}}```
other than the fact that one is ui friendly?
you need to add quotes in both, but there is no difference in how they are handled
choose:
- conditions: "{{ template }}"
sequence: []
- conditions:
- condition: template
value_template: "{{ template }}"
sequence: []
- conditions:
- "{{ template }}"
sequence: []
@orchid oxide these are all valid, but if you need multiple conditions the first one will make that hard 🙂
and talking about typos, I generally miss the first i in condition
Hello friends, I'm struggling with this template:
icon_color: >
{{ iif(is_state('light.lightstrip_kitchen_light','on'), "'#%02x%02x%02x' %
state_attr('light.lightstrip_kitchen_light','rgb_color')", 'grey') }}
Images for context: https://imgur.com/a/TnOnC5c - Also screenshots of the states. That sometimes are BRIGHTNESS and not RBG_COLOR.
I have success making the background follow the RGB with this:
background: rgba({{ (state_attr('light.lightstrip_kitchen_light', 'rgb_color') | join(',')) }},0.1)
{% elif is_state('light.candeeiro_cozinha', 'on') %}
background: rgba(245, 192, 47, 0.1);
{% endif %}```
It shows the "grey" properly, but the moment the lightstrip is on, it'll break (and show that black color thing). Both on Brightness and RBG.
What am I screwing up?
you are using double quotes around the true statement of the iif
so that will alwasys be the string '#%02x%02x%02x' % state_attr('light.lightstrip_kitchen_light','rgb_color')
which will not be a valid input for icon_color
I don't think I understand what you mean 😓
Okay, I figured this works:
{{ '#%02x%02x%02x' % state_attr('light.lightstrip_kitchen_light',
'rgb_color') if states('light.lightstrip_kitchen_light') == 'on' else
'disabled' }}```
But if the color isn't really RGB, and is doing a "brightness" only color, it still shows the "broken black".
Can you help me fixing that?
I don't know which state I should look for tho, would brightness work?
Or even, show a SOLID COLOR, if the lightstrip isn't on rgb_mode, is that possible?
I'm a bit stuck. The templates renders correctly when testing it in dev tools giving me a *true * result, but when executing a script and using it as a condition with *choose *it results to *false *and skips the sequence. Any help will be appreciated.```
- choose:
- conditions:
- condition: template
value_template: "{{ (((now() | as_timestamp ) - (state_attr('automation.test_automation_1', 'last_triggered') | as_timestamp)) | int) > 240 }}"
I have also tried, the following, but with the same result.```
{{ (as_timestamp(strptime(states.sensor.date_time.state, '%Y-%m-%d, %H:%M')) - as_timestamp(state_attr('automation.test_automation_1', 'last_triggered'))) > 240 }}
I'm not sure what you expect from this '#%02x%02x%02x' % state_attr('light.lightstrip_kitchen_light', 'rgb_color')
is that a choose in automation.test_automation_1?
That creates the hexadecimal code for the RGB color. I actually don't know hahaha but on the forums people used that and it ended up working with some tweaks.
yes
I think I see what you are getting at...
test it in developer tools > template. you will be doings something lik '#%02x%02x%02x' % [ 0, 0, 255] which will give an error
The issue now, is it possible to add something that would also use the brightness when there's no RGB color? It's a yeelight lightstrip and sometimes the color doesn't have RGB-Color in the states.
use this.attributes.last_triggered instead, that will be the previous trigger
Its not giving an error anymore. That part is working. I just need to also make it so it checks if there's no RGB it gets another color. And a {else} isn't enough.
Worked perfectly - The previous syntax used to work, have it on a few automations, did something change that I missed?
remove the else completely, or use else 'grey'
it works if you use it in the condition part, because the automation is considered triggered if that part passes
but if you use it in a choose, you are in the action part, so it has been triggered
Ah, that will make sense, I have only used it there in the past, first time using it in under actions. Appreciate the explanation.
hi all, I'm trying to make a binary sensor from a cover. The cover sensor has 2 true states, 'open' and 'opening' but when I try to capture 'opening' it does not like it. How can I capture both states as true?
{{ is_state('cover.overhead_garage_door_controller', 'open', 'opening') }}
there is also closed and closing which would be false
{{ is_state('cover.overhead_garage_door_controller', ['open', 'opening']) }}
thank you sir!
are you sure you don't want it to be true while it's closing? Technically it is still open then 🙂
why didn't you just try instead of asking?
you already knew the symbol
you didn't even need to ask chatgpt as it probably has no clue either
Of course Jinja has a frobnication operator
Hello! Guys is possible to apply operator to state_filter ? I am only able to set matching value to sensor, i want to ad operator such “>=“ or “<“
entity: sensor.0x00158d0002c4ccb9_device_temperature
state_filter:
">28": brightness(50%)```
You can use {{ not is_state('cover.overhead_garage_door_controller', 'closed') }} then
Is this like a way to save cpu? Use the inverse?
Since it's only checking one state as opposed to 3?
How do I put "last-changed" on the secondary information of a Mushroom Template Card?
did you provide an entity: in the config of the card? And how do you expect it to be displayed?
if the answer of the first question is yes, you can use {{ states[entity].last_changed }} to get it as a datetime string
Yes I did . Getting closer. It provided me a format of "2023-04-24 14:55:40.059324+00:". I was expecting two hours ago. Any ideas?
and {{ relative_time(states[entity].last_changed) }} to get that
Thanks, TheFes!!! You rock. Been goofing with that for an hour!
is there a way to get the current temperature from a climate entity using a sensor?
most probably yes
how do i do that
ive been looking at community posts and the template docs for about 20 mins and my brain cant comprehend that
I'm not sure what you mean with using a sensor though
i want a graph to show the current temperature returned by my aqara thermostat
you want to create a template sensor with the current temperature of the climate enitty as it's state?
and i cant just use the climate entity for the input of the graph
okay, I assume it is in an attribute (I don't have climate entities in my setup). Can you check in developer tools > states what that attribute is?
its current_temperature
and what is the entity id of your climate entity?
climate.hkt_zone_1
template:
- sensor:
- unique_id: current_temp_climate_hkt_zone_1
name: Current temperature HKT Zone
state: "{{ state_attr('climate.hkt_zone_1', 'current_temperature') }}"
device_class: temperature
unit_of_measurement: "°C" # or "°F"
state_class: measurement
put that in your configuration.yaml
unless you are already using the template: integration
thank you very much, ill try it
if this is your first template entity, you need to restart HA, otherwise you can reload template entities in developer tools > YAML
Okay thanks again!'
there was a typo in the entity_id of the state template
is the unique id linked to anything in any way or can you freely change it?
you can freely change it, I usually use randomly genereated UUID's
cool cool
it's not used for the name or entity_id
the name is converted to the entity_id
but by adding a unique_id you can change the name and entity_id in the GUI, among other settings
ah
forgot to thank you 👍 works flawlessly
What's the correct syntax that allows me to use the state of input_number.hvac_ds_cool_away like so?:
{"hvac_mode": "heat_cool", "target_temp_high": states('input_number.hvac_ds_cool_away'), "target_temp_low": 68 }
@grand robin I converted your message into a file since it's above 15 lines :+1:
ChatGPT beat y'all to the punch this time 😉
Im having issues making a separate temp sensor to convert C to F. I think I have to make a template but I am not sure. I put the following in a the config.yaml but im still not seeing the new sensor. is there something else I need to do??
Loads default set of integrations. Do not remove.
default_config:
Load frontend themes from the themes folder
frontend:
themes: !include_dir_merge_named themes
Text to speech
tts:
- platform: google_translate
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml
sensor:
- platform: template
sensors:
sonof_temp_f:
unique_id: "Sonsof temp f"
friendly_name: "sonsof temp f"
unit_of_measurement: '°F'
value_template: >-
{% set t = states('sensor.1000574c0e_t') | float %}
{{((t)*9/5)+32}}
FYI the templete works in the template checker
Put it on a new line
value_template: >-
{% set t = states('sensor.1000574c0e_t') | float %}{{((t)*9/5)+32}}
would the matter if the syntax works in the template cheacker
it is on another line, I guess it didnt paste correcty
sensor:
- platform: template
sensors:
sonof_temp_f:
unique_id: "Sonsof temp f"
friendly_name: "sonsof temp f"
unit_of_measurement: '°F'
value_template: >-
{% set t = states('sensor.1000385c0e_t') | float %}
{{((t)*9/5)+32}}
thats from studio code
There's no line break there...
Please format your code
lol nm it didnt copy corrtly, wish i could just use a screen shot
No, just share it properly
That gets you what you provided above
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
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.
i guess i dont know what message share is
it was my broken attempt to do that on my phone
sensor:
- platform: template
sensors:
sonof_temp_f:
unique_id: "Sonsof temp f"
friendly_name: "sonsof temp f"
unit_of_measurement: '°F'
value_template: >-
{% set t = states('sensor.1000385c0e_t') | float %}
{{((t)*9/5)+32}}
ahh
gack
i used the dpaste site
i guess im not getting how to copy it over from dpate
make a new snippet on dpaste, share the link
sometimes I miss Gitter lol
heres the entire config https://dpaste.org/kfiON
Did you reload after updating ?
lol not sure, I did a core reload and also restarted HA
HA restart would cover it for sure... there's no sensor.sonof_temp_f is what you're saying? Or there's an error in your log?
yes no sensor
and in the template tester output I get sensor:
-
platform: template
sensors:
sonof_temp_f:
unique_id: "Sonsof temp f"
friendly_name: "sonsof temp f"
unit_of_measurement: '°F'
value_template: >-87.08000000000001
so it should be correct as its getting a temp value and seems to be correctly converting it
I'd check your log to be certain... but that config looks fine
You're certain you restarted after saving your config?
lol now that I looked at it again, now I can see the sensor. thanks
I'm in need of a automation condition where I check a precipitation sensor if there was a certain amount of rainfall, anybody know a easy way to achieve this?
you mean in the past?
yes
how far in the past?
https://imgur.com/a/ESflaqy
should be true on > 0,5l in the last 24h
you can use an sql sensor to get the last 24hr of data out of the database
but I'm not an SQL query expert, so I can't help you with that
so alternative is a boolean which gets reset every 24h then ?
too bad, I thought there is something new where one can check "min/max/avg" over x time
Hello - how can i add 0.025 to my resultant state in this code? (I.e. after the * 1.21. I tried to just add (+ 0.254) but it didn't work..... many thanks,
- sensor: - name: epex_spot_price_ct_per_kWh_with_vat unit_of_measurement: "€/kWh" availability: '{{ states("sensor.epex_spot_nl_price") != "unavailable" }}' state: '{{ states("sensor.epex_spot_nl_price") | float / 10 * 1.21 }}' unique_id: "my_unique_id_epex_spot_price_ct_per_kWh_with_vat"
it's just normal order of operations
"float" is not a number
this is just basic math
corrected 🙂
state: '{{ (states("sensor.epex_spot_nl_price") | float / 10 * 1.21) + 0.025 }}'
ahh, yes, that makes more sense. The whole thing has to be brought into the bracket
thank you. works now!
chatgpt is perfect for summarizing what old templates do so i dont have to parse my own chicken scratch to remember lmao
#frontend-archived is the right place for JavaScript. This channel is for jinja templates
noted
Does anyone know why my result of this template gives me +1 month than what the helper is? If helper is set to 26 April the result of this template gives me 26 May.. And if I add -1 in the sensor it only works if the month in the helper is in this month.. If I set the helper to be 26 May the result of the sensor will be 26 April..
{% set months = ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"] %}
{% if now().date() < input.date() %}
{{ input.strftime('%d ') + months[now().month] }}
{% endif %} ```
The if statement is meant to show a date if the date hasn't passed yet
Sorry,
After update lastest ver of HASS.
I can not play music on local .
With error:
homeassistant.components.cast.media_player
['Failed to cast media https://khaisilk1910.duckdns.org:8123/local/media/children/Con Heo Dat.mp3?authSig=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiIwMjBjYjIxYThjNGY0NmM3OTk4ZmY1ZjE1ZWNjNmE5MSIsInBhdGgiOiIvbG9jYWwvbWVkaWEvY2hpbGRyZW4vQ29uIEhlbyBEYXQubXAzIiwicGFyYW1zIjpbXSwiaWF0IjoxNjgyNDk3MDk0LCJleHAiOjE2ODI1ODM0OTR9.btepsrdwMYu73KDjnNK07IoahCIvk59esZ5NiiBeDyc from external_url (https://khaisilk1910.duckdns.org:8123/). Please make sure the URL is: Reachable from the cast device and either a publicly resolvable hostname or an IP address']
Can someone help to me
alias: Play Music At Morning
sequence:
- service: media_player.play_media
data_template:
media_content_type: audio
media_content_id: >-
media-source://media_source/local{{state_attr('sensor.children','file_list')|random}}
entity_id: media_player.phong_ng_speaker
mode: single
icon: mdi:playlist-music
This is a template question, is there anyway to template my venetian blind so that if 0-30% state is considered closed, 30-70% state is considered open and 70% to 100% state is considered closed? the state_attr is current_tilt_position: 53
Yes
@thorny snow I converted your message into a file since it's above 15 lines :+1:
Hello - is it possible to manipulate sensor data which is used in a chart (as it has attributes) to add my VAT (21%) and some additional cost (2.54 euro cents)?
So, for example - with one sensor, I am able to add VAT and additional costs like this:
- sensor: - name: epex_spot_price_ct_per_kWh_with_vat unit_of_measurement: "€/kWh" availability: '{{ states("sensor.epex_spot_nl_price") != "unavailable" }}' state: '{{ (states("sensor.epex_spot_nl_price") | float / 10 * 1.21 + 2.54)/100 }}' #add vat and extra costs, then into 0.00 cents that can be understood by threshold input unique_id: "my_unique_id_epex_spot_price_ct_per_kWh_with_vat"
However - this sensor (sensor.nl_energy_prices_average_electricity_price_today) is where my chart data is - and I'd quite like to add VAT and additional costs (like above) to each attribute for the hour in this sensor. - therefore so each bar int he chart is correct.
You can see a screenshot of the attributes here: https://ibb.co/z60cfHY
And the code for the chart, which uses the sensor is here: https://wtools.io/paste-code
The end result I would like is a chart that includes the original data but with VAT added (21%) and 2.54 euro cents.
thanks!
@vernal pawn I converted your message into a file since it's above 15 lines :+1:
Huh? ok, I did not expect that to happen.
Ok again:
Hmm, something weird which I hope you can help me with.
I want to get a timer working on the Ulanzi Pixel clock and therefore I need the time to be updated every second. I try to do this with the below template. The resulting time display however is always 1 hour above the actual remaining time.
{% set duration = 7200 %}
{{ duration }}
{% set end_time = as_timestamp(now()) + duration %}
{{ end_time | timestamp_local }}
{{ now() }}
{% set remaining = end_time - as_timestamp(now()) %}
{{ remaining | timestamp_custom('%H:%M:%S')}}
results in:
7200
2023-04-26T16:35:00.308053+02:00
2023-04-26 14:35:00.308112+02:00
02:59:59
As you can see remaining is one hour up on the duration of 2 hours, while the end_time and now() are exactly 2 hours apart.
What's going on and how can I fix this?
No, i do not want to use the timer function of Home Assistant. That only works with a set time. I want to define the duration of the time based on a calendar item.
remaining isn't a timestamp any more and that's what you're formatting at the end
{% set duration = timedelta(hours=2) %}
{{ duration }}
{% set end_time = now() + duration %}
{{ end_time }}
{{ now() }}
{% set remaining = end_time - now() %}
{{ remaining }}
Depends on what you want to do w/ it
But there remaining will be a timedelta object
I want to calculate the time of a calendar item by doing something like:
{% set duration = as_timestamp(state_attr('calendar.robin', 'end_time')) - as_timestamp(state_attr('calendar.robin', 'start_time')) %}
timestamp_custom assumes a local time
when you use a timestamp integer/float with timestamp_custom, you must supply the timezone, otherwise it will be off by your timezone
otherwise use what NSX said, which is a timedelta object
With that time difference (of lets say 30 minutes) i want to set a timer of 30 minutes, which is started by the press of a button. So the end time is not the end time of the calendar item.
Just use the library I created
Er, well, It can't do time differences between things yet. So nevermind
Hmm thanks.
This seems way more complicated than I thought.
Too bad the timer helper of Home Assistant only has the option to set a fixed default value which cannot be updated. That would be ideal.
Cannot be updated? https://www.home-assistant.io/integrations/timer/#service-timerstart
If a new duration is provided, this will be the new default for the timer until Home Assistant is restarted (which loads your default values).
Ah!
It was a bit hidden to me. Thanks!
I came up with another solution which might have worked. The duration was in seconds, so a timedelta could be set with seconds.
Too bad the remaining attribute doesn't seem to update that often. It stays on the duration time, while the timer is running down.
A well found this solution:
{% set remaining = state_attr('timer.robin', 'finishes_at') | as_datetime | as_local - now() %}
{{ (remaining|string)[:-7] }}
This results in something like: 0:09:54 and is what I need.
Thanks for the help 🙂
Add false to the timestamp_custom filter to remove the additional hour
But this will only update once per minute
If i want to store a JSON Message in a text helper, is there an easy way to add/remove/update specific fields using templates?
I'm trying to see if i can get away with less helpers and more complex templates
For example i can sort of reconstruct a json with:
{% for key in (states('input_text.scene_controller') | from_json | list ) -%}
{'{{key}}': {{(states('input_text.scene_controller') | from_json )[key]}}}
{% endfor %}
{% set j = {"Basement Remote":1, "kids_remote": -1} %}
{% set update_value = dict({'Basement Remote':2}) %}
Inital Dictionary: {{j}}
Update packet: {{update_value}}
Merged: {{ dict(j, **update_value)}}
That kind of worked...
{%- macro remove_field(json_data, field) -%}
{{ dict( json_data.items() | rejectattr('0','eq',field) | list ) }}
{%- endmacro -%}
{%- macro update_or_add_field(json_data, field, value) -%}
{{ dict(json_data.items() | rejectattr('0','eq',field) | list, **dict({field:value})) }}
{%- endmacro -%} #}
Your macros are alittle verbose and have a few redundancies. Also, you can make use of kwargs
{%- macro update(data) %}
{{ dict(data.item() | rejectattr('0', 'in', kwargs.keys() | list) | list, **kwargs) | to_json }}
{%- endmacro %}
use
{{ update(data, x=1, y=2) | from_json }}
that's if you're replacing
binary_sensor:
- platform: template
sensors:
wouter_iphone_home:
value_template: >-
{% if states('sensor.wouters_iphone_ssid') == "WWWiFi" %}
home
{% else %}
not_home
{% endif %}
friendly_name: "Wouter's iPhone Home"```
is there anything wrong with this? because despite my SSID changing, the sensor stays the same.
Yes, it's a binary_sensor and they can only be on or off
You're trying to assign home and not_home
hm, okay, apparently that used to work based on the article I copy/pasted it from
Meh, it's just wrong
binary_sensor:
- platform: template
sensors:
wouter_iphone_home:
value_template: >-
{% if states('sensor.wouters_iphone_ssid') == "WWWiFi" %}
on
{% else %}
off
{% endif %}
friendly_name: "Wouter's iPhone Home"
so this will work?
So, that's a sensor
or is there a way to make it work with home/not_home? similar to the usual presence detection?
I have 10 of the same type of sensor, I want to create template sensors that run a calculation on each sensor with different offsets variables in order to well calibrate it. Is there a way to have a reusable function i can call for each template sensor so when i modify it, it affects all the sensor instances?
Not sure if this is even possible. Currently when my mic active sensor becomes active it turns on a light then off when mic sensor is off. I have it start a timer helper which counts down from 10 minutes. Firstly would love to express the time remaining as a percentage. Unsure on where to even start?? Next if the call runs over from the 10 minutes how can I determine call time? Is there a way to start a counter at the beginning to “log” the whole time?
Yes, macros
Is there a quicker/better way to access values that may not exist (unavailable) than
(states('sensor.pv_power')|float|round(1) if has_value('sensor.pv_power') else 0.0)
?
Just use | float(0) to let it default to 0
Ah I didn't spot it had an arg, thanks
@thorny snow I converted your message into a file since it's above 15 lines :+1:
Is this even possible
@thorny snow
- trigger:
- platform: time_pattern
minutes: '/1'
- platform: state
entity_id:
- sensor.charger_power
attribute: charger_amps_actual
sensor:
- name: template_ev_consumption_home
state: >-
{% if trigger.platform == 'state' %}
{{ trigger.to_state.attributes.charger_amps_actual }}
{% else %}
{{ states('sensor.template_totalexcesssolarforcharging') | float(0) * 24 / 100 }}
{% endif %}
unit_of_measurement: kW
device_class: power
keep in mind, if you want the charger_amps_actual as the output, the code will change the 2nd line to
{{ trigger.to_state.attributes.charger_amps_actual }}
I dont think the if statement is evaluating correctly
{{trigger.to_state.attributes.charger_amps_actual }}
{% else %}
{{(states('sensor.template_totalexcesssolarforcharging') | float(0) * 24/100 ) }}
{% endif %}```
If I paste this in the template tool it errors with 'UndefinedError: 'trigger' is undefined'
Do the trigger entities work for a template sensor?
There are no trigger events in the template editor. Trigger events only occur in automations, where the template will work as expected.
You can't test this in the template editor
You can just Copy/paste what I wrote and it'll work out of the box.
guys, could I make a template that triggers an automation with a logic similar to this? When the state of a sensor is under a value trigger the automation once and when the state of a sensor is over a value trigger the automation based on a time pattern (like /5)
@lofty mason I converted your message into a file since it's above 15 lines :+1:
I pasted a solution but the bot chomped it, see above and see if that works for you.
Thank you! Need some time to process this 🙂
basically use triggers to trigger any time number falls below and every five minutes, and then use conditions to carve out the triggers you didn't want.
That is the way
Thank you both! I've implemented this - will have to test it in time to see how it works 🙂
Hi, how can I cover the whole subnet 10.10.10.0/24 in the following template
{{ state_attr('persistent_notification.http_login','message').split('(')[1].split(')')[0] != '10.10.10.30' }}
Use [0][:-3] != '10.10.10'
Thanks, unfortunately it didn't work:
{{ state_attr('persistent_notification.http_login','message').split('(')[1].split(')')[0][:-3] != '10.10.10' }}
just forgot the '.' in the end. it needs to be
[0][:-3] != '10.10.10.'
Thanks a lot for your help.
Thanks.
But this is part of a template sensor, not an automation. It isnt clear to me if the trigger entities are available in a template sensor.
they are
as long as you're actually loading the template sensor and letting it trigger, rather than just sticking the template itself into the template dev tool
Q: With this new found template power, is there a way to create a custom filter to use in a template? I have a simple python function I need to use in a filter
import struct
def float_2_ieee(f):
binary_string = ''.join(f'{b:08b}' for b in struct.pack('>f', f))
return hex(int(binary_string, 2))
Unfortunately not
You can't create filters at all
The only new capability is to make Jinja declarations global
the fact that if you dont format templates it auto fomrats them like this {{((area_entities('Living Room')|select('match', 'lock'))|list, (area_entities('Living Room')|select('match', 'switch')|list))|reject('search', 'bun_cam_v2_notifications')|reject('search', 'bun_cam_v2_motion')|list}} drives me insane
cause naturally 'Living Room' and 'Living Room'
are not the same thing
Don't use the GUI for automations, scripts and dashboard creation 😜
i like the immediate feedback 😦
Well, that's what causes the reformatting of the templates.
If you use YAML only, it will stay exactly as you wrote it
- name: "pE"
unique_id: pe
state: >
{{(((states('sensor.eth_hourly') | float(0) / 1000) / 3600) * 1000) | round(7)}}
unit_of_measurement: "m/s"
Any ideia, of how to make this calculation happen hourly? Without an automation, I mean...
Use a trigger
But that would need an automation, right? As in:
trigger:
- platform: time_pattern
minutes: '/60'
no, templates accept triggers
hello, if I have this
mqtt: sensor: - name: "Battery_SOC_Imeon_1" state_topic: "imeon_1/battery_SOC" unit_of_measurement: "%"
is there any way I can add a tag to this? I would like to filter later on based on tags. Would like a tag like "imeon_1"
Hi, I have a current meter, which returns sensor values for all three phases (L1,L2,L3). Those are differentiate by the entity-id being sensor_a_voltage, sensor_b_voltage, etc. same goes for other units. If I want to write a template to show all of them, I can use {{ states("sensor_a_voltage") }} but how can I loop throw all three sensors replacing the id by a, b and c?
when using the IMAP sensor to scan subject in the email how do you scan for partial text instead of the entire subject has to be perfect.. if i have subject "Fedex <track number>: Your Package Is On The Way" but i only wanna search for "On The Way" but i cant get it do it.. it only works if the entire subject line is correct and only want to search part of it
{% elif 'out for delivery today' in subject %}
thats what i have out of the email subject.. the subject is
FedEx Shipment 00000000: Your package is now out for delivery today
'out for delivery today' in subject should work fine unless subject is not a string
what i get is blank for the sensor.... but if i click on the sensor and click attribute the email is in there
if the full string works, but partials do not, that indicates subject is not a string but a list
Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
or just share the text if it's code.
please copy/paste the attributes from developer tools -> states page
@queen perch I converted your message into a file since it's above 15 lines :+1:
only pasted some of it unless you want the entire thing
@queen perch I converted your message into a file since it's above 15 lines :+1:
so far the first 3 dont work either cuz i copy and pasted it from my Intelcom delivery so i tweaking it for fedex
so instead of making the sensor say on_the_way it makes the sensor blank as you see in the pic
and it works for my intelcom delivery.. but that one i use the entire subject line so its exact.. as it doesnt use a tracking number but when i try to search part of the subject line thats when it doesnt wanna work
so i figured maybe its like a windows search? you gotta do like *out for delivery then it searchs for the star
just output the subject as the state of that sensor to see if it's a list please
it's literally only going to be that
not sure whaty a mean or how do that
unless there's special characters in the subject, even then searching for a single character would work or single work
make your value_template: "{{ subject }}"
so erase the >-
you can make it
value_template: >
{{ subject }}
too if you want
then paste the state here please
post what you tried again
value_template: { { subject } }
#>-
# {% if 'Your package has been received!' in subject %}
## received
# {% elif 'Your package has been delivered!' in subject %}
# delivered
# {% elif 'Your order has been delivered!' in subject %}
# delivered
# {% elif 'out for delivery today' in subject %}
# on_the_way
# {% endif %}
yeah, that's not what I wrote
thats what studio code changed it to
value_template: "{{ subject }}"
or
value_template: >
{{ subject }}
literally just copy/paste what I wrote
don't try to write it yourself if you don't understand templating
neither work
you're doing something wrong. Here, I'll write the whole thing out...
end of stream pr a document seperator is expected
Yes cause you're not honoring yaml or jinja
i just copied what you wrote
#######################################
### FedEx Deliveries Template ###
#######################################
- platform: imap_email_content
server: outlook.office365.com
name: FedEx Delivery
port: 993
username: @@@@@@@@@@@@@
password: @@@@@@@@@@@@@
senders:
- TrackingUpdates@fedex.com
value_template: "{{ subject }}"
well, ya did it wrong 🤷♂️
nope
I'm not sure what to tell you. There isn't much to this
it's a single template
there's only so many rules
what you posted above violated yaml rules
\https://imgur.com/a/wr5VCOS
i just copied what you wrote
no you didn't
i did
No, you literally removed 2 fucking spaces
Right, but where was value_template before?
was it indented by 2 spaces?
is it indented by 2 spaces on the full thing I just posted?
k i spaced it
ok, so paste the state here please
FedEx Shipment 0000000000: Your package is now out for delivery today
i replaced the number with 0's
Ok, this is working in the template editor w/o issues
{{ 'out for delivery today' in 'FedEx Shipment 0000000000: Your package is now out for delivery today' }}
so there's no special characters and it's not a list
so your original code should work whenever the imap sensor updates
ya its just leaving it blank. i have a automation to set it say "unknown" on boot up of home assistant. so the sensor has something but as soon as the email comes in the state goes blank wont put in "on_the_way"
as you seen in the orginal pics
ill re add the if statesments and do a full home assistant restart maybe that help?
probably not, the code is fine including your yaml & spacing so it should just be working.
ah ok i did it anyways.. so be 5 min or so before it comes back up sometimes 10 min... would clearing the cache work? like when home assistant reboots in my automation it sets it to unknown so i know that part is working then not too long it flips it to blank and and then i can see the email in the attribute
No clearing cache only fixes frontend issues.
so i tried full subject line didnt work.. i looked in the logs i get this error.. maybe its the issue dunno how to fix that? ```Logger: homeassistant.components.recorder.db_schema
Source: components/recorder/db_schema.py:585
Integration: Recorder (documentation, issues)
First occurred: 12:42:46 PM (4 occurrences)
Last logged: 12:42:49 PM
State attributes for sensor.fedex_delivery exceed maximum size of 16384 bytes. This can cause database performance issues; Attributes will not be stored```
is that because of the body of the email is large?
that's telling you it's not going to store the attributes in the database
so would that possibly reason why its not storing it then why i get blank? and is there a way to not load the body of the email in the imap sensor
i dunno i just asking as i have no idea
cant post the entire attribute either discotrd says like -4200 lines or so
You don't need the whole attributes, all you care about is the subject
and your code for the subject is good aside from not having an else case
well if have the elseif's but doesnt seem to be working
which is why you're getting a blank result, but that doesn't explain why 'xxx' in subject is not working yet the full string does. Either you're unknowingly lying about the full string working or something else is going on. You've output the subject directly in the state and that gave you a subject without list indicators. Therefor 'xxx' in subject should work every time. I don't use that integration, so I can't comment on it's behavior.
@queen perch I converted your message into a file since it's above 15 lines :+1:
and thats ok i appreciate the help so far..
and ya it says canada post i made it for canada post too... but they all the same
so i thinking its like that database overflow issue but i just guessing..
guess ill play with it later..
Trying to get a home built GPS sensor to send Latitude/longitude data to HA through MQTT. The sensor publishes to a topic called "car/gps/attributes" a string that looks like {"latitude":-50.34724,"longitude":199.21634} and I'm using the following in configuration.yaml to try to get the sensor into HA:
mqtt:
device_tracker:
- unique_id: car_mqtt_gps
name: "Car GPS Sensor"
state_topic: "car/gps/state"
json_attributes_topic: "car/gps/attributes"
json_attributes_template: "{{ value_json.latitude }}, {{ value_json.longitude }}"
The sensor is found by HA and shows as an entity under MQTT. The sensors state changes with the "car/gps/state" topic but I'm not getting the lon/lat data anywhere, at least no where I can find, and the entity wont show on a map card.
I'm sure I'm making a really dumb mistake but I can;t work out what it is, any help would be great....
I suggest removing the json_attributes_template line entirely as the content is already a JSON dict
You're not generating proper json there, so I'm sure it's confused
Man, I both hate and love when this happens. Love it b/c my sensor is now working and it only took one quick question, one simple answer and 5 mins.... Hate it b/c I always feel so dumb for not thinking of trying that myself...
Thanks for the help, I'm smiling again....
is this correct ? i want to add a binary sensor for quick automation trigger
name: "Nobody home"
state: {{states('zone.home') | float(default=0) == 0 }}```
You're missing a -
And you need to surround your template in quotes
And you need to nest the whole thing under template:
But that sensor is unnecessary if all you want to do is trigger on an empty zone. Just use a state or numeric_state trigger
is there a check for Visual code, i always miss small quote
i mean extension for visual code that does checking for quote?
For quote?
yes
I don't think it will catch not surrounding the template in quotes
Otherwise I don't know what you mean by 'for quote'
for information i just adapt this line from forum https://community.home-assistant.io/t/entity-state-to-binary/439898/7?u=rayte
so i wonder why not working
The things I said above
I have 2 wait for triggers 1 after another. If the second one times out and continues on timeout. I am unable to avoid the error when wait.trigger none from the second wait for trigger.
second_wait_to_state: "{{ iif(wait.trigger != none,wait.trigger.to_state.state,'null') }}"
UndefinedError: 'None' has no attribute 'to_state'
An iif always renders both the true and false statement
Don't use it if the false statement can generate errors
How would you recommend getting around this? I guess using ```py
{% if wait.trigger is not none %} {{ wait.trigger.to_state.state }}
{% endif %}
To replicate what you had:
{{ wait.trigger.to_state.state if wait.trigger is not none else 'null' }}
Which will give the string 'null' if the wait trigger is none
That's cleaner thank you.
Does wait for trigger not accept templates in the entity_id field?
- wait_for_trigger:
- platform: state
entity_id: "{{ room_lights | reject('eq',first_wait_entity_id) | list }}"
continue_on_timeout: true
I would rather use wait for trigger vs wait for template to get the to_state without having to get complex with wait for template.
Ignore my spacing
your yaml isn't spaced properly
it's all over the place
Well I know it's because I'm on mobile and pasting from a code editor but spacing isn't the issue it doesn't like a template it appears.
yeah but if you're posting code from the editor entity_id and platform would be aligned at least
literally every row is messed up
But in regards to templating entity_id for triggers, that's also not possible. The only thing that can be templated in triggers are template triggers
Message malformed: Entity {{ room_lights | reject('eq' is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']
I attempted to align them and failed lol
- wait_for_trigger:
- platform: state
entity_id: "{{ room_lights | reject('eq',first_wait_entity_id) | list }}"
continue_on_timeout: true
There you go lol those 2 are aligned.
see this
Yeah I figured it's not allowed just wanted to be sure. I have another idea for handling this.