#templates-archived
1 messages · Page 145 of 1
I see
- platform: template sensors: vapor_deficit: friendly_name: 'vpd in kilo pascals' value_template: >- {% set T = states('sensor.itc_308_temperature')|float %} {% set RH = states('sensor.ihc_200_humidity')|float %} {% set SVP = 0.61078 * e ** (17.2694 * T / (T + 238.3)) %} {% set VPD = ((100-RH) / 100) * SVP %} {{-VPD | round(2) -}} unit_of_measurement: 'kPa'
It works but sometime trigger a lot of this error and make spikes in Grafana graphs:
Template warning: 'float' got invalid input 'unavailable' when rendering template '{% set T = states('sensor.itc_308_temperature')|float %} {% set RH = states('sensor.ihc_200_humidity')|float %} {% set SVP = 0.61078 * e ** (17.2694 * T / (T + 238.3)) %} {% set VPD = ((100-RH) / 100) * SVP %} {{-VPD | round(2) -}}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1
Is there something I can do to avoid this error? Am I in correct channel for possible help on this? Thank you!
Either provide a default when you use |float or use an availability template
I see, thank you!
The dev tools show a "last changed" timestamp, is that an attribute we can somehow read?
attribute, property, same same? 😄 thanks
so I guess that's why I can't use it with state_attr? the entity has leading zeros in it's id, so states.sensor.000e9be993a473.last_changed is not recogniced
However, {{ state_attr("sensor.000e9be993a473", "last_changed") }} returns "None"
Because it’s not an attribute
You have to use [‘00e9….’]
some other guy doing the exact same thing
Evening all, did anyone have any thoughts on this post i did last night. I really struggle with this kind of subject #templates-archived message
omg, so close, only half a page up in here 😅
weird, states.sensor['000e9be993a473'].last_changed seems to be an empty string (not None)
because states.sensor['000e9be993a473'] is None
then you have the entity_id wrong
Isn't what I can enter in the "states" screen the entity id?
according to the entity list, the id is "climate.000393c994df54" so there is even a dot in the id 😆
how can I use time templates , to increase the minutes of a time set in an input_datetime by an 'X' amount ?
I 've been pulling my hair trying to figure it out - tried to go a different way by using jinja2 and increasing individual values for hours , minutes while trying to set them using input_datetime.set service but I ended up hitting dead ends having to do too many number and string manipulations to get it right.
So I am falling back to what seems to be the correct approach ... the time templates. But I am not sure if/how they can serve my purpose.
Something like this?
{{ states('input_datetime.something') | as_datetime + timedelta(hours=3, minutes=25) }}```
That will return a datetime which you can use for input_datetime.set
let me try this looks promising
And you were trying to reference sensor.000e9be993a473
so...states.climate['000e9be993a473'].last_changed
I went to the documentation to understand it first of all (as I'm not familiar with templates very much). So first things first thank you for that. I see what you did , and it should be working , however there seems to be some weird type incompatibility that I cannot explain.
{{ states('input_datetime.vacuum_scheduler_weekdays') | as_datetime + timedelta(hours=3, minutes=25) }}
TypeError: unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta'
I also tried going as_datetime( ... ) and putting the states() argument as a parameter inside ... same thing
I mean I don't get it , you are 100% correct. The state of the datetime entity is indeed a string ... and the as_datetime is supposed to get a UNIX formated time string and turn it to something that the timedelta in turn should be able to alter
but the machines have a different opinion 😛
What does {{ states('input_datetime.vacuum_scheduler_weekdays') }} return when you put it in
> templates
Hi, i need some help (:
When jusing:
{{ (as_local(states.switch.switcher_boiler_34b0.last_updated)) }}
I'm getting:
2021-12-31 07:30:00.762222+02:00
I'm trying to get rid of the seconds, miliseconds and +02:00 text so it will only say:
2021-12-31 07:30
But nothing seem to work for some reason...
i tried using
strptime and as_timestamp but i can't get it to output the text i want.
Any ideas?
Try this: {{ as_datetime("2021-12-31 07:30:00.762222+02:00").strftime("%Y-%m-%d %H:%M") }}
I'm getting this error:
TypeError: float() argument must be a string or a number, not 'datetime.datetime'
So it's a float for some reason
OK, this works:
{{as_timestamp(as_local(states.switch.switcher_boiler_34b0.last_updated)) | timestamp_custom('%H:%M %d/%m/%y')}}
Thank you!
np. glad you found it! 🙂
So i'm trying to have a script that tells me how long was my boiler running last time.
What i thought about doing is retrieving the last time boiler state was changed minute the last --> last time boiler had changed.
So basically it will be when boiler changed to off MINUTE when boiler changed to on = the amount of time it ran.
But i don't think there's a way to get the last --> last updated time right?
Any simple ideas on how to do it?
I can probably create a helper that change everytime that the boiler turns on and keep that time.
But i wonder if there's a simple one liner script that can do that calculation without adding more complexity to this
i can also create 2 helpers
- for when the boiler last turned off
- for when the boiler last turned on
- create a sensor that has 1 minute the other
And also keeps the two other fileds (last turned on and last turned off)
So i'll have a sensor with all those fileds.
Just wandering if there's an easier way...
you could probably store "last" value in a input_text helper, then do the compare to the current
if I got this right, that is... 🙂
emmmm you might be right.
Let me think about it for one sec
Morning everyone, yesterday (and for last year or so) this was working fine. Today I am getting errors when trying to restart HA or do a config check. ```yaml
- platform: template
sensors:
toaster_cost:
friendly_name: Toaster Cost £/day
unit_of_measurement: £
value_template: "{{ (states('sensor.toaster_energy_today')|float*0.21607))|round(2) }}"```
The error is Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['toaster_cost']['value_template']. Got "{{ (states('sensor.toaster_energy_today')|float*0.21607))|round(2) }}". (See ?, line ?).
theres an extra ")"
how the fk did that happen, ive not changed this in AGES....
Looking at it, you seem to be missing a parenthesis right after the pipe sign "|"
i just removed the extra ) after the 0.21607 and its solved the error message. Dont know how on earth this has ever worked
I wanted to replace the 0.21607 with a variable I declared called var.electric_tariff
but when i substitute the number for the variable it complains about float & integer
im not very good with templates
try type-casting your variable? float("22")
{{ (states('sensor.speakers_energy_today')|float*('var.electric_tariff'))|round(2) }}```
thats what i put into the Template editor
get TypeError: can't multiply sequence by non-int of type 'float' as error message
what does float 22 mean? (sorry im rubbish with templates)
I'm sorry if I am confusing you, trying not to. I would try this "{{ (states('sensor.toaster_energy_today')|(float* float(var.electric_tariff)))|round(2) }}"
no its ok, just trying to get my head around how it hangs together to try and be self sufficient
Get this message TemplateSyntaxError: expected token 'name', got '('
Well, without being able to test, I am at loss too, sorry. Hope someone else can spot the issue, good luck!
cheers and happy new year
Happy New Year! 🙂
@pastel moon getting there with this template...
{{ (states('sensor.toaster_energy_today')|round(2))| float * (states('var.electric_tariff')|round(2)) }}
This gives me an output which is correct, but is 0.xxxx in format
Oh! states... I should've seen that. Good job!
need to somehow make it 0.xx
guess need to encapsulate the whole expression into a round(2) somehow
only been 1 hr of fiddling
When adding a template to my config.yaml, can I bring over the exiting properties too?
sensor:
- platform: template
sensors:
mmolbloodsugar:
friendly_name: "Blood Sugar"
entity_id: sensor.blood_sugar
icon: "state_attr('sensor.blood_sugar', 'icon')"
value_template: "{{ '%.1f'|format(int(states('sensor.blood_sugar')) / 18) }}"
Here, Icon is updated by the integration, but I need to format it into mmol/l instead of mg/dl. I do however want the icon to come through also.
out of interest, where are you retrieving the blood sugar levels from?
So the following which provides an output that I can't seem to keep at 2 decimal places only, it is very unlikely that the value would ever be about 1.0 £{{ (states('sensor.toaster_energy_today')|round(2))| float * (states('var.electric_tariff')|round(2,'floor')) }} so far today
Sometimes the output is 0.xxxx and sometimes its 0.xxxxxxxx etc
i just want it to always be x.xx
Convert to a number and then round
Also, convert both to numbers, do your math and then round at the end so your values are more likely to be accurate
Greetings! I am using the following to get readings from 2 different oregon scientific weather sensors, using the following:
value_template: '{% if value_json.chan == 1 %} {{value_json.tempf}} {% endif %}'
as well as :
value_template: '{% if value_json.chan == 2 %} {{value_json.tempf}} {% endif %}'
and they are working, except that when the value is for the opposite case for the channel, the value is set to zero.
How can I get the value to be ignored and not set if the channel is not for the current temperature? one sensor is outside and one is inside, so it isn't good for them to be bouncing between the temperature and the value of zero. any ideas?
Thanks!
they're MQTT sensors?
yes
the raw data looks like this: {"lowbatt":0,"chan":2,"tempf":73.220001,"humid":53.000000,"tempc":22.900000,"checker":30841} for the mqtt topic 'tele/ostemp'
I wonder what would happen if you just specified the current state of the sensor
BTW, you could simply what you have with this:
value_template: '{{ value_json.tempf if value_json.chan == 1 }}'
then, maybe value_template: '{{ value_json.tempf if value_json.chan == 1 else states('sensor.whatever') }}'
so in the else statement, it would effectively use the previous value, right? I think i like that
see if it works
thanks, trying now
it's a bad idea for a template sensor, but may work here
if I had been wiser i would have initially had the chan number as part of the topic.. 🙂 I may go there if this doesnt pan out!
that would be a better solution if you're controlling it
this is an atypical combination of topics and sensors
right.
You can also use an availability_template, but I suspect that that would cause the state to switch to unavailable
restarting now with the example with the else statement in it.
the else states version fixed it, thanks!
Quick question... i don't get it.. i'm going nuts
{{as_timestamp(states('input_datetime.boiler_last_on')) | timestamp_custom('%H:%M:%S') }}
Results in: 17:32:46
{{as_timestamp(states('input_datetime.boiler_last_off')) | timestamp_custom('%H:%M:%S') }}
Results in: 17:33:04
The second - the first should give: 00:00:18
i.e. {{((as_timestamp(states('input_datetime.boiler_last_off'))) - (as_timestamp(states('input_datetime.boiler_last_on')) ))|timestamp_custom('%H:%M:%S') }}
However, it results in: 02:00:18
What's going on!?
Both entities are date&time objects.
Sounds like a time zone issue
i thought so as well, but both on their own provide the same time zone. i've checked
That worked...
{{((state_attr('input_datetime.boiler_last_off', 'timestamp')|int) - (state_attr('input_datetime.boiler_last_on', 'timestamp')|int))|timestamp_custom('%H:%M:%S', false)}}
Hi everyone! Is there a way to auto-populate a group from entities within an area?
Yes, by calling group.set with a template
But why would you need that? Vs just using the area as is, or just creating a group
I want to just expose 1 singular entity for all of each room's lights with Google Assistant, if that makes sense. So even if I swap some lights around, as long as the areas are set up correctly in HA then Google will still control the appropriate lights.
And GA sees the areas? Or just a group?
I got my template rounding as I wanted using this ``` value_template: "£{{ ((states('sensor.ninja_xl_energy_today')|float)| float * (states('var.electric_tariff')| float))|round(2,'floor') }}"
I would just ignore areas and create a group
shame ive spent hours fiddling about to do it, all good learning though
Half my cards use auto-entities based off of their areas and I don't know how I would tell it to expand a group
I would like to stick with areas, basically just trying to make it as hassle-free as possible
It’s mentioned in the docs: https://github.com/thomasloven/lovelace-auto-entities#filters
Anyway, group.set with a template that uses area_entities() and an automaton to call that at startup
It’s possible, but not straightforward
I'll fiddle around with that! Thank you for your help! Happy New Years!
Thanks for the inspiration! I managed to get around to it ultimately like so:
- service: input_datetime.set_datetime
data_template:
time: "{{ (strptime(states('input_datetime.vacuum_scheduler_weekdays'), '%H:%M:%S') + timedelta(minutes=10)) | as_timestamp | timestamp_custom('%H:%M') }}"
target:
entity_id: input_datetime.vacuum_scheduler_weekdays
Idk if there are redundant filters in the time: attribute however this does exactly what I want.
#energy-archived Hello, I have 3 PZEM sensors installed on the 3 phases at the main entry of my house to analyze my electical consumption. In order to have a full view of the consumption, I have a template to add the value of the 3 phases. For some reason, at unknown events, the total value jumps to unrealistic values (in thousands of kWh).
- sensor:
- name: PZEM Main Energy Total
unique_id: pzem_main_energy_total
state: "{{ (((states('sensor.pzem_main_l1_energy') | float(0)) + (states('sensor.pzem_main_l2_energy') | float(0)) + (states('sensor.pzem_main_l3_energy') | float(0))) | float(0) / 1000) | round(2) }}"
unit_of_measurement: "kWh"device_class: energy
state_class: total_increasing
- name: PZEM Main Energy Total
I did comment to 2 last lines. Was is the mistake?
@solid jay posted a code wall, it is moved here --> https://hastebin.com/ijuzebozew
so ive been researching all night and can't find anything on how to make a automation that sends a notification to my phone randomize the message that is displayed on the notification can someone point me in the right direction? I see a bunch of stuff about TTS service and random messages and tried how those people set that up but didn't work for my case.
https://www.toptal.com/developers/hastebin/igabekowoy.yaml
What is the originating JSON payload
You’re missing a space before message:, you should use data: instead of data_template, and just use the notify service directly rather than using a device action
@solid jay
a space before message: ?
your indentation is inconsistent
two spaces some places, one in others
none before title:
nope
I don't know whether templates work with device actions, but it's much more compact to just use the right notify service
- service: notify.mobile_app_xxxx
data:
message:'{{ ["Hello Welcome Home", "Welcome Home, Sir", "Good to have you back"] | random }}'
title: Home Automation
got it working! thank you
Define payload on and off in sensor config
hm, just to confirm something.. Can you use data_templates with Scenes? Im trying to call a dynamitacally created scene related to the name of my switches, but I get an error with this code block ``` - service: scene.turn_on
data:
scene_id: "{{ trigger.event.data.id | regex_replace(find='_switch.*', replace='', ignorecase=False) }}_daylight_lights"
Error while executing automation automation.hue_light_remotes_on_variable: extra keys not allowed @ data['scene_id']
it's complaining about scene_id, which doesn't look like a valid thing
it is for scene.create
Ahhhh... -.-
Yeah, I copied the code and just replaced the create with turn_on, totally missed that
Hi all. I'm trying to set up a means to edit a field within lovelace where the value of that field is referenced by an automation. As an example, I can set the temperature from a lovelace card where an automation looking for the value uses the very same value from the other card. I have a helper set up using input_number but I'm not sure how to tie that to the automation in the UI. It seems I can only choose one or the other (thermostat or input_number helper) where I want to really use both (use input_number as value for thermostat). Am I missing something?
aw heck, I don't even need to do this. If I set up a single entity to climate.set_temperature it achieves the same exact thing as the whole helper idea anyway. This is basically a built in alternative. Nevermind!
Can someone please explain why this isn't working
[[[
if (light.d_g_kitchen.state == 'on'){
return `<ha-icon
style="height: 20px; color: black"
icon="mdi:lightbulb">
</ha-icon>`
} else {
return `<ha-icon
style="height: 20px;"
icon="mdi:lightbulb-outline">
</ha-icon>`
}
]]]
light.d_g_kitchen.state isn’t the way to get the entity state
What card are you using? (This is a #frontend-archived question)
custom button card
The docs have lots of examples for getting the state
Exhibit A:
label: >
[[[
return 'Other State: ' + states['switch.skylight'].state;
]]]
Thx i will try again
You also need to surround the HTML in backticks, and shown in the docs. It’s JavaScript
It is working now 🙂 Thx @inner mesa
Having difficulty with simple template created to convert units from gram to lbs:
template:
- sensor:
- name: "Kiki's Weight"
unit_of_measurement: "lbs"
unique_id: "sensor.kiki_s_weight"
state: "{{(states('sensor.t3_100006205_pet_weight') | float * 0.00220462) | round(2)}}"
- name: "Kiki's Weight"
Will about once per minute return a momentary zero for value in history trend, original sensor does not show these zeroes
I suspect that the sensor is becoming unavailable or otherwise reporting something non-numeric. You'd also see something in the log for that
Yep, the log has a detail stating 'float' got invalid input 'unknown', is there an easy way to change to refer to previous value rather than '0'?
You could add that the source sensor as a trigger and use trigger.from_state.state
As the default. |float(trigger.from_state.state)
Thanks, I haven't played around with trigger before so I give that a read/try
I have this in the configuration now:
template:
- trigger:
- platform: state
entity_id: sensor.t3_100006205_pet_weight
sensor: - name: "Kiki's Weight"
unit_of_measurement: "lbs"
unique_id: "sensor.kiki_s_weight"
state: "{{(states('sensor.t3_100006205_pet_weight') | float(trigger) * 0.00220462) | round(2)}}"
- platform: state
It seems to no longer return the 0 in the trend, but still getting log errors
Error rendering state template for sensor.kiki_s_weight: TypeError: unsupported operand type(s) for *: 'dict' and 'float'
resetting now
You should also review automaton variables: https://www.home-assistant.io/docs/automation/templating/
I had tried it, but didn't wait long enough for the poll refresh (2 minutes), so it was not returning any value
It was also incorrect
With
state: "{{(states('sensor.t3_100006205_pet_weight') | float(trigger.from_state.state) * 0.00220462) | round(2)}}"
I am now getting the log error
Error rendering state template for sensor.kiki_s_weight: TypeError: can't multiply sequence by non-int of type 'float'
Oh, add |float
state: "{{(states('sensor.t3_100006205_pet_weight') | float(trigger.from_state.state|float) * 0.00220462) | round(2)}}"
Thanks, trying now
It will still be a problem if you get more than one in a row
Template warning: 'float' got invalid input 'unknown' when rendering template '{{(states('sensor.t3_100006205_pet_weight') | float(trigger.from_state.state|float) * 0.00220462) | round(2)}}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1
I'll look into that, thanks. I'm guessing the source is polling every 2 minutes and it normally returns the prior value (and briefly is unavailable while polling)
I'm guessing the dev can quickly fix the sensor issue since it looks like the rest of the sensors only update with value changes instead of with every poll
Thanks again @inner mesa
I want to display additional weather attributes/states computed from a formula
@round hill you could also provide an availlibility template and state is should only be available if the source sensor is available
Hi guys! This morning something odd happened. isoweekday() no longer works? If I instead use weekday() I'm back in operation... Using it in this template {% set day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] %} {{ day[now().weekday()] }}
Ok. Somehow it was the list that did not return correctly. Changing the list into this syntax resolved it tho {% set days = {6: "Saturday", 7: "Sunday"} %}
Hi,
need some I getting values from api, they coming through as a string instead of numeric.
how can I go about changing it?
|float
hi all, is there an way to template to count the total number of calendar event for the next 12 hours.
will actually more than count. And the end I want to pull all the event for the next 12 hrs and read in my current tts morning briefing
so far i can going get event message for the next incoming events and nothing after that.
Probably should be using |float(0) now (or whatever default you want)
Yeah, adding the default float(0) to 2nd float fixed my log warning @inner mesa @marble jackal
So my unit conversion template seems to be working perfectly without log issues with the trigger fix
Hi , im trying to include template sensors on my configuration in order to use them on the energy screen . So far i was not able to make the template.yaml file to load properly , and there are no visible errors detected by the config check . just the message template integration could not be set up , any ideas what the cause may be ?, tks
Sorry I know this message is ancient, just now getting back to this after all the holiday madness... yeah, feed count is an entity. I thought I could use a numeric state for that, but if I'm reading the docs right numeric state is only useful when you're crossing a given threshold. I guess that means I could still use it but it wouldn't be as simple, e.g. I'd have to set up separate ones for when it crosses 1 time fed, 2 times fed, 3 times fed for the day etc. which I would need to use a template in the trigger to accomplish. Does that sound right?
you can use a numeric state trigger with no params other than the entity. use a template condition or choose action to figure it out from there
{{ trigger.to_state.state|int(0) > trigger.from_state.state|int(0) }}
morning all, I'm trying to create a template that will calculate my bmi. the formula is weigh in lbs / height in inches squared multiplied by 703, butI cannot get my template to work.
{{ (states('input_number.weight_karl_lbs') | float / (states('input_number.height_karl_inches')*(states('input_number.height_karl_inches'))) *703) }}
the error i recieve is:
TypeError: can't multiply sequence by non-int of type 'str'
i'm just not sure how i can fix it now.
turn the other two values into float
| float
great. Thank you! didnt realise it was a s simple as putting that after each entitiy.
If you want to avoid warnings/errors in your log, you should also provide a default value (eg | float(0))
Thank you. Managed to get that doing the calculations i need.#
Hey guys, Pretty new to all this home assistant, really excited. By any chance is there a free/outsourced template for Lovelace or something I can at-least start from?
👋 Home Assistant generates a dashboard for you
which you can use as the starting point (it will ask if you want to keep the existing dashboard when you take control)
Yeah I chose the “no option” and realised that was a mistake and now I have no idea how to get it back 🤦♂️
You can create a new dashboard in the configuration panel
a new dashboard will by default be the auto generated one
Or you can go into the raw editor, delete everything, and save. But we're well into #frontend-archived territory
Is it possible to parse a json Webhook that is multipart? Specifically for plex webhooks. I saw a post from '17/'18 saying HA didn't support it and I can't see that it does now? Thanks
Trigger: https://pastebin.com/WWTT7ZhP
Good morning everyone! Yet another HA Newbie here... so far I'm enjoying the experience although I get sucked into a lot of black holes! I hear that's par for the course... I've got a few questions if that's ok... first one is a custom sensor I setup for my litter robot which "works". It feels like I did it the wrong way however and I'm hoping someone can guide me in cleaning it up:
#Litter Robot Sensor Over Torque
template:
sensor:
- name: "Litter Robot Status Code"
state: =
{% set litterrobotstatus = state_attr('vacuum.litter_bear_litter_box', 'status_code')%}
{{litterrobotstatus}}
I don't think I have it written the right way although it is functional.. but I think that due to the way I'm writing it, it is stopping me from creating other customer sensors (that read attributes)
I think you can replace it with just state: = {{ state_attr('vacuum.litter_bear_litter_box', 'status_code') }}
@sly urchin Trying that now... is the other part ok though? the way it's structured? template, sensor, name i mean
I don't get discord formatting but the link above should be fine
I'd use > rather than = actually
@sly urchin thank you.. I'm trying that and attempting to clean it up like you wrote... Afte that I'll try to add my second sensor and see if it gives me issues like before
No problem, I wish you well 👍
Is there anyone who can help with my post above regarding a mutli part json webhook from plex? I am struggling to extract the relevant pieces of info. Thanks
that formatting isn't quite right
if you're putting it all on the same line, it would be this:
state: "{{ state_attr('vacuum.litter_bear_litter_box', 'status_code') }}"
">" is only used if you're introducing a multiline template
@sly urchin @inner mesa Indeed, when I do it the with the proper formtting that HolyBift sends me, it breaks it.. I was able to rework it a bit to make it work again though buy doing this:
#Litter Robot Sensor Over Torque
#template:
sensor:
- name: "Litter Robot Status Code"
state: = {% set litter_robot_status_code = state_attr('vacuum.litter_bear_litter_box', 'status_code')%} {{litter_robot_status_code}}
(minus the # )
If I don't put in % set then it doesn't work (or well, then I'm not reading the info right lol)
that's just broken
You've mixed and matched there
use the code that I provided
@sly urchin @inner mesa So, I've used the code provided but now it says (and I think it makes sense): entity not available: sensor.litter_robot_status_code. I'm thinking that makes sense because I haven't created a custom sensor called litter_robot_status_code. What I'm trying to do (which worked with my sucky code) is to add a status and when it has a certain value (OTF specifically), it will turn off my smart plug and turn it back on (the only way to fix that error according to support). With my bad code, I could see this:
oops..seems I can't post a screen cap lol
I assumed that the entity and attribute that you were using actually existed
@inner mesa No, I'm sorry.. I need to create a custom sensor.. I'm actually trying to do that with multipel different devices but I can't get past the one I posted lol
@inner mesa I wrote it in the original thread but maybe I used the wrong words to express myself clearly lo
please stop tagging me
oh sorry
with the bad post, this is what my card looked like: https://imgur.com/a/EYkR65W
sorry bad code
is it possible in template to cut part of entity name? Lets say trigger will be climate.trv and i need to change the part "climate" into switch. so it become switch.trw.
of course. I recommend checking out the template docs...
{{ "climate.foo".replace('climate', 'switch') }} -> switch.foo
where did you learned all the stuff?
I just stumbled upon this in the HASS logs:
2022-01-03 19:30:23 WARNING (MainThread) [homeassistant.helpers.template] Template warning: 'multiply' got invalid input 'unavailable' when rendering template '{% if is_state('sensor.tasmota_kuhlgerate_energy_total', 'unknown') %}
Unknown
{% else %}
{{ '{:.2f}'.format(states('sensor.tasmota_kuhlgerate_energy_total') | multiply(0.19)) }}
{% endif %}' but no default was specified. Currently 'multiply' will return 'unavailable', however this template will fail to render in Home Assistant core 2022.1
This is the little script that calculates the whole kW usage to a properly readable Euro value. However I really have no idea what's wrong here as I also just found this exact thing in a forum and edited the values... Could someone help me? I already found the forum entry explaining how to "fix" it but I still am just... stuck 😓
Or maybe there's a better solution to this in general, as I just want to convert one value to Euro. Maybe this is too complicated to begin with anyways.
How? I really don't understand templates at all, I simply just found this in a forum and copied it.
And since then it work(s/ed) ^^"
check the 'confused about defaults' pin
it describes how to add defaults to existing methods & filters, multiply is a filter
From the docs, searching on the forum, and trying stuff in the template dev tools. And occasionally from folks here 🙂
I know I sound really stupid but I don't understand this much at all ^^"
So... simply editing multiply(0.19) to multiply(0.19, default=0.19) should fix this?
yep
but default is for the value you're multiplying against
The "perks" of not being a programmer nor understanding any of the terms much at all lol
so when states('xyz') fails to convert to a float, it will use the default
do you want to multiply 0.19 * 0.19 if the state of sensor.tasmota_kuhlgerate_energy_total fails to convert?
But to my understanding a simple state of 0.19 which will never fail to be a float could also just be ignored? I mean, I understand that this is rather for cases that "in case this sensor gives me a wrong value back" and all.
Or am I understanding this wrong
you are
Hm.
your code is
value | multiply(value_that_youre_multiplying_value_by)
essentially
value * value_that_youre_multiplying_value_by
Oh, so if value = undefinied it'll take the default I gave it and use that instead of value?
the default is for value, not value_that_youre_multiplying_value_by
well, it's only confusing because you're using multiply
you could just... multiply
{{ states('sensor.tasmota_kuhlgerate_energy_total') | float * 0.19 }}
I mean, as said I found that script online somewhere ^^" I really have no idea about Templates whatsoever as you may already could guess by me being confused by this simple stuff :D
but you still need to specify a default for float
states are strings i.e. letters. you can't multiply letters and numbers. So you have to convert the letters to numbers
that's what float does
multiply also does this for the user, but as you can see, it's confusing.
So | basically just "gives" the state of the sensor to float for it to convert it to a proper number, then multiplies it
| means "apply filter"
you're filtering the letters into numbers
🤷♂️
you could also write it like this...
{{ float(states('...')) * 0.19 }}
but you still need a default for float
So HA understands both these variants? Cause that makes a bit more sense to me heh
Yep
It doesn’t work for every filter or function
But you can find out which do what in the docs
Yeah, tho thanks for explaining it a bit. Never really looked much into this since I never needed it and also a bit confusing.
Not even sure if this is the "most elegant" way to do things, it simply converts a value my Tasmota plug gives me into Euro for Today, Yesterday and All-In-One values. But that's out of the scope for Templates then of course.
If you have used macros in excel, it’s the same crap minus the {{ }} and {% %}
How can i check if this works in Template editor? {{ state_attr('trigger.entity_id', 'current_temperature') > state_attr('trigger.entity_id', 'temperature') }}
seems it do not
You can’t
Also, trigger is an object. Putting in quotes makes it a string
oh
this should work right {{ state_attr( trigger.entity_id, 'current_temperature') >= state_attr( trigger.entity_id, 'temperature') }}
Probably. As long as it's in the action of an automation and the automation triggers
It’ll work if your triggers have entity_ids
Every trigger*
If you have a time trigger it won’t work
I have it but it doesn not work :/
@final parcel posted a code wall, it is moved here --> https://hastebin.com/pitequxazu
always chooses default option
of course it will not work if i trigger it 😄
sorry guys
Both triggers have entity_ids, so the template should work.
If you want to test it in the template editor, you can do something like this:
{% set trigger = { 'entity_id' : 'climate.radiator_loznice' } %}
{{ state_attr( trigger.entity_id, 'current_temperature') >= state_attr( trigger.entity_id, 'temperature') }}
I added a custom switch, to toggle my alarmsystem on and off (I use that variable in node red)
switch:
- platform: template
switches:
alarmsystem:
turn_on:
service: switch.turn_on
target:
entity_id: switch.alarmsystem_on
turn_off:
service: switch.turn_off
target:
entity_id: switch.alarmsystem_off
But why do I have then on the dashboard this lightning icons?
and not a regular switch like another cards
Because you didn’t provide a value_template
The state is determined by the template provided by the value_template field
It doesn’t know the state, therefore is just provides you with on or off buttons
so I need a sensor template? Cant find a "value_template"
What do you mean “can’t find a …”
ok sry I found it. https://www.home-assistant.io/integrations/template/
But I don't understand this now ... I have now defined a switch and this switch is in the end a entry ( I can perfectly switch from off to on and in node-red I get the state correctly) If I add now a sensor, why should this affect the dashboard ...
I tried a sensor, but that didnt worked
I think this is often my problem with home assistant ... I have still a problem / bug with my total power consumption from a measure device. I searched in the whole source code from the integration why this can happen ... didn't found the reason yet ... Maybe I have to read the whole documentation from HASS including the integration docs
thx worked
what's the bug..
oh no it didnt, now the switch flips automatic back
the state is determined by the value_template
if your template is wrong, the state will always be wrong
Hey guys I'm having somewhat of a problem controlling my lights. The setup is as follows: All my lights are controlled by a Siemens LOGO which I control through Node Red. All lights exist inside HASS as template lights and input booleans. the boolean corresponds to the current state of the light and is defined as such. node red listens for the events and triggers a variable inside the logo which turns on a relay. Node red reads this change and updates the input boolean to have the correct value.
unique_id: light_bedroom
friendly_name: Licht Slaapkamer
value_template: "{{states('input_boolean.light_bedroom')}}"
turn_on:
event: light_bedroom
turn_off:
event: light_bedroom```
Everthing works fine when I use the lights individually either from HASS or pressing the switches inside my home. Updates instantly and has been working for over half a year without any issues. Now this issue is when I want to update more than one light at once, for example turn on/off all the lights in a room. Because this just inverts the state of all lights, due to the turn on and off event being the exact same thing.
The PLC operates completly seperatly from hass which is a hard requirement as I want my lights to function as normal even when my HASS instance could be dead.
Inside the LOGO the logic is that if a Pulse is detected on the variable the corresponding output relay is switched on/off.
The problem is that HA calls a turn off command for lights that are already turned off, which somewhat makes sense, just not in my case 😄
I created the switch now in node-red and its work perfectly fine. I think the service: switch.turn_on and switch.turn_off was the problem? I don't know
I was able to set the state from off to on and vise versa in the dev tool
and the state was displayed correctly on the dashboard
@nimble steppe posted a code wall, it is moved here --> https://hastebin.com/rixisisinu
I did find a template i think has been written by petro so i am trying to get to work but cant get it to work as my Yaml knowlage is minimale..
i have a template sensor i am trying to get to put out 5 states open, closed, closing, opening and sensor error. ( 4 states works but not closing)
Setup:
i have 2 binary sensors so giving input if door is open or closed and i want 2 "fake" between status opening and closing when sensor goes between the states open_on and close_on.
But i cant get the templaet to work properly, after the state open it do not go to state closing after the binary contact for open_on goes false/off. (it then goes back to opening and not closing)
What if you try
{% elif close_on and not open_on %}
closed
Or
{% elif (not open_on) and close_on %}
no still the same, but will it not be this part of the template so changes the "fake" states betwen closing and opening?
{% else %}
{% if is_state('sensor.garage_door_2_status', 'open') %}
closing
{% else %}
opening
{% endif %}
Oh sorry, I misread. I though closed was not working, but it was closing
If I understand correctly, the state should be closing or opening when both binary_sensors are off
and it should be closing when the previous state was open, and opening when the previous state was closed
if i have understand the template right the state shall change to open and close when binary contacts are triggerd, and that {% if is_state('sensor.garage_door_1_status', 'open') %} statment will trigger the next fake state when one of the binerys goes false/off.. but i cant read code so im on thin ice hehe
yes as you write is how i have understand this template to work
Could you check in
> States if the entity_id of this sensor is actually sensor.garage_door_2_status
entity_id is: sensor.garage_door_2_status copyed from dev tools
And if the door is acutally closing, the state shown is probably opening right?
the sensor is not connected to the door, i have it right her with me so i can trigger it as i want. Green wire was the idea of closed and yellow was open. and that is what so is showing when i trigger the binarys. ( it is a fibaro smart inplant)
Okay, but what happens then if you simulate the closing of the door, what does your sensor return in that case
if i trigger the binary for close door (green wire) status is closed, if i relase binery it goes to opening, then when i put binary sensor on for open door (yellow wire) it goes to state open. ( so far it works fine) and if i then relase binary for open (yellow wire) it goes to state opening ( her it was supose to go closing). The error state works to if i try both binary at same time it says sensor error.
dubbel checked from dev tools that yellow wire is the binary_sensor.garage_door_1_open this goes on
Okay, then the part which goes wrong is this {% if is_state('sensor.garage_door_2_status', 'open') %}
Could you stimulate the open state, and check what this returns in the template editor
{{ is_state('sensor.garage_door_2_status', 'open') }}
IMO, to avoid any issues, you'd need to make 2 template sensors. 1 that is an event stream, and 1 that's your actual states. All using the new templates.
had to update link, template got cut off.
I'm sure you could simplify the event stream template to just
- sensor:
- name: Garage Sensor Events
unique_id: garage_sensor_events
state: >
{%- set a = is_state('sensor.a', 'on') %}
{%- set b = is_state('sensor.b', 'on') %}
{%- if a and b %}error
{%- elif not a and not b %}transition
{%- elif a and not b %}open
{%- else %}closed
{%- endif %}
either way, to avoid circular references, you'll need 2 sensors. IIRC the guy in that thread only wanted one... So I made 1 sensor.
2 sensors is more robust and will not produce errors
I have these template lights, but I want to prevent turn_on/turn_off actions to fire the event if the state of the corresponding boolean is on/off. I've found there is a condition property but I'm not sure how to combine these with the event property.
light:
- platform: template
lights:
light_desk_upstairs:
unique_id: light_desk_upstairs
friendly_name: Licht Bureau Boven
value_template: "{{states('input_boolean.light_desk_upstairs')}}"
turn_on:
event: light_desk_upstairs
turn_off:
event: light_desk_upstairs
turn_on and turn_off are action sections, so treat each one like a script. You can add as many actions as you want, even conditions.
This is going to sound really lazy but is there any free dashboard templates out there that I am able to have a play around with I have not long started and just looking for something to get me started mainly
that's not how this works. Everyone has different entities, if you don't have the same entities, nothing will work. Also, you keep coming to templates for what you think are templates, but in actuality, these are not the templates you think they are. You should be asking this in #frontend-archived
Aaaaa okay I see what you but can’t I just edit the entity’s or would I just be defeating the object then and may as well just start from scratch and make my own from step 1 🤷♂️ also my bad I didn’t realise I thought templates was what I was asking, so what is the section mainly for then?
this section is for templating
with jinja and yaml
#frontend-archived is for everything lovelace
this is a template: "{{ do_something('xyz') | something_else }}"
and yes, you'd be hand editing everything. You should just use the auto front end. If you want to play around, make another dashboard where you can add things in. Otherwise starting from some one elses UI is fruitless because you'll have to edit the entire thing.
Hello. I need an automation to be triggered by numeric state change but it is being triggered just by not change but even by update by the same number. To avoid that I would need to make to automation to run only each three minutes but I need to leave the triggers there. Is it possible to solve it by condition to template? How please? 🙂
Thanks I was able to get it working 😄
np
Thank you for the help think it is going to take awhile to understand this 😂
Can anyone help extract a webhook that starts as such? Thanks
data: __type: <class 'multidict._multidict.MultiDictProxy'> repr: >- <MultiDictProxy('payload': bytearray(b'{"event":"media.pause",
that doesn't appear to be valid data. That's a string repr of the class. How are you getting that information
From a plex webhook
I am stuggling to find any information on it like usual templates
are you using a webhook trigger?
Yes
you want the trigger.json
If I use {{ trigger.json }} then it just spits out the whole thing yes. I'm wondering if I can actually extract from it like json i've come across before
yes, but you have to use trigger.json
Sorry I don't understand, use it how?
what have you seen before?
I can make it print the whole webhook by just using {{ trigger.json }} in the message but for a sonarr webhook for example I can use {{ trigger.json.level }}: {{ trigger.json.message }}
ok then, what's the problem, it's the same thing
if you aren't getting trigger.json, then that would mean your result isn't json
I get trigger.json but the attributes I'm trying either don't work or i'm doing it wrong
what are you getting back from trigger.json then
again, what you've posted is not trigger.json
dude, you have to post the entire thing
not snppits of it
can't help with snippits
that's with some formatting trying to split it sorry
so {{ trigger.json }} emits this....
Ah it's embedded all my info taking ages to clense so I've passworded and pmed you sorry for the long
it's still cut off
that's still not json, that's a repr of the python object
if plex is cutting off the payload, then there's nothing you can do
Yes this will be all that's being sent from plex, I can't change it in there at all
I'd need to see what's fully in trigger.json, not trigger.data
Ok, now head over to jsonformatter.com
paste that pastebin into the formatter and format it
what info are you trying to get?
for example, if you wanted "event"
it would simply be trigger.json.event
however if you want metadata
it depends on what you're trying to get
Oh
I was using trigger.data the whole time
Error: Error rendering data template: UndefinedError: 'dict object' has no attribute 'json'
So is it JSON nested inside plain data? In basic terms
the json attribute will only be populated if it has valid json
is that error occuring when you use {{ trigger.json }} or {{ trigger.data.json }}
when using `{{ trigger.json.event }}'', but using {{ trigger.json }} it doesn't show anything the message just sends with the icon no text
Then the information being sent over is not json
again, trigger.json only exists if it's actually json
Right I understand, so is it possible to 'parse' the trigger.data to grab the things I'd like (user , device, title, episode)?
it is but it's not easy
you have to use regex or split the string
both can be complicated
Yep I got as far as finding a split example but you are right it is complicated. Where should I start? 🤣
start with the word you want and split the string based on that
with regex, you'll need to fart around. It's a whole string parsing language
Ok thanks very much for your help thus far, I've just realised you're the author of some posts i'm reading on HA forums too lol
Been here a looooooooong time
I've probably been using HA 4 years now and every time I go to change anything I learn something new!
{{ (trigger.data.split("event":[?] }} is this on the right line? Does it literally split by number of characters? My goodness I thought templates were difficult
So, I have a question I can't figure out. I've added an template sensor which determines the active speaker in a pool of Google Homes. the state is simply the name (media_player.googlehome8007). However, I would like to create a 'template' media_player which I can use in my lovelace cards. Any idea?
Can anyone help me with these sensors I am trying to create https://pastebin.com/iHEKRXei I am getting these errors https://pastebin.com/6mCFKJHA but I thought I copied the example for people groups directly from the docs
You are missing an } at the end
The template should be closed with }}, you only have one }
thanks, that was it, so weird i must have lost it in the copy/paste
how to check if my variables has a value, in order to avoid some errors and warning in my logs
fields:
variable1:
description: 'speed of wled effect'
example: '100'
sequence:
- choose:
- conditions: '{{ variable1 is defined }}'
sequence: ...```
I saw somewhere this is defined but Im not sure..
Should work, but in that case it will also return true if the variable is [] or ''. If you don't want that you can use {{ True if variable1 else False }}
is there a way to sum up 41 sensor that contain some repeating keywords in name (so i can clearly use regex) without naming every single one of them and add a + after each one
basically i do not want this:
{{ (states('sensor.server_room_outlet_1_energy_power')|default(0)|float + states('sensor.server_room_outlet_2_energy_power')|default(0)|float)|round(3) }}
Do they all end with _energy_power
yes
and they all contain outlet also
so easy to regex them
but i do not know the format i'd use
The | default(0) is not needed anyway, you can use | float(0) to use 0 as default
will do
so any idea how to accomplish this?
{{ (states('sensor.server_room_outlet_1_energy_power')|float(0) + states('sensor.server_room_outlet_2_energy_power')|float(0))|round(3) }}
i've change it to this for now
Something like this:
{{ states.sensor | selectattr('entity_id', 'search', 'energy_power') | selectattr('entity_id', 'search', 'outlet')| map(attribute='state') | map('float', default=0) | sum | round(3)}}
this actually works
I know
very nice
thanks man
Template loop detected while processing event: <Event state_changed[L]: entity_id=sensor.total_sockets_consumption, old_state=<state sensor.total_sockets_consumption
sad story
no idea why
since in template on test worked ok
skipping template render for Template[{{ states.sensor | selectattr('entity_id', 'search', 'energy_power') | selectattr('entity_id', 'search', 'outlet')| map(attribute='state') | map('float', default=0) | sum | round(1)}}
😦
But does it return a result?
yes
Well, I think it is because it's a sensor itself, so it is included in states.sensor. but after that it is filtered out, so it doesn't matter
yah i took special care not to include any of searched attributes
so i do not include this sensor also
Maybe if you do it like this it won't give this warning:
{% set energy = states.sensor | selectattr('entity_id', 'search', 'energy_power') | selectattr('entity_id', 'search', 'outlet')| map(attribute='entity_id') | list %}
{{ expand(energy) | map(attribute='state') | map('float', default=0) | sum | round(1) }}
let me give it a try
oh yah
seem if you make a list and parse that it works
no more warnings
ty
@marble jackalcan u please point me in the right direction to learn more template-ing in general?
There are some pinned links on this channel
ty a lot for everything, much appreciate it
I'm trying to create a template for all my doors and windows. Basically i want if all are closed i want the state to be Closed, if one is open it should be the name of that sensor (or something readable) and if multiple are open it should say "multiple open". How can i achieve this?
Just create a group
Oh, the multiple open will not work then. But you can not template the name of the sensor, only the state
Hi! Does anyone could help me to tell what is wrong with the expression below?
- service: script.activate_alexa_custom_skill_notification
data_template:
text: >
Espere! As janelas
{% set windows_area = { "binary_sensor.janela_do_quarto_contact": " do quarto", "binary_sensor.janela_da_suite_contact": " da suíte", "binary_sensor.janela_da_varanda_contact": " da varanda" } %}
{{ [windows_area[k] for k in windows_area.keys() if is_state(k, "on")]|join(", ") }}
ficaram abertas
event_id: "close_windows"
response: {}
alexa_device: media_player.echo_dot_sala
The line that is causing the error is:
{{ [windows_area[k] for k in windows_area.keys() if is_state(k, "on")]|join(", ") }}
I am receiving this message:
Invalid config for [automation]: template value should be a string for dictionary value @ data['action'][1]['data_template']. Got None.
@hollow smelt To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
data_template is long dead, it's just data
What are you trying to achieve with this template?
I would like to join only the values of the filtered list
I have a list of key:value pairs (entity_id:area)
I would like to filter the values based on the state of the entity id (key) and join its areas (value)
I thought I could use python...
That is why I used [windows_area[k] for k in windows_area.keys() if is_state(k, "on")]
Then I saw mentions about jinja2 in the docs and don't know whether there is some equivalent to do what I need
I changed to data and the error is the same.
The expected message translated would be similar to this:
"Wait! The windows from room, bathroom, kitchen are open"
"room, bathroom, kitchen" is the dynamic part that is causing the error
Check the template docs in the pinned post. There is actually a function to retrieve the area_name:
{{ area_name('entity_id') }}
in my case, it isn't the area exactly because of my language that requires different preposition for each area
In portuguese, the message would be:
"Espere! As janejas do quarto, da suíte, da varanda ficaram abertas"
"do quarto, da suíte, da varanda" is the dynamic part
I think the biggest problem I have is how to filter a list using jinja2
based on the condition is_state("entity_id", "on") or similar
https://blog.finxter.com/how-to-filter-a-list-in-python/#Python_Filter_List_with_Condition
lst = [11, 14, 3, 0, -1, -3]
filtered = [x for x in lst if condition(x)]
that is what I am trying to do
{{ expand(windows_area.keys() | list) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }} should return those which are on
What will happen if multiple are open if i have a group?
It will show open if at least one is open
Okey but it wont show which one?
wow! almost there!
it is returning the entity_id, it is expected the values from windows_area
I will think how to map these entity_ids to the values
Thanks, @marble jackal
You can using templates 😅
Any guidance on how that would look?
Something like this:
{% set open = states.binary_sensor | selectattr('attributes.device_class', 'in', [ 'door', 'window' ]) | selectattr('state', 'eq', 'on') | map(attribute='attributes.friendly_name') |list %}
{{ open | join if open | count == 1 else 'multiple' if open | count > 1 else 'closed' }}
Hm. That seems to report closed all the time.
This is how the template looks.
doors_and_windows:
friendly_name: 'Doors and windows'
value_template: "{% set open = states.binary_sensor | selectattr('attributes.device_class', 'in', [ 'door', 'window' ]) | selectattr('state', 'eq', 'on') | map(attribute='attributes.friendly_name') |list %}
{{ open | join if open | count == 1 else 'multiple' if open | count > 1 else 'closed' }}"
@marble jackal
I wasn't able to retrieve windows_area back again after all those filters applied
I did this:
Espere! As janelas {% set windows_area = { "binary_sensor.janela_do_quarto_contact": "do quarto", "binary_sensor.janela_da_suite_contact": "da suíte", "binary_sensor.janela_da_varanda_contact": "da varanda" } %}{% for k in windows_area.keys() %}{% if is_state(k, "on") %}{{ windows_area[k] }}, {% endif %}{% endfor %}ficaram abertas.
The only side effect is an additional comma at the last item but it doesn't make difference to Alexa.
Actual result: Espere! As janelas do quarto, da suíte, da varanda, ficaram abertas. (satisfatory)
Expected result 1: Espere! As janelas do quarto, da suíte, da varanda ficaram abertas. (acceptable)
Expected result 2: Espere! As janelas do quarto, da suíte e da varanda ficaram abertas. (my dream)
the first two look identical to my American English eyes
just an additional comma after "varanda"
I believe they are aside from a comma
oh, I missed the comma
I tried but I am new to jinja2
I usually recommend creating your variable that is input into the string on one line, with {% set myVariable = template_stuff_here %} and then outputting it in the sentence afterwards.
So what we're really looking at, is how to do this part better:
{% set windows_area = { "binary_sensor.janela_do_quarto_contact": "do quarto", "binary_sensor.janela_da_suite_contact": "da suíte", "binary_sensor.janela_da_varanda_contact": "da varanda" } %}{% for k in windows_area.keys() %}{% if is_state(k, "on") %}{{ windows_area[k] }}, {% endif %}{% endfor %}
tried to find a way to pass it through map but no joy
So this part:
{% for k in windows_area.keys() %}{% if is_state(k, "on") %}{{ windows_area[k] }}, {% endif %}{% endfor %}
Could become:
{% set myOutput = expand(windows_area.keys()) | selectattr('state', 'eq', 'on') | list | join() %}
got this far:
{{ expand(test.keys())|selectattr('state', 'eq', 'off')|map(attribute='name')|join(', ') }}```
Untested, but that might work.
uses the friendly names
This is what @marble jackal did. It returns the entity_id (key) at the end
(Though if it's assigned to an area I think I read something earlier about getting the area from a the entity_id? area_name('entity_id')? I've lost the forum post)
looping == failure 🙂
{% set myOutput = expand(windows_area.keys()) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | map('area_name') | list | join() %}
Yeah... @marble jackal mentioned it.
I said that in portuguese we need a different preposition before each area
that is the reason why I need "do quarto", "da varanda"
You could put the preposition in the area name itself 😉
It's a relatively common approach to translations to make sure that articles are included where they are necessary. Cases do complicate matters, but they're not impossible either.
I've customized the friendly_name of my leak detectors to improve text output
you could even make a custom attribute just for this if you like
use items
(If this were German, Latin, Russian, or any language with cases, you'd need custom attributes for the indefinite and definite articles in each of the cases!)
{% set test = {"binary_sensor.living_room_occupancy": "living room", "binary_sensor.guest_bedroom_occupancy": "guest bedroom"} %}
{% set open = expand(test.keys())|selectattr('state', 'eq', 'off')|map(attribute='entity_id')|list %}
{{ test.items() | list | selectattr('0', 'in', open) | map(attribute='1') | join(', ') }}
it wouldn't work because the preposition depends on the sentence
it could be other preposition in other sentence
i am satisfied the way it is afterall.
I will check this
Then my suggestion as per the cases applies 😉
Does Merriam-Webster accept PRs?
Though perhaps a different construction of the sentence would be better:
Aguentar! Existem janelas abertas nos seguintes quartos:
- Balcony
- Living Room
...
*Apologies for the Google Translated Portuguese
Alexa doesn't differ it. It is expected Alexa say this message.
But you are right about this
{% set windows_area = { "binary_sensor.janela_do_quarto_contact": "do quarto", "binary_sensor.janela_da_suite_contact": "da suíte", "binary_sensor.janela_da_varanda_contact": "da varanda" } %}
{% set open = expand(test.keys())|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list %}
{% set open = test.items() | list | selectattr('0', 'in', open) | map(attribute='1') | list %}
{% if open | length > 1 %}
Espere! As janelas {{ open[:-1] | join(', ') }} e {{ open[-1] }} ficaram abertas.
{% else %}
Espere! As janelas {{ open[0] }} ficaram abertas.
{% endif %}
It worked.
I just changed "off" to "on"
yeah, all of my sensors were off so i needed to get it working 😛
this is my dream expected result.
the best part is that you avoided usage of for-loop
{% if open | length > 1 %}
Espere! As janelas {{ open[:-1] | join(', ') }} e {{ open[-1] }} ficaram abertas.
{% else %}
Espere! A janela {{ open[0] }} ficou aberta.
{% endif %}
I said that in portuguese we need a different preposition before each area
almost. portuguese.
it also is latin
Italian and Portuguese look vaguely like Spanish to me
yes
they all have the same origin
similar enough, and yet not
and even then, I suspect that English curses are probably understood by most worldwide 🙂
at least you can tell if somebody is swearing at you
Thanks @mighty ledge , @silent seal , @inner mesa, @dreamy sinew and @marble jackal
I will study this code, mainly selectattr('0', 'in', open) this part
I also will read more about custom attributes
There's also rejectattr which has the same syntax but works the other way around.
You'll have a tough time studying what I did because it's a work-around
It's taking key value pairs, converting them into a list of tuples, then comparing the first item but using the second item
it's not high level stuff, but it's not straight forward
I'm also puzzling over that one
ok, so dict.items() returns an items() object
I cast that as a list
which looks like this
[('key1','value1'), ('key2','value2') ]
selectattr only accepts strings
I didn't know that '0' and '1' worked in that way
so... if I want to select based on the first item, '0', then I have to put it in quotes
yah, it's dumb
like I said, work-around
well, good to know
so whats funny is people say you can't do "{{ json.0.foo }}" but you can
its the hacky stuff that comes up when you're mixing python and jinja
yah
you totally can but it might not do what you expect 😛
so its usually better to say "don't"
heh its been a while since i've been able to catch a question here. Too many of you have caught up to me 😛
it's making it a string that confused me, or at least quoting it
things inside of filters are kinda strange too
jinja just treats all keys as strings for the most part
it's why you can do foo.0.foo in jinja but not in python
is it possible to fetch the last updated value of a sensor prior to it becoming unavailable? something akin to: state at time = last_updated?
If you trigger on the state going to 'unavailable', then the trigger.from_state.state would be the state it came from
fetching it after the fact requires you to use the SQL sensor
Would this be correct then for a template sensor?
https://paste.debian.net/1226043/
Yes, but it will only have a state after sensor.ence_01_energy_total became unavailable
You probable want to trigger on every state change, and use the to_state in case the state is not unavailable.
I always wonder if this type of thing is poor form? having automations that fire so often
So then something like this:
https://paste.debian.net/1226045/
(typo: Should be 01 instead of 02)
That will start producing 'unavailable' after the first one
Ah it can update the unavailable state and still remain the same I see
{{ trigger.from_state.state if trigger.to_state.state == 'unavailable' else trigger.to_state.state }}
Does it? The sensor triggering the changes is not the template sensor itself
The sledgehammer is to store the last valid value in an input_number. You may be able to replicate that by referencing the current template sensor state
Ah this is why people were saying to install the variable custom integration
Is there not a way to say "If state is unavailable, keep template the same as previous template state"
In the end, it's better to gave a reliable sensor.
Oh wait, looks like it is..
Not built in. In part because it's a bandaid for a broken sensor
Any idea what would be a best solution in future updates? Are the hass devs not sold on having "variables" and would rather have the helpers?
Try replacing trigger.from_state.state with states('sensor.xxx') (your template sensor)
input_number is a helper
Yeah Im saying are the helpers Hass' answer to variables going forward?
https://paste.debian.net/1226050/
So like this
yeah, maybe something like that. gotta work through all the cases
you can condense it using the syntax that TheFes provided
Yeah I will definitely give that a shot. Quite compact!
Would it be...
{{ trigger.to_state.state if trigger.to_state.state != 'unavailable' else states('sensor.ence_01_energy_total_const')}}
Hm, looks like that doesnt work. Changing the state of total to unavailable made the template unknown.
Perhaps I will just create the helper then.
what does your whole template sensor look like now?
I would expect something like that to work
Oh wait I changed it away from the template sensor.
https://paste.debian.net/1226056/
this is correct
Using the template I wrote up above does not change anything
that's using the helper
I was more curious if you could get it working by just referencing the template sensor value
you're saying that if you use the template from directly above, you still get "unknown"?
are you sure your sensor name is correct? I would have expected sensor.ence_01_energy_total_consistent
it looks like you're using the unique_id instead
Oh jeez
Yup... now it works. Oh god.
Note to self, entity names are not derived from unique_ids.
Ha, interesting. I think the new functionality of being able to set the unique id made me assume that's been changed.
A problem that I've now encountered with the above solution is that upon resetting the templates, the value resets to an unknown.
You can use 'is defined' or 'is not none' or similar to detect that and provide a default. This ends up being a lot of work to workaround a misbehaving sensor
I wouldn't really say misbehaving - its a plug that I dont always use so sometimes its disconnected and thus unavailable
I was also struggling to see what you did there, until I found out that dict.items() | list includes the keys. 🙂 I thought it would only have the items.
.keys() returns keys, .values() returns values, .items() returns both
But don’t let it fool you, those items are not lists, they are objects
You have to cast them as a list to get list funcs
However most list funcs are present on them with a small set of exceptions
Aaah, right, I mixed items and values.
I already used it in several templates now
I have a quarterly sensor for electricity. Now this just increases every until it resets after 15 mins. But I would like to use that sensor to calculate a quarterly average instead.
1 kWh in 5 minutes -> 3 kWh for that quarter
Is there a way to do that?
I hope this is the right place to ask, and Ill try to make it short.
I have made a covers.yaml file and included it in the configuration,yaml and it works fine, I use it to group up my curtains.
Now i need an automation for my garage door, but when i place the code in covers.yaml then it doesnt accept: platform: template.
And if i put the code in configration.yaml it says cover: is already in use
I am trying to use the code from this example: https://robert.stadsbygd.net/2021/01/23/home-assistant-garage-door-status-with-aqara-vibration-sensor/
~share your code
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://hastebin.com/ (sometimes may not allow you to save)
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.
post your actual error and the code you're using
you're either missing the -'s in your cover file, your spacing is off, or you have cover inside cover
https://paste.debian.net/1226177/ and the error in the log is: Invalid config for [cover.group]: [cover] is an invalid option for [cover.group]. Check: cover.group->cover. (See /config/covers.yaml, line 15). Please check the docs at https://www.home-assistant.io/integrations/group
17.19.35 – (FEJL) config.py
If that's the contents of covers.yaml, then it's what petro said: you need to remove cover: and realign what's under it
@short magnet Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.
2 issues, you're pasting the word cover inside the cover.yaml. You don't need to specify it, that's already specified before the include. Second, you're - and acompanying fields aren't aligned in the yaml.
good rule of thumb: Don't copy and paste blindly.
Hmm it blocked my picture, but i get this error when i remove cover: https://paste.debian.net/1226179/
Well thats why i am asking here, im very VERY new to this
because the indentation is wrong
look at the previous section
then look at the one you're adding
it looks like this
- platform: ...
otherstuff: ...
- platform: ...
otherstuff: ...
- platform: template
otherstuff: ...
see how that's wrong?
all the platforms and other stuff should have the same indentation
@short magnet did you die
By bad indentation. Must be a first
🤷♂️ I'm guessing he's confused an afraid to talk because my example of bad indentation is less complex than what he has
Sorry, the wife made pancakes... ill try to fix the indentation now
https://paste.debian.net/1226189/ this is the error now, and Studio Code Server doesnt show error anymore, but when i reload, the log throws this: Invalid config for [cover.group]: [cover] is an invalid option for [cover.group]. Check: cover.group->cover. (See /config/covers.yaml, line 15). Please check the docs at https://www.home-assistant.io/integrations/group
are you sure that error isn't old?
Post your entire cover.yaml file
that's telling me that cover is still included in the previous item
And your indentation still appears to be wrong
Please align icon_template properly
The whole section is 2 spaces too far to the left
Looks better. Does it work?
Theres no more errors now, now i just cant find the right entity to add to lovelace
Should I use name: instead of friendly_name: ?
like I do with my curtains above
Should clicking the reload "GROUPS, GROUP ENTITIES, AND NOTIFY SERVICES" button in the settings menu work, instead of a restart?
There's also a template button in the reload. I though he also made a new group.
Ahh. I'm just trying to understand when those reloads can/can't be used. I seem to have trouble with them sometimes.
If there isn't already at least one template in the system or advanced mode isn't enabled, it won't be there
Well im a fucking moron. Restart fixed all. thanks alot for all the help and especially the patience
Next part is to figure out why the icon doesnt change :)
Made some new template sensors. friendly_name: is not a valid option. Any alternative?
name:
Ok, thanks! My sensor.abc is based on the name: abc so if I change the name, my sensor name will also change I guess. Have it used on many places... Any clever 'mechanism' to discover where it is used in HA?
{% if state_attr('binary_sensor.garageport_vibration_sensor_vibration', 'orientation')[2] | int > 0 %} im guessing the state it tries to read is orentation, but i want it to read angle_y - i am unsure what the [2] after orientation does
I wanted to change it to {% if state_attr('binary_sensor.garageport_vibration_sensor_vibration', 'angle_y') | int < 7 %} but there i dont have the index
yay, it works, thanks again
np. You need to look at the attributes to know how to access them
I'm trying to get milight remote controls to control my Hue lights. I've got an esp8266_milight_hub set up and I've integrated it into HA via MQTT which is working fine, but the entities appear in HA as lights and I'm struggling to wrap my head around how to control lights in another integration using their state. Is this a use case for templates? Or is there some easy way of doing this that I'm missing?
I could build a bunch of automations to update the state of the hue lights every time the state of the MQTT lights changes but I feel like there has to be a less clunky way of doing this
So you want to trigger on some number of remote controls and each should control a light?
the DIY hub is basically listening to the radio traffic, normally the remote would be paired with a light. In the hub I can define devices for each device ID and group number, and these will appear in HA as light entities via MQTT, but there's no actual bulb paired so I end up with a light entity whose state changes when I use the remote control
There's an MQTT forwarder automation in the documentation (https://github.com/sidoh/esp8266_milight_hub/wiki/Using-Milight-Remote-with-HomeAssistant), I think I need to use something like that but I feel like there's an easier way that I'm missing
The easiest way to do that is to trigger on a list of light entities and use names for the remote lights and real lights that are easily translated. Then you construct the real light from the entity that triggered
Thanks for the template, i have had some time to try it and i am getting the sensor events to work, but the garage_door template sensor only changes from closing to opening state. can this be as i did put in 2 diferent .yaml files as i have splited the config file and using template: !include_dir_list do it need to be in the same file?
{{states.sensor.new_movies.entries | map(attribute='title') | list | join(', ') }}
I am trying to grab the 'title' value from my attributes from my sensor but unable to.
Can someone point me to the right direction?
the sensor is an rss feed from my Feedparser HAC integration.
How do I get the creation time of a persistent notification entity? "created_at" does not work even though that is what it seems like it is in the source.
Got it. last_changed
What exactly do the attributes look like? Do you want the title from every element in a list?
If so:
{{ state_attr('weather.wf_udp', 'forecast')|map(attribute='temperature')|join(',') }}
Or for you:
{{ state_attr('sensor.new_movies' , 'entries') | map(attribute='title') | join(', ') }}
I guess it somehow wrong(ish) place but a problem with Template Editor under Developer Tools: on different PCs contents is different, can we sync it somehow to allow working on same entries from different sessions?
No, the data in different browsers is stored by the browser.
Thanks, so save snippets to cloud and reuse at another location 🙂
Hi there, I consider myself still a beginner of HA. I got the following log entries. Can I find out somehow where to look for the source that I need to correct (e.g. cast)? There are no more hints in the log file...
2022-01-07 13:01:24 WARNING (MainThread) [homeassistant.helpers.script] Error in 'choose[1]' evaluation: In 'template' condition: TypeError: '>' not supported between instances of 'str' and 'int' 2022-01-07 13:08:17 WARNING (MainThread) [homeassistant.helpers.script] Error in 'choose[1]' evaluation: In 'template' condition: TypeError: '>' not supported between instances of 'str' and 'int' 2022-01-07 13:09:10 WARNING (MainThread) [homeassistant.helpers.script] Error in 'choose[1]' evaluation: In 'template' condition: TypeError: '>' not supported between instances of 'str' and 'int'
I even don't know what to post here as the error in the log is very generic. Is there a way to see more in the logs, e.g. which script/automatisation is executed before / after?
you have a condition thats checking if a string is greaterthan an int
most likely states('something.something') > 8972
@mighty ledge Yes, I can see that in the log and I need to change that. But how do I find out where to look?
read the error like a sentence
it points to 2 things that should stand out to you. can you identify them?
@mighty ledge I will search in the HA files for that...
keep in mind, the starting number inside the brackets [] starts at zero
so the [1] indicates the second condition
well, second choose path
@mighty ledge: OK so in YAML I should look for a "- condition: template"...?
I looked after that and only found (states('something.something')|int)
yes, in the second -conditions: on a choose
choose: <---------- YOUR CHOOSE THAT IT"S CALLING OUT
- conditions: <------------ FIRST ITEM IN THE CHOOSE, START IS INDICATED BY the -
- blah
sequence: <----------- THIS IS STILL PART OF THE FIRST ITEM BECAUSE THERE IS NO -
- blah
- conditions: <------------ SECOND ITEM IN THE CHOOSE, START IS INDICATED BY the -
<-------------------------- HERE
is also good to use alias
no alias's here, hard mode all the time
instead of starting an item with -condition
start with:
choose:
- alias: 'bla bla'
conditions:
- first cond
....
sequence:
this works and also will show in debugger what alias was executed
simple example would be:
action:
- choose:
- alias: 'during night select silent profile'
conditions:
- condition: time
after: "00:00:00"
before: "07:59:59"
sequence:
- service: ....
default:
- alias: 'in rest of the situations select Auto profile'
service: ....
@slate tundra, @mighty ledge Thx. Will look for that...
Got it, it was in a blueprint I made...
After restart it seems to be gone...
Thx!
2021.10 brought changes to templates, which will be enforced in 2022.2. You can read more about them in https://community.home-assistant.io/t/updating-templates-with-the-new-default-values-in-2021-10-x/346198
So I read in #automations-archived that there's going to be breaking things in 2022.2 re templates ? Is there more info on this somewhere, I'd like to read up on that.
oh...that timing tho.
Disappointed in you @mighty ledge - you never even pinned a link to the article you wrote
Lol, I did!
check out the 4th pin 😉
Is that what that means 🤔
I can edit that pinned message to have a better phrase
Yeah, that'd help. I know it means something to you, but ...
I tried to keep the phrases short for mobile
We need a link shortener for HA 😄
what if you're not confused by default but you don't know what it does
I'm just permanently confused
that's called early onset Alzheimer disease
That's just being confused in general
that's usually the case in templates
so, start top down with the pins 😉
Early? I was born that way 😄
Will the Check Home Assistant configuration add-on throw warnings about the templates that are impacted with this default thingy ?
🤷♂️
most likely no
if the template is correct, but the resolution only fails when the conversion fails, it won't show up
Do you understand what |int and |float are doing?
they convert a string to an int or a float
but what happens the value of your sensor is "HEY MY NAME IS TOMMIII"?
and you convert that to a float or an int?
what would you expect?
it'll say warning : unwarranted use of all-caps.
nope, it'll just result in that warning about missing a default
when conversions fail, default is used
It ought to return a value that corresponds to the conversion...
if you don't provide a default, it bitches
read the post 😉
if you understand the code, you won't need an example explicitly calling out int
because they are all the same
will be getting heavy use.
you can do a simple find and replace
that's all I did
well, I did update a few templates to actually use default to catch bad info. But other than that, find/replace and you're done
int -> int(default=0)
I was using the following to get my nuc's uptime.
{% set d, h, m, s = states('sensor.intel_nuc5i3_system_uptime').split(':') | map('int') %}
{{ as_datetime(states('sensor.date_time_iso')) - timedelta(days=d, hours=h, minutes=m, seconds=s) }}
But for some time it's not rendering anymore. now i get this warning and shows Unknown instead of time.
sensor.template_intel_nuc5i3_uptime rendered timestamp without timezone: 2021-12-30 08:28:38
how can i solve this?
put a timezone on your docker container
That works! Thank you!
So, Im perhaps totally out of my depth here, but Im trying to write a command_line switch to test of a service is up and running by running some JSON queries via curl. I've got the queries setup and the service returns "READY" as a responce when its up and running, but Im rather confused what Im supposed to put in for the value_template to read and parse that in a way that HA will understand
https://pastebin.com/E8bgvuDK - this is what Ive got so far but.. nots ure if its right or not
is the total response from the command just "READY"?
Yup.. # curl -X GET -H "Content-Type: application/json" -H "Authorization: xxx" http://xxx/api/v2.0/system/state "READY"
what happens if the state of the switch is off?
Hm, nothing.. It would be powered down and unable to respond
ok, so in that instance, what does that command return
It'd return nothing, just a http time-out I'd imagine
well, that's what you'd want to find out
cause that'll all be for nothing if you can't template off the command
{{ value == 'READY' }}
Becaue this is controlling a physical PC, if its 'off' then.. its never going to return anything because its actually off, I guess I could read the state of the machine from IPMI (which is what Im doing to turn it on) but..
(If the damn ipmi did a APCI shutdown this would be much simpler :D)
You could also just use a device_tracker home/not_home for the pc on your network if your router is connected to HA via an integration
either way, it's a polled state, so it won't be live
you could also leave it out all together and just have the on/off commands
Hm, well I tried changing the value template to just {{ value = 'READY'}} Im not getting any errors in the log.. but its also not reporting the state of the machine correctly either
do I not need some way for HA to tell when the machine is actually on though?
only if you want to condition off it
if you don't care, you can just have the on/off commands
either way, it's polled
so the state will be out of sync until it's polled
polled means HA is asking what the state is
not it telling HA what the state is
How often will it poll by default? I'd want some feedback to know if this service is running or not
30 seconds IIRC
Even something basic like.. 'does it respond to ping' would do? If that's easier
yes but pinging is also polling
I dont mind if its 30 seconds behind, as long as it updates within a few mins I'd be content with that
then anything you can dream up can be in that value template
it has access to the entire state machine
Im sorry, Im not following. Presumably 'value_template' must have some connection to the command_state Im running, so HA knows what to do with the answer its getting?
The command is run every 30 seconds
value_template represents the state of your switch
true or false
when the command run, value_template runs
templates in general also update whenever anything used in the template updates
so if you can come up with a way to let your switch know through the state machine by attaching it to HA... IP sensor, something your PC runs, etc, then you could get faster updates
templates are templates, they behave the same way everywhere
but if you were to go the route where something else is creating the on/off state of that virtual switch, I would change to command_line services with a template switch
... right because.. Unless Im reading what you are saying here wrong, thats not what the docs say?
If given, this command will be run. Returning a result code 0 will indicate that the switch is on.
value_template string (Optional)
If specified, command_state will ignore the result code of the command but the template evaluating to true will indicate the switch is on.
then you can use an automation trigger to trigger it
you're not understanding what's written there
that's saying exactly what I said
Ok, so in thsi context.. 'value_template' can be true or false, but where does it get the data from for its evaluation? I took it to read that it could take the result of command_state? but.. thats not the case?
okay.. so if command state in this context returns READY, what would I need to template that to read that state, and return 'true' if that is the value, and false if its anything else? 😄
i've already given you that
{{ value == 'READY' }}
value is what comes from command_state
Yeah, except that doesnt seem to work, Im not getting any errors but HA is still reporting that the switch is 'off'
if that's not working then your command doesn't send just "READY"
you can try
{{ "READY" in value }}
(As an aside, is there way ot test/update this code without rebooting the entire HA instance as its pretty slow)
"READY" in value works 🙂 it's now returning 'ON'.. how odd!
maybe its returning a linereturn or.. something daft..
🥳
it's probably a line return, usually is the case
sometimes it's a special char in front that's not visible
But yeah, all seems to be working a treat now, state is returning correctly and the on/off works fine, Thank you for the assistance 🙂
Guys after restart ONLY of home assistant I am getting the following error messages
2022-01-07 21:38:17 WARNING (MainThread) [homeassistant.helpers.script] Error in 'condition' evaluation:
In 'template' condition: TypeError: argument of type 'NoneType' is not iterable
You're iterating over something before it exists
a for loop
it's in your condition
gotta find out which condtiion, but that should narrow it down.
it says in your error
I have a lot if if conditrions in script.yaml but thye work just fine
see my previous responses
Is it also possible to randomize the order of the elements in a list? How does one accomplish this with the template? Never mind... I was able to do it with {{ state_attr('sensor.new_movies' , 'entries') | map(attribute='title') | random}
ok moving my issue from #automations-archived to here since this is mainly a templating issue..
{{ ( states.input_datetime.zoe_last_fed.attributes.timestamp | timestamp_custom('%H:%M', False)) }}
so if I pop this into the template editor it spits out 22:22 which would be 10:22PM however the acutual value of states.input_datetime.zoe_last_fed.attributes.timestamp is 1641594123 which is 2:22PM – where are those 8 hours coming from? lol
Time zone?
shouldn't setting the TZ in HA config be enough? 🤔
Sometimes things are quirky and don't have time zone attached to times
Causes them to go into utc time. You can quickly verify that by checking your utc offset
ah.. so it seems timestamp_custom is coercing my timestamp to the wrong time zone
And you're passing False, which means 'not local time'
thank you for pointing that out.. timestamp_local is what I'm looking for? just as you sent that I finally found the docs I was looking for. so things like timestamp_custom are custom filters provided by HA for jinja? i was looking for jinja docs to tell me what that boolean arg was for
or duh, timestamp_custom without the 3rd argument 🔫
Or that
awesome – taking my full paternity time to learn to speak HA/Jinja lmao.. thank you guys.
if there a way to write else if within this block? say I wanted another condition to be evaluated within this --> {{ 1 if is_state('light.study_light','on') else 2 }} Currently it only allows else
You sure?
when using a ternary statement, you can just add another condition after the else. See https://www.kite.com/python/answers/how-to-perform-a-ternary-if-elif-else-statement-in-python
{{ 1 if 2==3 else 3 if 2==3 else 4 }} -> 4
thanks. I was just adding else if earlier 🙂
{{ as_local(as_datetime(states('input_datetime.dishwasher_program'))).strftime('%H:%M') }} this will work if you change it to your input_datetime
@red gale
Thanks for the reply! So many different ways to do things in HA lol.. my automation is triggering now that I dropped the falsey local time value
You can also use .time() at the end, but that will include the seconds
resource: https://api.airvisual.com/v2/city?city=......
method: GET
value_template: '{{my_test_json["data"]["current"]["pollution"]["aqius"]}}'
name: "Air Quality Index"
scan_interval: 1800```
I'm writing this rest sensor, how do I set the value I'm getting from this to attribute and set custom names like Healthy, Unhealthy to the state?
Like if value is
0-50 then good
else if
51-100 then moderate
else if
101-150 then Unhealthy for Sensitive Groups
etc...
exactly how you wrote it out there, with proper jinja notation
there's thousands of examples that show you how do to if statements and check values against other values
Yes I've got it to work
@gleaming eagle posted a code wall, it is moved here --> https://hastebin.com/asadofajix
is there a better way to do?
Nope, that’s good
Can anyone give a hint how to add this in a seperate file? I have a packages folder with yaml files included but if i add this template to my garagedoor.yaml i get this error.
Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/packages/garage.yaml, line 6).
- trigger:
platform: event
event_type: zha_event
event_data:
device_id: xxxxxxxxxxxxxxxxxxxxx
command: Tilt
binary_sensor:
- name: garagepoort
state: >
{% if trigger.event.data.args[0].degrees|float > 0 %}
on
{% else %}
off
{% endif %}```
you currently can't use that template format in packages
Thanks RobC 🙂
Just pasted it to configuration.yaml but after a restart i don't get a binary_sensor?
your indentation is wrong too
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
- HAOS & Supervised use
ha core check - Container uses
dockercommands - Core requires you to activate the venv first
Just noticed that, but the strange thing is it passes the config check?
Oh, didn't know the UI config check is not reliable
Fixed the indentation but still no sensor?
it's not bad YAML syntax, but it's not valid for HA
- trigger:
platform: event
event_type: zha_event
event_data:
device_id: xxxxxxxxxxxxxxxxxxxxxxx
command: Tilt
binary_sensor:
- name: garagepoort
state: >
{% if trigger.event.data.args[0].degrees|float > 0 %}
on
{% else %}
off
{% endif %}```
still broken
Whut? 😐
compare with the example: https://www.home-assistant.io/integrations/template/#trigger-based-template-sensors
Thanks 🙂
You can also set your template to just {{ True }} and use auto_off
Is there a way to pull the full title as a state attribute please? https://i.imgur.com/UHIy4S5.png
{{ state_attr('sensor.tautulli','mbridges88') }} Pulls the activity and full title but I am just after the full title for that user
I don't have any like that, but either {{ state_attr('sensor.tautulli','mbridges88.full_title') }} or {{ state_attr('sensor.tautulli','mbridges88').full_title }} or {{ state_attr('sensor.tautulli','mbridges88')['full_title'] }} should work if it's really a dict
I have one that looks like that, but it's really just a big string
If I'm making a JS template to display the brightness attribute of an entity, is there a way to use a generic variable like "this.entity_id" within the template so I don't have to update the entity per card?
This is the template I'm working with
label: | [[[ var bri = Math.ceil(states[this.entity_id].attributes.brightness / 255 * 100) + "%"; return bri; ]]]
Depends the card it’s going into
button-card
It just returns [object Object] and I don't know how to convert to an entity_id
it’s the state object
So if you want state it would be entity.state
If you want the entity_id, what would it be?
It would be entity.entity_id, thank you for pointing me in the right direction!
Thank you for this! Was able to get it working with the second suggestion
how can I write a template that takes the average of all the temperature sensors (or a subset from a list). Is there a sum() or mean() function equivalent I can use?
Yes
Jinja Template Designer Documentation
For more examples and samples, visit see this page.
{{ [states('sensor.xxx'), states('sensor.yyy')]|map('float')|sum }}
{% set sensors = [states('sensor.xxx'), states('sensor.yyy')] %}
{{ sensors|map('float')|sum / sensors|length }}
so I can create a list wrapped n brackets like python, get the sum, then divide by len(list) or something?
beat me to it 🙂
could I use a for filter to define sensors
there isn't a for filter
what are you trying to do with that?
generate the list based on some criteria?
yes
like what?
get all the temperature sensors
what makes a temperature sensor unique?
unit of measurement?