#templates-archived
1 messages · Page 31 of 1
element 0 of the list is the dict, so grab the dist and pull temp out of it
oh
that IS what you posted above
yes
but keep in mind, I added another field
json_attributes_path: '$.0'
you need that for attributes
to work
wonderful, this works perfectly
thanks so much for your help, i'm going to go mail my computer science degree back to the school now, this seems very obvious now that you've explained it.
@mighty ledge I was looking at your post about finding the next dst, and I understand what you are doing
I was able to remove the need for the first macro
{%- macro is_dst(t) %}
{{- t.timetuple().tm_isdst != 0 }}
{%- endmacro %}
{%- macro finddst(t, kwarg, rng) %}
{%- set ns = namespace(previous=is_dst(t), found=none) %}
{%- for i in range(rng) %}
{%- set ts = t + timedelta(**{kwarg:i}) %}
{%- if ns.previous != is_dst(ts) and ns.found is none %}
{%- set ns.found = i %}
{%- endif %}
{%- endfor %}
{{- ns.found }}
{%- endmacro %}
{%- set t = now().replace(minute=0, second=0, microsecond=0) %}
{%- set d = finddst(t, 'days', 366) | int - 1 %}
{%- set h = finddst(t + timedelta(days=d), 'hours', 25) | int - 1 %}
{%- set m = finddst(t + timedelta(days=d, hours=h), 'minutes', 61) | int %}
{{ (t + timedelta(days=d, hours=h, minutes=m)).isoformat() }}
but I can't understand why you can't replace is_dst(t) and is_dst(ts) with (t.timetuple().tm_isdst != 0) and (ts.timetuple().tm_isdst != 0)
when I do that, it will give yesterday as next dst
is that my original template?
DST is really stupid btw
If I remember correctly, I had to jump through hoops for DST to work year round
as the check stopped working when DST changed
no, that's my version in which I removed the first macro
maybe that first macro is needed to let it work year round, as the DST starts end of this month over here
yes pretty sure it was that
that's what I currently use
the tm_isdst does not work year round
it was something like that
whatever the problem was, it was annoying and I had to go back to the drawing board when DST changed because it messed up
but I don't think I tried the timetuple
so tha tmight be a way around that stupid macro that I wrote
does seem to work though
it probably will over .dst()
{%- set t = now().replace(minute=0, second=0, microsecond=0) %}
{%- set d = finddst(t, 'days', 366) | int - 1 %}
{%- set h = finddst(t + timedelta(days=d), 'hours', 25) | int - 1 %}
{%- set m = finddst(t + timedelta(days=d, hours=h), 'minutes', 61) | int %}
{% set t = (t + timedelta(days=d, hours=h, minutes=m)) + timedelta(days=1) %}
{%- set d = finddst(t, 'days', 366) | int - 1 %}
{%- set h = finddst(t + timedelta(days=d), 'hours', 25) | int - 1 %}
{%- set m = finddst(t + timedelta(days=d, hours=h), 'minutes', 61) | int %}
{{ (t + timedelta(days=d, hours=h, minutes=m)).isoformat() }}
I applied it 2 times like this
well, just so you know, testing it with a timedelta isn't going to work
because time is oh-so-over-fucking-complicated
grabbing a date during DST actually changes the underlying datetime object when you're in DST vrs out of DST
and the only thing you can do is wait until DST is applied for you to check the code
Well, I can't get it to work anymore, so I believe you that all 3 macro's are needed to have it span years
🙂
and that time is oh-so-over-fucking-complicated 🙂
It took some time to come up with it, and I remember I was annoyed with the outcome of my really long macros
yeah, I understand why you put it in a trigger based template sensor, you don't want this to run every minute
yeah, it's super heavy
as a calc
we really just need a DST integration
I don't know how the code can be simplified tho
as DST is handled really oddly as a flag
I remember why i had to do the stupid for loop too
because some guys DST started at 1:05 instead of 2:00 like most of the world
so I had to search for the minute instead of the day
basically the code adds a time increment and notes when the DST offset changes. Then, when it finds it, it 'increases' the resolution until we get the exact second it changes
starts on days, then hours, then minutes, and I think seconds after that
oh, no, just minutes
How would I dynamically either merge these 2 lists or only have - foo .
https://dpaste.org/Ur9oG
Essentially with Jinja how would I generate those 2 being combined to produce that output.
But is it possible lol?
yes
and only myself, thefes, or rob would probably be able to help
it's probably the most difficult thing to do in templates atm
so what do you expect the outcome to be of that merge?
santa:
- foo:
name: test
type: disk
size: 100
world: test
?
Oh I worded it wrong
The output is what I put in dpaste
That would be the expected output.
If I want both lists of dicts
If I want only the
santa:
- foo:
name: 'test'
type: 'disk'
For example that's another possible output
2 output possibilities.
santa:
- foo:
name: 'test'
type: 'disk'
Or
santa:
- foo:
name: 'test'
type: 'disk'
- type: 'disk'
size: '100'
world: 'test'
I just don't know how to construct that dynamically with Jinja.
YOu're going to need to explain the situation alittle better because constructing that information depends on the input information and what you currently have
I can write an example, but I can almost guarantee you won't know how to use it in your situation
espeically if the dictionaries themselves are dynamic w/ their keys
I think I could figure it out once I see an example. Those are just arbitrary values in my examples but the inputs are static names and not dynamic.
{%- set ns = namespace(items={}, spool={}) %}
{%- set fmat = "('{0}': {1})" %}
{%- set items = (switches or []) + (lights or []) %}
{%- for item in items %}
{%- set state_obj = expand(item) | first | default(none) %}
{%- if state_obj and state_obj.domain in ['light','switch'] %}
{%- set domain = state_obj.domain %}
{%- set entity_id = state_obj.entity_id %}
{%- set entity_ids = lights if domain == 'light' else switches %}
{%- set current = settings[domain] %}
{%- set current = dict(current, **settings[entity_id]) if entity_id in settings else current %}
{%- set key = domain ~ '_' ~ current.items() | list | string | lower | regex_findall('[a-z0-9_]+') | join('_') %}
{%- if key in ns.spool %}
{%- set ns.spool = dict(ns.spool, **{key:ns.spool[key] + [entity_id]}) %}
{%- else %}
{%- set ns.spool = dict(ns.spool, **{key:[entity_id]}) %}
{%- endif %}
{%- set entity_ids = ns.spool[key] %}
{%- set current = dict(domain=domain, **current) %}
{%- set current = dict(current, entity_id=entity_ids) %}
{%- set ns.items = dict(ns.items, **{key:current | string}) %}
{%- endif %}
{%- endfor %}
[{{ ns.items.values() | unique | sort | list | join(', ') }}]
that's an example
that uses all 3 methods of dynamic keys
in a list
here's another one
cycles: >
{% set rollup = current_cycles + [ next_cycle ] %}
{% set ns = namespace(ret=[], attrs=[]) %}
{# setup durations for phases #}
{% for i in range(rollup | length) %}
{% set attrs = rollup[i] %}
{% set next_attrs = rollup[i + 1] if i + 1 < rollup | length else {} %}
{% set ns.attrs = attrs.items() | rejectattr('0','in',['duration', 'action']) | list %}
{% set duration = (next_attrs.start | as_datetime - attrs.start | as_datetime).seconds if next_attrs else 0.0 %}
{% set ns.attrs = ns.attrs + [('duration', duration)] %}
{% if attrs.phase == 'on' %}
{# on state, try to find phase #}
{% set l, u = current.final_spin.duration - current.final_spin.window, current.final_spin.duration + current.final_spin.window %}
{% if l <= duration <= u %}
{% set ns.attrs = ns.attrs + [('action', "finish")] %}
{% else %}
{% set ns.attrs = ns.attrs + [('action', "spinning")] %}
{% endif %}
{% else %}
{# off state, do not collect phase #}
{% set ns.attrs = ns.attrs + [('action', "idle")] %}
{% endif %}
{% set ns.ret = ns.ret + [dict(ns.attrs)] %}
{% endfor %}
{% set last = ns.ret | list | last | default(idle) %}
{% if ns.ret | length == 1 and last.phase in ['off', 'idle'] %}
[]
{% else %}
{{ ns.ret if 'finish' not in ns.ret | map(attribute='action') else [] }}
{% endif %}
from https://github.com/Petro31/home-assistant-config/blob/master/scripts/washer_dryer.yaml
@silent vector ^
Checking it out now. Pretty cool Jinja 🧙
the second example isn't great, but it uses it for next_cycle and it's way over complicated for what's actually needed
Thank you I will play around with this
you're welcome
@silent vector the first one is the only example where i'm creating dynamic dictionaries of information in a list using lists of other information
Yep that works. Problem is, what if I dont know what "Value1" is? 🙂
hi all, I'm trying create a weekly (or monthly) average sensor BUT I do not want the average to include when the sensor is 0....does this makes sense I can explain what I'm trying to do if it does not make sense
If you don't know what it is, how do you know if you want it?
If its there, I want it. But its the "id" of Value1 that matters
So your example has multiple ids. which one do you want?
yeah, you probably need a foreach loop over each of the keys in the dict, then find the one with the greatest added time, and grab the id of that
But basically the thing to know is that state_attr() will return the whole dictionary, and then you can use whatever code you need to operate on that
Hello hello, is there anyone around that wants to help me with a few template questions?
ask away
Can anyone help me with a template to calculate a battery state of charge percent to batter time to 0 or battery time to 20%
Not sure how you'd be able to calculate that. There's not enough information.
Hi, im trying to make a value template for a custom switch but its not working as expected
{{ is_state('sensor.f1', 'running') }} returns False
{{states('sensor.f1')}} while this returns running
Why isn’t the top one true?
huh, weird
does the state include a trailing whitespace or something? I don't have any other ideas :\
It shouldn’t
But it might, its a sensor for a rest api i created in python and i couldnt use an if statement there aswell
If I set my state to "running " I get False/running, and if I set it to "running" I get True/running. So it could happen in theory
What does this return
{{ states('sensor.f1') | trim == 'running' }}
Ofcourse, theres a zero width invisible character behind running. I told python to remove one character and the word didn’t change. Its working now
Thanks guys, wouldn’t have figured it out without you
Is the Android template widget read only or can you include buttons in it that change state? I basically want to just put a mobile dashboard I made on my home screen and it looks like templates are the only way to do it.
Hello, So, I am having a fun time with the imap_email_content sensor. Overall goal, I'm trying to extract a number from an email and set it as the value of a sensor to a helper (or a template sensor?). I have the template code that works to extract the number out of the email, but when I put it into the template sensor the sensor doesn't update and stays as unknown.
thats weird I restarted the server and the sensor updated with the extracted value from the email for a second and then flipped to unknown. and when I goto the history of the sensor it shows the value I'm looking for, but the sensor state is unknown
weird after sitting for 5 minutes its updated now.
It looks like something is causing the startup to be very slow, and it appears my sensor doesn't initialize until HA has finished starting up
Hey I am wanting to have an automation announce when someone has entered/left a zone on a google hub how do I get TTS to say the person's name and the zone they entered/left I was told to use a template and I'm assuming I just have all my people inside one template person and when one of them changes it makes the template equal them and that state change will trigger the automation the problem is I don't know how I would go about doing that
trigger:
- platform: state
entity_id:
- person.john
- person.jane
to: ~
action:
- service: tts.google_translate_say
target:
entity_id: media_player.livingroom
data:
message: >
{% set name = states[trigger.entity_id].name %}
{% set action = 'left' if trigger.to_state.state == 'not_home' else 'arrived_at' %}
{% set zone = trigger.from_state.state if trigger.to_state.state == 'not_home' else trigger.to_state.state %}
{{ name }} {{ action }} {{ zone }}
how can I make this - less than '20' for 5 minutes?
wait_template: "{{ states('sensor.couch_smartplug_watts')| int < 20 }}
Error rendering data template: UndefinedError: 'trigger' is undefined
that error makes no sense for what thefes posted, it's either unrelated or you copy/pasted the automation incorrectly.
or you're clicking the 'test' button for the automation, which wont work because there's no trigger
im just trying to test the actions
right, see my last message
there's a typo in the template as well. trigger.from_state.staet should be trigger.from_state.state
@brittle socket see this, test actions won't work.
ok ill try spoofing my location on my phone to see if it works
Just make sure you fix the typo...
yea i did
Which typo? 😉
I just accidentally found a script where I didn't end the service template with an {% else %} ... as it is a practically impossible task to manually go through all of my yaml files, I wonder if we could have a smart search for that somehow?
above issue hadnt hurt in the past, because any/all of the possible states we're included in the if and elif's, but still, I dont like the templates dangling like that .
I’m not sure what you’re even saying here, can you post the full template
no, it's not about a specific template. I was looking for a way to check all templates in the config, for a missing {% else %}
For a missing else??? Not possible without a crazy regex statement
yeah, thats what I figured.... o well, will check by hand in one of my maintenance cycles...
I know I’ve said this in the past, but I really think you should take a coding class of some sort
Just so you can learn basics so that you understand logic
? I have, and I did, and I have no understanding issues
I just had some older files....
Because having an else or not is 100% contextual and it shouldn’t be something that every template needs. It’s something that you as a template creator should decide for that specific template
look, its more the opposite in this case. just like when you encounter a certain string, and think, hey, where else did I see that. I had that now with this specific template, and figured: I wonder if I have that elsewhere too.
realizing its way easier to search for something, than for the absence of something 😉
Im getting there @lofty mason 😄 Now the automation works if there is only one item in the list.
{{ data.id }}
{%- endfor -%}```
That will return the "id" I need. But if there is multiple items in the list, it breaks ofcourse.
Anyone who knows how I can send tap action from a custom:button-card?
I am trying to send a tap to node red, it works with normal button. But not with custom:button-card. I can hold to get into more info and the press the "press" button and it works. But not when I tap the icon on my dashboard
@rare furnace I converted your message into a file since it's above 15 lines :+1:
I have tried: call-service and toggle
uh your service is wrong
or your entity_id is wrong
input_button services require an input_button entity, and button services require a button entity
entity_id is that the same as the entity?
by using the corect service that matches your entity_id...
and that is?
what's your entity_id?
I feel like you're complicating this in your head
and it's really really simple
for example, if I have an entity called switch.xyz, and I want to turn it on, i use the switch.turn_on service
if i have a light that's called light.xyz and i want to turn it on, i use the light.turn_on service
So, 1: Find your entity_id. 2: Find the service that works with that entity_id that does what you want
in your case it's going to be input_button.press or button.press, depending on what your entity_id is
my entity i want to use is: button.flexit_operating_mode_away
this is a button created in node red
alright, so which service do you want to use then?
I dont know
I just want to toggle it or activate it, not sure if its boolean or a state or something, cant really tell. It just activates a flow
what do you want the button to do?
Just activate a flow
...
I'm trying to lead you to water and I feel like you're not reading what I'm writing
I'm new. I'm sorry.
I have tried looking for the ID, I dont know where to find it.
I tried looking in "entities"
Yeah ok, then my id is: button.flexit_operating_mode_away?
Entity and entity ID is the same?
I guess so 🤷♂️ is that what you see in your frontend?
Yes
click on your entity, there's an info page that will tell you the entity_id
if that's what you see in the frontend, then that's the entity_id
alright, so based on that, what service should you use according to what I said before?
you're using input_button.press
but that service doesn't match the entity_id button.flexit_operating_mode_away
I'm not sure what service I should use. The example i had up there was something I googled and it didnt work
I have tried toggle and it didnt work either
But with regular button created in dashboard I can use "toggle"
did you see this message?
and this?
and this?
Ok, I get it now. It was just button.press, not input_button.press. Thanks
So I was almost there, the service was wrong.
Yes, keep in mind you can view all entities in developer tools -> states page (for entity_ids)
and you can view all services in the developer tools -> services page
right, but using those 2 pages will help you figure out what you can do and how the services/entities interact
Cool. I am also trying to make animations to the button, but the entity im calling the service on have no feedback, can I use a different entity to start animations, change colors etc on the same button?
I have a multi state object I can read the feedback from
yeah you can but you have to use the custom button card templates, which is JS. #frontend-archived can help with that
yeah thats what I'm using
I have been trying out this one: https://community.home-assistant.io/t/fun-with-custom-button-card/238450
Currently i have standard buttons in a container with fan symbol
Oh ok, frontend, noted
all, I'm scratching my head with this one....I'd like to create a sensor that only averages the value of another sensor when its non-zero. Is this possible? Some other members suggest filter and create a new sensor with a filter, and average that, but im not sure if this would work
if I create a low bound filter say of 0.01, does it mean that when the real sensor is 0, will the state be 0.01? because I don't want it to include 0.01 when the real sensor is 0.
i would just use a simple template
{{ expand(['sensor.x', 'sensor.y', 'sensor.z'])|rejectattr('state', 'eq', '0')|map(attribute'state')|map('float', 0)|sum }}
ok, but how do I make this a 30 day average?
Btw, I would move the float so it converts non numeric states to the default of 0, and filter out the 0's
its one sensor, and this is how it looks
https://ibb.co/XzmgmS0
I just want the average when its on (i.e. above 0), over 30 days
How about a template that just follows the input sensor, but with a state trigger of not_to: 0. Then you can use statistics platform on that for average.
i'll work with this {{ expand(['sensor.x', 'sensor.y', 'sensor.z'])|rejectattr('state', 'eq', '0')|map(attribute'state')|map('float', 0)|sum }}
this sounds simpler
im monitoring my HVAC velocity to determine when my filter needs changing. This happens slowly over time, hence the requirement for monthy average. Having 0 in this, would skew the data,
This would mean that for the entirety of the time where it is 0, the template will hold the last non-zero value. I'm not sure if that's the right answer for your usecase, how that will affect the average. Maybe forcing it to be unavailable would be better, but I don't exactly know how statistics handles that. I'll guess it just ignores those points, which may be what you want.
if I create a binary sensor entity, based on 0 or above 0, only when its above zero, inject the data to the long term average sensor...lol
This is where we need my feature request for conditions in trigger-based template sensors
do you have a PR? I can support it!!
No more PRs from me until my 8 month old bug fix PR gets some attention
wonder if there is a way to create a mini-database for this application
this i could use right now!
how is not possible. Im thinking now, I might have to use google sheets (Excel) when value is above 0, and Excel will be the engine and database. Send the data to google sheets and =mean(AX:BX)...if you think about it, it has time and number...surely HA can do all this, but I'm not seeing it.
I've tried to create a template to add gas consumption to my energy management system (already have CO2, Solar, Main import/export, solar array, and battery), though all attempts so far have been unsuccessful.
(what is the link to upload code to, instead of pasting it here?)
ty
This does create the sensor and add the value, though I cannot get the Energy Distribution graphic to show the gas icon and consumption
I've tried several permutations, where device_class=energy, state_class=measurement, etc
The one in the upper right at the demo link https://demo.home-assistant.io/#/energy
Even for gas? The one's I've seen are in ft3 and m3
you have to add that as a sensor to gas consumption that produces kwh
so your device_class should be energy, and the state_class should be whatever the sensor does
then you have to add it to your gas in the energy tab
Why do all the working examples I've seen show m3 or ft3 for UOM?
in their templates?
if that's what gas requires, then that's the units, but kwh will also work
and it should be m3 per hour
energy is a rate over time
not just a value
so to show up in energy, it needs to be an energy
" add that as a sensor to gas consumption" is there something special I need to do for this?
see the blurb?
it describes what you need
also keep in mind that you need to have a history for you to be able to select an entity for gas consumption
Ah yes, how could I have missed that!
And now it shows up!
Now I just have to fix the units.
You've been a big help, Petro. Thanks so much!
Yes, thanks!
In reality, I'm usings propane, measured in gallons, though I tried using "gallons" and "gallon" for the unit of measure, and it never seemed to work. However, my furnace burns propane at 0.8664 gallons per hour. Since the furnace and heatpump measurements are in watts, and the template time defaults to hours, I assumed that it would automatically perform something like an Riemann integral. However, as the furnace has been running for over an hour, it's now show 91.4, so I'm going to have to figure out some other approach than what I have currently
"{{ state_attr('sensor.uren_gewerkt_deze_week', 'time') }}"
Please, what should i fill in instead of 'time' for this to get a returned value?
It's a history stats sensor that i created
To track time at work
Check in developer tools > states
Open your Home Assistant instance and show your state developer tools
But if it is the state of the sensor you are looking for, use {{ states('sensor.uren_gewerkt_deze_week') }}
Thank you sir!
Graag gedaan
Is it possible to hide this for a specific user?
{%- if now().hour < 12 -%}Goedemorgen
{%- elif now().hour < 18 -%}Goedemiddag
{%- else -%}Goedenavond{%- endif -%}, {{user}}
Je hebt deze week {{ states('sensor.uren_gewerkt_deze_week') }} uur gewerkt```
I have this, but my wife also is seeing my worked hours
Probably, which card are you using?
Oh wait
I already see you are using the user variable
{%- if now().hour < 12 -%}Goedemorgen
{%- elif now().hour < 18 -%}Goedemiddag
{%- else -%}Goedenavond{%- endif -%}, {{user}}
{% if user == 'Ziepoeskenetnie' %}
Je hebt deze week {{ states('sensor.uren_gewerkt_deze_week') }} uur gewerkt
{% endif %}
You are the best! Thank you
is possible to change integration name of created sensor in config.yaml, so device from that integration gets assigned this sensor/attribute? Exmple: sensor.light_power which was made in yaml gets assiged as attribute to Device switch.light from different integration
A better question for #integrations-archived but no, only integrations can provide entities to devices.
thx, fixed it by using a different integration
I give up after hours of trying to fix my sum of "sensor.power" entities to exclude entities with "unavailable" states, since some plugs lose connection from time to time and get "unavailable" as power, and then my "sensor.total_power" reports "unknown"
You can use the new sensor group under helpers for that
You r a live saver
all those hours wasted and I had it right in front of my face...
I never tried group helpers. I only used "Combine the state..." helper then I had non-numerical error and went straight to using Conditions with automation...
Are you able to access event data in a template? I'm using fire event in Node-Red thats called WandD, and I'm attempting to use the data in card.
value_template: >-
{% set event_data = state_attr('event.WandD', 'data') %}
Some additional details, I've been trying to do so, but with no success.
I see the event coming in via the developer tools using WandD
event_type: WandD
data:
utcDate: "2023-03-04T16:02:46.000Z"
windSpeed: 0.94
windDirection: 29
origin: REMOTE
time_fired: "2023-03-04T16:02:47.217389+00:00"
context:
id: 01GTPNS19H1JEM0GSSFFAPWGMV
parent_id: null
user_id: ee5ff5714a954a30b260e3d3afc07837
But no matter what I've tried I'm not seeing data in the template.
not like that
but if you have an event trigger, you can use the trigger data
trigger.event.data
Also, if you don't actually have the need for the event, just create a sensor instead: https://zachowj.github.io/node-red-contrib-home-assistant-websocket/node/sensor.html
Well, I'm pretty new to HA. I have a weatherflow device, and it has local network UDP events that sends out updates on wind direction and speed rapidly. So I am trying to create a card that shows wind direction and speed in real time. I'm not sure which would be easier. If I do the trigger approach does the event that I'm sending from Node-Red need to be modified for the trigger to work?
Have you looked at this? https://github.com/briis/hass-weatherflow2mqtt
I don't have a MQTT server on my network, I use ISY and Polyglot. But since I'm using synology docker, I suppose I could add that to the node-red and HASS containers running there. I have had on my list to learn more about MQTT. I'm already working on learning HA and Node-Red and feel like that is going to take a few weeks.
Otherwise, there's this one too.... I'm not sure if that works w/ yours as well, but it appears to be polling though: https://github.com/briis/hass-weatherflow
Yes, that one polls, if I'm not able to get the template to work, then I'll go the MQTT route.👍
I figure if I can wrap my head around the template and triggers, it will translate well to what I have been using for 15 years. ISY from universal devices is a state engine, so triggers is how it works.
Still... I think if you're going to keep the event, you're going to end up writing it to a template sensor to then display on a card, just seems like you could skip that if you're using Node-Red and create an entity directly
I wanted to be able to do that to start with, but I haven't found in Node-red a way to do that.
does node red create the entities on startup? If not, going the template sensor route is the best option as the state & entity will persist on a startup
I appeared they only way to pass data other than boolean, was the fire event.
Ohh...... ok... now I see the light!
Yes I'll try the socket.
To petro's point, I'm not sure how state is restored (or not) upon startup
If it uses websockets, I would assume it doesn't exist on startup
It does have it's own integration though: https://github.com/zachowj/hass-node-red
On the node red front, I just have a flow that used the node-red-contrib-weatherflow-udp and then pass a value via the fire event.
I'm seeing I need to do some reading on this now.
personally, I avoid node red and go w/ just HA
the small headaches that node red produces in the long run aren't worth the fancy graphics
and if you want to do anything complicated, you need to learn JS which is harder than jinja
to me, it makes no sense
Some of the questions being asked are outside of my understanding right now. I like that idea of KISS, but I don't think HA has local UDP integration with Weatherflow.
and then you get to a point where you never understand yaml either, so you are just shooting yourself in the foot
it does...
I definitely don't want to learn JavaScript.
It sounds like there is a weatherflow UDP local network solution for HA, is there?
Sounds like the MQTT route would be the better route for me. Yes, it was. 👍
there was also a custom component at some point that offered direct integration, I think
Ahhh thank you! Yes, that looks like addresses what I was looking for. As I mentioned earlier, there was alot of information given to me, and I needed to go through and do the reading to figure out next steps. Thank you @obtuse zephyr @mighty ledge @marble jackal and @inner mesa
I am using a template that pulls the street number {{ state_attr('sensor.bill','street_number') }} How do I create a blank if the street number is none or N/A?
it will be none in that case, so basically blank
or you do something like this
{% set number = state_attr('sensor.bill','street_number') %}
{{ iif(number, number, 'blank') }}
Would the output be the word blank? What I would like is nothing i.e. a space.
then output ''
Thanks
What would be the suggested method to get a history graph of an entity attribute? Do I create a new entity to contain that attribute, or is there an easier way?
Create a template sensor for it
Ok, as I thought then. Will try that as soon as I get my HA back up. It often crashes when I use Studio Code Server... Maybe time I figure out why.
Probably lack of RAM
Nevermind, IBM error
Dont know where i should ask this... how do i make a sensor (rest sensor?) from this? https://ergast.com/api/f1/current/next
I need the date and time in a sensor for the next race
Hi, pretty new to HA and no coder, been fiddling around with this for a few hours now, to get where i am 😄
My situation,,
I receive dates for my waste pick up by using a HACS integration (RecycleApp), works perfectly.
I want to notify myself a day before.
Maybe this is not the perfect way, then i am open to new ways!
If i would add this code to a card i see the date of today. (because tomorrow is "pmd collection")
{{ (as_timestamp(states('sensor.pmd')) - 1) | timestamp_custom('%Y-%m-%d') }}
So i added this code to my automation.
But does it not pass the condition test.
I feel i need something in front of my code like "now=", or "today=", dunno tbh, tried a few things, but no avail 😄
Does anyone have any experience with this please?
Thank you
How about:
{{ ((states('sensor.pmd')|as_datetime).date() - timedelta(days=1) == now().date()) }}
Will be true from midnight to midnight the day before a timestamp sensor
Gurus, what am I missing here? Shouldnt this return all entities with 'door' in the name and are 'on'?
{% if 'door' in state.name %}
{% if state.state == 'on' %}
{{ state.name }}: open
{% endif %}
{% endif %}
{% endfor %}```
I would say so, but this is case sensitive, could it be that you use Door in the name?
Nah dont think so. Tend to only use lower case. But at least now I know im on the right path 🙂
{% for state in states.binary_sensor %}
{% if 'door' in state.name and state.state == 'on' %}
{{ state.name }}: open
{% endif %}
{% endfor %}
this should work as well
the template works for me (it returns the ESPHome API status binary sensor for my doorbell)
thanks, will give it a shot.
or even this:
{% for state in states.binary_sensor if 'door' in state.name and state.state == 'on' %}
{{ state.name }}: open
{% endfor %}
damn, you makes this prettier for each minute
its interesting. Your last example works as I would expect. Only that it only returns binary_sensors with door as device_class. I have a z-wave contact sensor thats also named door_xxxx but with device_class safety. That one does not show up.
im sure its something on my end. I'll figure it out. Thanks @marble jackal
Are you sure it's a binary sensor?
Hi, i want to write one number into the other, but i always get an error:
data:
value: >-
"{{states("input_number.niedertarif")}}"
target:
entity_id: input_number.strompreis
Fehler beim Aufrufen des Diensts input_number.set_value. expected float for dictionary value @ data['value']. Got None
ah now I know what I was missing. It actually looks at the "friendly name". That why it didnt pick up my z-wave contact. Its called "Yttre altandörr", but the entity name is "door_outside".
Then use state.entity_id
ahhh. Now I feel proper stupid.
can someone help me?
You are using the same type of quotes inside and outside the template
how should i do it?
'{{states("input_number.niedertarif")}}'
"{{states('input_number.niedertarif')}}"
'{{states(input_number.niedertarif)}}'
"{{states("input_number.niedertarif")}}"
nothing worked
The first or the second
Oh wait, you are using the multi line format.
Don't use quotes outside the template then
data:
value: >-
{{states('input_number.niedertarif')}}
target:
entity_id: input_number.strompreis
like this?
Anyone know why I am getting this error after 2023.3 in my logs: 2023-03-05 10:06:16.949 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'None' has no attribute 'battery_pct' when rendering '{{ state_attr('sensor.freezer_sensor', 'data')['battery_pct'] }}'?
This is my template: freezer_sensor_battery: friendly_name: "Freezer Sensor Battery" value_template: "{{ state_attr('sensor.freezer_sensor', 'data')['battery_pct'] }}" unit_of_measurement: "%"
does not work :DD
Could it be due the restart of HA on first pull? I am pulling that data from a rest platform sensor.
Try it in developer tools > templates
Yes, the rest sensor is not available when the template is rendered just after a reboot
Use an availability template or defaults to prevent that
is it possible to use multiple filters in the if statement? Like if 'door' in state.entity_id but not 'contact'
maybe with regex?
That fixed this one error, what about this? 2023-03-05 10:31:22.398 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'None' has no attribute 'last_checkin' when rendering '{{ strptime(state_attr('sensor.freezer_sensor', 'data')['last_checkin']|replace('-00:00Z','-0000Z'), '%Y-%m-%d %H:%M:%S%zZ') }}'
hi there, I'm recently getting over and over error on the Logs page related to template I have.
http://pastie.org/p/4MdSoPO8Y7CeKxdbwbULju
that is the automation which have at the bottom part this template -
http://pastie.org/p/7lsw0MEyDRimseXKTB9avX
Thanks!
P.S the automation working great, but for some reason I'm getting this error on Logs
What's your code now
friendly_name: "Freezer Sensor Last Update"
device_class: timestamp
value_template: "{{ strptime(state_attr('sensor.freezer_sensor', 'data')['last_checkin']|replace('-00:00Z','-0000Z'), '%Y-%m-%d %H:%M:%S%zZ') }}"
availability_template: "{{ states('sensor.freezer_sensor') == 'success' }}"```
You can use regex, but also 'door' in state.entity_id and not 'contact' in state.entity_id
@dense swan availability_template: "{{ state_attr('sensor.freezer_sensor', 'data')['last_checkin'] | default('na') != 'na' }}"
Hello, I have this template for my boiler in the bathroom https://pastebin.com/eABi9K6k
and I want somehow to change this number '65' based on if input_boolean.guest_mode is on or off. If its off => leave 65 degrees, and if its on to increase up to 80 degrees should I set saome variable if guest mode is set to on. and then to create an if statement?
"{{ states('sensor.aqua_ariston_current_temperature') | int > 65 if is_state('input_boolean.guest_mode', 'off') else 80 }}"
It has the same result 🙂
end: "{{ now() }}"```
Is this the correct format for tracking a whole week?
Because my sensor has reset today
I want to track from monday 00:00 to sunday 00:00
My purge_keep_days is set to 10 days
What is "today" where you are? I assume it's not working correctly or you wouldn't be asking?
That seems like it would track from monday 00:00 to monday 00:00
Monday at midnight would simply be
{{ today_at() - timedelta(days=now().weekday()) }}
But what you had should give the same (but then a timestamp)
Very strange it has reset today, huh?
Hi, i just made 2 sensors with scrape to get the info from a website: sensor.f1_date (2023-03-19) and sensor.f1_time (17:00:00Z)
How do i get these in a template condition like now() == sensor.f1_date and now() == sensor.f1_time
Yes, but is has reset today at around 4 pm
I'm in europe
{{ now() - timedelta(days=7) }}
if you want monday to sunday, that's a bit different
what the fes posted
struggling on a comparitor template. the value shows as 0 but this returns false.
"{{states('sensor.tesla_charger_actual_current') == 0}}"
nm made both strings and it worked
yes, all states are strings
How can I use a string value from a value template as part of the broadcast message on tss.google_translate service?
Is there some example of the sintax
Can you give some more insight where this string value comes from, is it the state of an entity
heyo.
I keep getting flooded by this error on the Logs
http://pastie.org/p/6oZy6gWldWbM38dmZzoaNE
Template - http://pastie.org/p/0B8tQmJjH4EsbSzhmLRWrM
Any idea why it keeps appearing in my logs? Thanks!
EDIT: I sent the wrong template before
Because you are trying to convert unavailable to an integer
Is there a way to ignore the unavailable or should I just remove this sensor to fix it?
https://imgur.com/dS3SbS2
These are the attributes, looks like it's not unavailable, but it's on 0.
my guess would be that the templates for the light entity are rendered before the number entity is available
so you will probably see this after a reboot
yeah it's coming right after rebooting
the best way to avoid is, is to add an availability_template on the light entity
oh you already have it
add a check on the number to it
but there already has an availability template
availability_template: "{{ states('switch.hfjh_v2_eadb_fish_tank_2') in ['on', 'off'] }}"
Which only checks on the switch, not on the number
availability_template: "{{ states('switch.hfjh_v2_eadb_fish_tank_2') in ['on', 'off'] and states('number.hfjh_v2_eadb_ledboard_brightness') | is_number }}"
Checked on the devtools it's returning true, is that ok before I change it?
do yo understand what the template is checking?
Yeah, if device is ON/OFF and if the number.brightness has numbers as output and not text such as unavailable
okay, so it return true now?
yeah
okay, then you answered your own question
BTW, what is in that script you are using for the turn_on and turn_off actions
I have a problem with sensor to sum up the kWh from the data provided from zigbee outlet which provides current power consumption.
- platform: template
sensors:
ac_grow_box_watt:
value_template: "{{ states('sensor.grow_box_switch_power') | float | round (2) *0.1}}"
friendly_name: "Grow Box Watt"
unit_of_measurement: "W"
device_class: energy
unique_id: acgrowboxwatt
- platform: integration
source: sensor.ac_grow_box_watt
name: Grow Box kWh
unit_prefix: k
round: 2
unique_id: growboxkwh
{{ states('sensor.grow_box_switch_power') | float | round (2) *0.1}} gives normal output of 3,5 ,but when reading the entity created is "empty" as there are no data accumulated
Got it solved. Thanks
@wicked pasture 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.
- W is not energy, that's power. 2. Mutiplying by 0.1 after rounding effectively removes the rounding. But neither of those points have anything to do with your issue. Can you elaborate on what you mean by "created is empty"?
to clarify point 1, energy is power over time. i.e. Wh or kWh. So, if you are just outputting watts, then the device_class should just be power.
so now i am trying to get rid of everything that i randomly copy pated from the internet 😉 and i tried following this one https://www.home-assistant.io/integrations/integration/ its suppose to be working, so now i have in my sensors.yaml this :
- platform: integration
source: sensor.grow_box_switch_power
name: energy_spent kWh
unit_prefix: k
unit_time: h
round: 2
unique_id: energy_spent_kwh_123
when i go to developer tools-> states and select energy_spent kWh entity i get state unknown and this what i mean by "empty" sensor from my pov
sensor.grow_box_switch_power is returning current power from the zigbeee tuya outlet
is sensor.grow_box_switch_power being recorded by history/recorder? If not, it needs to be.
how to check that?
otherwise, you may have to wait until sensor.grow_box_switch_power has data in the history before it will return a result
you can check that by looking to see if the sensor has a state history
go to the history or look in the more info on sensor.grow_box_switch_power
so i can see a power graph for that sensor
then you have a history and you most likely need to wait for an update
so from what i check in the tutorials it seems to be instant https://www.youtube.com/watch?v=JMEez3qnUEo 😉
ok I will check if this works out if not i will ask again
it'll only be instant if your device has the correct amount of data to create the integration
if you only have 1 datapoint in your database, then you won't have enough data to create the integration
when I say integration i'm referring to the mathematical integration, not a home assistant integration.
if you have alot of data, then you most likely configured something incorrectly. Verify your entity_id is correct as that's pretty much the only thing that can mess up the configuration.
unless you have 2 sensor sections, that could also cause a problem.
@wicked pasture ^
Hi, I am trying to use now() to give me the date but I don't want the time. I've only found now().day, month and year.
How would I only get the date?
.date()
Ah perfect ty
Is there an easy way to filter to lower after a specific string.
For example var is test
all lowercase after matching 'FOO_' so 'FOO_bar' instead of "{{ test | lower }}" which would be foo_bar
Not following you
Is it possible to after a certain string make everything lower
Vs the entire string
If I just do | lower that's the entire string.
But I would rather after a certain point be lower.
is FOO_ always at the start, and always included?
Yep it would be
{{ test | lower | replace('foo_', 'FOO_') }}
Is it also possible to look for _ in case FOO_ is not always at the start?
this wil also work if it's not at the start
Maybe it's FOOEY_
I guess I don't understand why you even want to do this
I'd just split on _ and check the 1st item or 2nd item
If you always want the first part, split on the _
I will try that
well, it needs a lot more code then what I had above
yeah, there's no way to split inline
condition: state entity_id: calendar.arbeit attribute: start_time state: "2023-03-06 14:00:00"
I am trying check if the state is today's date at 14:00:00 and got this:
condition: state entity_id: calendar.arbeit attribute: start_time state: {{now().date()}} 14:00:00
Can I do something like that or how would I format that?
on a generator
you might be able to use regex replace and then attempt to map it to a list
Do you have an example?
{% set test = 'FOO_BAR_BANANA' %}
{{ ([test.split('_')[0]] + test.split('_')[1:] | map('lower') | list) | join('_') }}
FOO_bar_banana
you can't use a template for the state field in a state condition
you need to use a template condition
Hmm thats what I thought but wasn't sure. I'll try to get into it
just make a template condition
{{ state_attr('calendar.arbeit', 'start_time') | as_datetime | as_local == today_at('14:00') }}
Tyvm I'll see if that works for me 🙂
How do i substract 10 minutes from an input_datetime helper. (Time only)
{{ states('input_datetime.date_test')|as_datetime - timedelta(minutes=10) }}
Hi all, I'm using the Torque integration (log car diagnostics to HA). The problem with this integration is that the entities don't survive restart but come back with its history soon as I start the Torque app on my phone. The Spook integration, on every restart, tells me my automation is using an unknown entity as a result. I was hoping a workaround would be to create a sensor based on the Torque sensor, but with an availability template. The state is the state, unless its unknown, unavailable or none...then its just unavailable.
this is so wrong, but its a start
attributes:
friendly_name: "Jeep Gps Latitue"
icon: mdi:jeep
state: >-
{% set latitude= states("sensor.jeep_gps_latitue") %}
{% if latitude = unknown, unavailable, none %}
{{ latitude = unavailable }}
{% else %}
{{ latitude }}
{% endif %}
yes, I would call that sorta pseudo-code
Pseudo-pseudo-code?
just make an availability template
that is what would normally work....BUT Frenck's spook will not like that the automation is using an entity that does not exist
- unique_id: jeep_gps_latitude
attributes:
friendly_name: "Jeep Gps Latitude"
icon: mdi:jeep
availability: "{{ states('sensor.jeep_gps_latitude') not in ['unknown', 'unavailable', None] }}"
state: "{{ states('sensor.jeep_gps_latitude') }}"
I assume the missing "d" was a typo
I don't understand this, or the relevance of it:
BUT Frenck's spook will not like that the automation is using an entity that does not exist
its a long story...but basically the Torque integration is outdated
Ok! I will try this, and yes that was a typo
Is there something that works for just a sensor with just numbers? Im using scrape to get time from a website that sensor is now 17:00.
I like to use that time in an automation but i want to trigger 10 minutes before 17:00
@inner mesa thank you, that worked! Now Frenk's Spook wont warn me every time I restart HA that Torque sensors are missing and the automation should be updated.
use something like {{ today_at(states('sensor.whatever')) - timedelta(minutes=10) }}
Thx ill take a look
Works.. well kinda, 17:00 is now 2023-03-06 16:50:00+01:00. How do i remove the date and +01:00? 😅
you could wrap it around a strptime() function and just output the desired time. https://strftime.org/
That url has the break downs of code to show specific parameters only.
How i add strptime to that? 🫣
Ummm like this
{{ strptime(today_at(states('sensor.whatever')) - timedelta(minutes=10).'%H:%M:%S') }}
Lemme try 😁
Hi guys, next question. So, i have a sensor that is tracking time at work. My boss is allowed to subtract a break legally. This is 30 minutes if i worked between 4,0 - 7,5 hours, 60 minutes if i worked between 7,5 - 10,5 hours and 120 minutes if i worked between 13,5 - 16,5 hour shift. Is it possible to implement this so it's calculated automatic?
That it is automatically pulled off the hours i worked at a day.
Gives an error 🥲
Basic question: would your (!) calculation (whatever it is) be accepted. I mean, you can construct anything where a calc runs in your favor, why would an employer accept this?
Accept what? It is for my own to check if my hours are payed out like they should
You mentioned 'your boss', so why would you need a sensor for this... whatever you register has not real value...just asking
And yes, one can construct a figure based on 'total hours'
I need a sensor to supervise if my boss is paying out correctly. He has his own calculation and I just want to check that. Do you understand?
of course I can ...only that your figures are just a check and your boss always 'wins' (was in similar situation)
How does this sensor work? An input_number that you increment? A template with history_stats?
Try this
{{ (now() - timedelta(minutes=10)).strftime('%H:%M:%S')}}
replace now() with your sensor states.
This is an 'ugly' solution and misses the part between 10.5 and 13.5 which you did not specify...it is readable so paste it into devtools > template an dplay around
{% set day = 8 %}
{% if day > 4 and day <= 7.5 %}
{% set day = day - 0.5 %}
{% endif %}
{% if day > 7.5 and day < 10.5 %}
{% set day = day - 1 %}
{% endif %}
{% if day > 13.5 and day < 16.5 %}
{% set day = day - 2 %}
{% endif %}
{{ day }}
I will be mocked for this 🙃
Nope 😔
you need to covert the sensor state to a datetime
{{ (as_datetime(states('sensor.petunia')) - timedelta(minutes=10)).strftime('%H:%M:%S')}}
Thank you!
Needs to be some version of #templates-archived message because it's just "17:00"
there's some holes in your bosses logic
I'm guessing 90 minutes between 10.5 and 13.5?
Exactly
well that template doesn't cover that
{% set hours = 8 %}
{% if hours <= 4 %}{{ hours }}
{% elif hours <= 7.5 %}{{ hours - 0.5 }}
{% elif hours <= 10.5 %}{{ hours - 1 }}
{% elif hours <= 13.5 %}{{ hours - 1.5 }}
{% else %}{{ hours - 2 }}
{% endif %}
it seems odd that is first duration is 3.5 hours but the remaining is 3
if it was 4.5 starting, then you could make an equation
a one liner
Thanks man, can i attach this to a weekly based sensor?
Hello,
I keep reading template code: …
and card code: …
Where to put the template code?
I know I have to place the card code in an new lovelance element.
you just squanch it into your configuration.yaml file
Thanks 🙏🏼
Is there a way to strip the first 10 and last 6 characters?
if it's a string... blah[10:-6]
Idk, can i put it in this? 😅 {{ today_at(states('sensor.f1_next_time')) - timedelta(minutes=10) }}
For a lot of this, just googling for your question in Python will get you your answer
'How to I get a substring?', for instance. Basic Python
Example: {{ (today_at(states('sensor.f1_next_time')) - timedelta(minutes=10)).strftime('%H:%M') }}
Yea like the other guy said strptime idk, this one works!!
Change your usename pls
"TheHero"
Thanks man.
Output just 16:50 now 🙌
🎉
Is it possible to show icons in the Developer Tools -> Template section?
Hi all
Anybody know how to make this work ?
- type: vertical-stack
cards
- !include ./template/gsp.yaml
- !include
- ./template/gsp.yaml
- name:
entity:
No, the frontend does the conversion from the mdi:icon reference to the actual icon
Is there another facility I can use to mock up what a line with icons and text would look like?
How do I get the description: to show on two lines in the developer services tab of my script? It keeps showing it as one continuous line of text. Tried > , >- and |-. ```
buttonid1:
name: Button ID
description: |-
Identifies the action being returned when the button is pressed.
Use only letters and underscores.
required: true
example: "CLOSE_GARAGE"
selector:
text:
You can use Material Design Icons Intellisense in VSCode
You can't, it strips whitespace
that seems to show the icon next to the mdi text name... how do I show just the icon?
look at the options for that extension
if it doesn't have an option to do that, you can't do that
As far as I know only the HA frontend replaces the string with the actual icon as already said by @marble jackal. Any editor/dev-tool will also show the original string
doesn't really serve my need/answer my question then..
not sure how it doesn't though if it shows both the text and icon...
I want icons with other text, not the text of the icon name.
That can work with emoticons https://emojipedia.org/. Or you will need to change the html/css directly to use mdi icons. But that is not globally supported and can give some weird effects depending on the usecase or will not work at all
You can't do that without using custom cards that accept HTML. The icons themselves cannot be placed into text.
if you're using the markdown card, you can get it to work in-line with text. Also, you can get it to work with custom:button-card as well
basically, it's not easy.
Hi everyone
Anybody can help me make a switch that sends a Google assistant SDK command when I turn it on
Like if I turn the switch on the Assistant gets a command
uh, that's a loaded question
I suggest you use one of the normal routes to connect to google assistant
that means you'll need to expose HA to the internet as well
@tender blade can you expand on what you're trying to do? Did you google SDK or do you actually know what it means?
It ought to be easier. I mean the Developer Tools -> Template section already auto-completes mdi names. There should be a way to spit out an icon in there..
but an icon is not text
it's an image
you can't just put images in the middle of text w/ software without having a method to do so
I think you're confusing emoji's with the icons that HA uses. You can use emojis all day, you can't use HA icons because they are not emojis
in a section on viewed with a web browser, that already shows the icon when you complete the name
yes... and?
that doesn't mean you can put that icon in the middle of a line of text
yes, and what means it can't? I see mdi icons next to text everywhere in HA.
Sorry for the question after I writed it I got it
Yes but that's a specific image element that's literally placed there in code and afixed to that position on the UI
you can't move that icon around your ui
So, I created a boolean switch and when it turns on then it sends a command to the Assistant throught the SDK
I suggest you read up on HTML, then you'd understand because at this point, you're just arguing without having the knowledge to argue.
I know HTML
The commands that are sent to google are done so though the smarthome integration in HA
you can't create custom commands w/ google assistant
<img src=...> text
ok, so try that in a text field
if your source is correct and the UI element renders HTML, it will show up properly
No built in cards (Aside from Markdown) render HTML
so you have to use something custom that renders HTML
You're saying the only way to render a gray rect box is to put it in a <input type=text> box?
and that's why that field can't output an image next to text?
The only way to render HTML in a PREBUILT card in home assistant is to use the markdown card or a custom card that renders HTML that someone else built
It works somehow
if you want to make your own custom cards, you can do that and use any html you want, but you need to use typescript & javascript to get the job done
to use the MDI icons, the html you can use is
<ha-icon icon="mdi:someicon" style="width: 1.4em; height: 1.4em; color: var(--paper-item-icon-active-color);"></ha-icon>
you can change the color to whatever you want, use spans to create sentences and place that in the middle. Again, that can only be done in the markdown card.
(or custom cards that render html)
Yes, those work but the code is buried in the integration I mentioned
So thank you
what exactly are you trying to do? You can expose all sorts of entities in HA to google assistant
you can tie scripts to a switch as well so it can run commands in HA
You can also expose the scripts directly
And call them by start <name> or use them in a routine
They are under scenes
Any body can help me with this? please.
That’s Lovelace gen
Do you know how to use that?
@mighty ledge I got it now, thanks for pointing ♡
sorry, got pulled into a meeting
The yml you provided looked like lovelace gen
if you were just trying to do a normal include, I can help w/ that
Hey, I accidentally put my question about sensors in the wrong channel… if anyone here could help me, I’d appreciate it very much ☺️
You may want to just delete the post in the other channel and edit them into your post here, just to keep everything in one place.
But as to your question, could you elaborate on what "not working" means? HA won't boot? Undefined value? Returns 6 instead of 7? etc.
Alright, thanks 🙂
@crimson token I converted your message into a file since it's above 15 lines :+1:
Okay, so… I tried making the RESTful sensor at the bottom, but it doesn’t show up at all in home assistant. That’s the issue 🙁
do you have 2 sensor sections?
Did you reload REST sensor or reboot after adding it? I threw that into my config in my dev instance and I do see a sensor created, though the value remains Unknown.
well, also looking at the resource the template is a bit wrong too
One sensor tag at the beginning of the copied section, that’s it 👀
Hmm, okay… I restarted the YAML, not the entire Home Assistant 🤔
That might be enough, not positive. If you go to developer tools -> states, Do Ctrl-F5, you don't see sensor.mystnode_quality?
{{ (value_json[0].quality.quality * 100 / 3) | round(1) }}
Alright 🤔
Let me see, one second 🙂
I’m on my phone right now, but the filtering for the sensor does not show any entities 🥲
also verify that you don't have a sensor: !include sensor.yaml in configuration.yaml
I don’t 🤓
Ok, then upon restart, it should work
Alright, wait a second… I’ll grab my MacBook ☺️
It'll show up as sensor.mystnode_quality as @lofty mason said
Does the value template need the quotes or not?
Alright, thanks. Copied your solution and now I'll restart >D
this
- platform: rest
name: "Mystnode Quality"
resource: https://discovery.mysterium.network/api/v3/proposals?provider_id=0xb393aeba7893a5e337298c183602ad5743e0d7a5
scan_interval: 120
value_template: "{{ (value_json[0].quality.quality * 100 / 3) | round(1) }}"
unit_of_measurement: "%"
Yes, exactly 🙂
I did try to follow the documentation and they use the strings as keys... I'm a little confused XD
Also, FYI y ou don't need quotes for name or UOM. You only need quotes when dealing with characters in your fields that have { [, etc
Alright, thank you 😄
and the word 'on' and 'off', those also need quotes
- platform: rest
name: Mystnode Quality
resource: https://discovery.mysterium.network/api/v3/proposals?provider_id=0xb393aeba7893a5e337298c183602ad5743e0d7a5
scan_interval: 120
value_template: "{{ (value_json[0].quality.quality * 100 / 3) | round(1) }}"
unit_of_measurement: %
Now it shows up! The restart seems to have worked 😄
whenever you ADD to configuration.yaml, you have to restart
Thank you very much both of you 🙂
❤️
unless the configuration already exists
Oh, so just doing the YAML reload doesnt work?
i.e. if you add a rest sensor, you can just reload
yaml reload only works if the integration has already been loaded
so when you add a new integration that's never been loaded, you need to restart
which might have been what you were running into
so from now on, you can add rest sensors without restarting
Ahhhh, that makes sense. Hadn't used the REST integration before, that's true 🙂
This took me way too long to do... just like everything else I do with home assistant 🙈
And the REST integration will now request the data every 2 minutes?
Great, thank you very much 😌
np
it wont' update if there's no updates
Oh 🤔
i.e. if the value is the same, it will not show a state change
@acoustic idol I converted your message into a file since it's above 15 lines :+1:
I can't make sense of the lower part. Can someone help me understand how the sensor Growatt Inverter has the attribute OutputPower?
It is part of the MQTT Message, but only the value TotalGenerateEnergy is bound to the sensor? Does it somehow save the MQTT Message?
@acoustic idol json_attributes_topic: "energy/solar/growatt/" that has your attributes in it
that topic
yes
so what aren't you understanding then?
Will these attributes be "saved" as attributes in that Sensor?
Hmm I'll try to explain
they will be attributes on the sensor.growatt_inverter entity
aaah
this this way I can access the full message I guess?
I assume this is specific for MQTT integration?
I'm not sure I follow you
that mqtt configuration creates the sensor. Whatever you tell it to create, it will create.
hmm ok I think I got it. Let me try
so that configuration you made, is making that mqtt sensor
based on the information in your topics
yes that I get. I just was assuming the message is ready by the sensor, the values taken over and the message discarded
I have no idea if that configuration is correct or if your topics give you the proper information
It seems odd to me that I can "access" the message via that sensor
But nevermind
Thanks alot for helping. I'll check this
you supplied it to the attributes topic, so whatever's in that topic will be in your attributes
when that topic updates, so will the attributes on that sensor
Maybe stupid question, sorry I'm a bit new to all this: Wouldnt it make more sense to map the MQTT Message into a new device (if thats possible) and derive the entities via templates?
You can do that
But you didn’t do that
You told it to make attributes out of those values with that configuration
Your mqtt configuration that you posted
I’m guessing you copied and pasted that config then?
Alright, I suggest you spend time learning what you copied and pasted by reading the mqtt documents
Hi, I have got a sensor (sensor.hoymiles_600_ch1_current) that is "unavailable" during night. Is it possible to set it to "0" during this time without creating a copy of it?
No
ok 🙂
Another question: I have got a AVG Sensor that is TOP-1 consumer in the homeassistan_v2.db. Why is this sensor so voracious?
''' - platform: statistics
name: "Stromverbrauch 15min Durchschnitt"
entity_id: sensor.stromverbrauch_in_watt
state_characteristic: mean
precision: 0
max_age:
minutes: 15
155193|4|||sensor.stromverbrauch_15min_durchschnitt'''
hmm strange, even it is top1 it is only 0,15MB if I am right
i'm trying to send the Set temperature from generic termostat via mqtt, but haveing a hard time : payload: "{{ states('climate.study.temperature.state') }}"
if I create a helper via the UI in which yaml is this stored?
I can't find the name in any using "grep -i...:"
I have a sensor outputting a string that is not formatted as I want to. It uses ; to state a new line but the text is continuous. How can I add that on every ; there will be a line break? Here is an example output https://pastebin.com/52YR36m4
I want a line break instead of ;
can you do something like: {{ "XYdjkfjsd; fsdfksdlhflsa; fdshsdjkl " |replace(";","\n") }} ?
That is exactly what I wanted! Thanks
Hi i have a question how to get all the calendar events ? When i do
{% set events = states.calendar %}
{% for event in events %}
{{event}}
{% endfor %}
list consists of only one event which is the one that is closest to the current date
I see there is a feature request for something similar https://community.home-assistant.io/t/calendar-new-entitites-or-helper-that-show-a-list-of-calendar-events-within-a-certain-scope/358014 is the only workaround is to create a single calendar for a single repeatable activity?
Remove .state
Oh, looks like you should use "{{ state_attr('climate.study', 'temperature') }}"
A calendar entity only has the next event
I have a sensor sensor.washing_maschine_initial_time and sensor.washing_maschine_remaining_time which give an output as follows: 0:00:00. How can I find out which format that output is in (i.e. string, time, ...). I would like to get the percentage of progress (i.e.
{{ (states(sensor.waschmaschine_remaining_time) / states(sensor.waschmaschine_initial_time) |float * 100) | round(0) }}%
But this template is currently not accepted.
All states are strings, so you will always need to convert them (back) to the appropriate type
All states are strings
And to receive the state you need to use quotes around the entity_id
Cheers, yes this was a quick copy and paste error.
Finally going to be able to load templates from a file soon (for reusing Jinja in automations/scripts)..
https://github.com/home-assistant/core/pull/88850
Much better implementation than the first guy who tried it
Let's see if it gets merged for next release
I'd wager it won't
🤞it will get merged for April.
@cold crag that's a #frontend-archived question. Also, make sure you format the yaml and post the full yaml where that card resides.
@weak cradle I converted your message into a file since it's above 15 lines :+1:
Moreover I do not like to have:
platform: homeassistant
event: start
because it will make the sensor.daily_energy_consumption zero after reboot. How can we keep the old info?
Trigger sensors will retain their state upon restart... what are you trying to do w/ that trigger then?
You should also only have one template: section
Also, have you taken a look at the utility_meter integration? Kinda seems like it might be doing what you want: https://www.home-assistant.io/integrations/utility_meter/#advanced-configuration-for-dsmr-users
I want to get daily consumption based on sum of 2 sensors. This utility meter will show separate values?
Can the following be replaced by the utility meter?
- name: "daily_energy_home_usage"
device_class: energy
state_class: total
unit_of_measurement: "kWh"
state: >
{{((states('sensor.energy_consumption_tarif_1')|float +
states('sensor.energy_consumption_tarif_2')|float -
states('sensor.daily_energy_consumption_saved')|float) +
((states('sensor.STP10_0_3AV_40_462_total_yield')|float +
states('sensor.STP3_0_3AV_40_542_total_yield')|float) -
states('sensor.daily_energy_solar_saved')|float) -
(states('sensor.energy_production_tarif_1')|float +
states('sensor.energy_production_tarif_2')|float -
states('sensor.daily_energy_production_saved')|float))
|round(3)}}
No, the utility meter will give a running total of a time period though. Like in that doc I linked, the next section then shows you'd use a template (like you just posted) to calculate the sum of multiple
But then in that case, you don't need it to be a trigger sensor either
You are right. I can port/change my part to that of utility meter. Thanks!
i got two kWh sensors which can be either a number or 'unknown'. How can i add these when one of them is unknown? Im doing a lot of if/then/else but i bet it can be written more hardcore syntax
Try with the is_number()
Example:
{% if is_number(states('sensor.daily_energy_offpeak')) and is_number(states('sensor.daily_energy_peak')) %}
{{ states('sensor.daily_energy_offpeak') | float + states('sensor.daily_energy_peak') | float }}
{% else %}
None
{% endif %}
its about 2 PV inverters. One can still be offline, while the other one is producing...
{{ [ 'sensor.inverter_1', 'sensor.inverter_2' ] | map('states') | map('float', 0) | sum }}
cool. Thats is indeed more hardcore then:
{% set a = 0 %}
{% endif %}
{% if not is_number('sensor.gw2500_ns_pv_power') %}
{% set b = 0 %}
{% endif %}
{{a+b}}```
thank you
if you want to sum values, you can always default them to 0
adding | int(default=0) ?
btw, what you had was always going to be 0 because you were not checking for the state of the entity, but for the entity_id itself
my bad. should have been states()
yes, which is the same as int(0), of use float(0) if you want to include decimals
yup. Thanks! ill use your array map+sum
that way i miiiight actually learn something 😉
and you should have set a to the state if it was a number
now you were not defining a and b in those cases
ill go try to fix my broken snippet, then hop over to yours 🙂
once again: many thanks
you can do something like
{% set a = states('sensor.banana') | float if states('sensor.banana') | is_number else 0 %}
but a lot easier for that is {% set a = states('sensor.banana') | float(0) %}
gotcha. Why do you always make it look so easy. I understand what you are presenting, but figuring it out by my self.... ugh
ill go with the array. To add something new to my hacked together HA installation😜
I'm trying to create a template sensor that will show the current open app on my Apple TV. I haven't ever created a template sensor...I've setup a separate sensors.yaml and templates.yaml file but don't know how to format the sensors I create properly. I'm finding it hard to understand the wiki about it too...
sensors:
- name: Television Media
state: "{states('media_player.kitchen_tv.').attributes.app_open}"```
Will something like this work?
"{{ state_attr('media_player.kitchen_tv', 'app_open') }}"
@amber oxide you are mixing the new format and the legacy format
How do I save a variable in an automation between runs
- variables:
prior_brightness: |
{% if brightness is defined %}
{{ brightness }}
{% else %}
0
{% endif %}
command: "{{ trigger.event.data.command }}"
brightness: "{{ trigger.event.data.params.level|int }}"
command_direction: |
{% if brightness > prior_brightness %}
on
{% else %}
off
{% endif %} ```
I'm doing this but brightness always is not defined
By storing it in an input_text or input_number
{{ states.sensor.540i_xdrive_mileage }}
TemplateSyntaxError: expected token 'end of print statement', got 'i_xdrive_mileage'
So numbers in entities are a no-go?
Devtools keep giving me this error, I'm just trying to write an automation trigger that fires when last_changed is a few minutes ago, but it can't even print it's value at all
{{ states('sensor.540i_xdrive_mileage') }}
Oh thanks boss, works, but I can't find any examples that use the states() func and get attributes like last_changed. state_attr() with last_changed gives me a dict and null 🤔
Could you not interpret last_changed as any state changes for x minutes ago?
Thanks. Now I get an error 'Incorrect type. Expected "object".' though?
Code is now - platform: template sensors: - name: Television Media state: "{{ state_attr('media_player.kitchen_tv', 'app_open') }}"
This as automation trigger
platform: state
entity_id:
- sensor.540i_xdrive_mileage
for:
hours: 0
minutes: 5
seconds: 0
You are using the legacy templates sensor with the keys of the new template sensors
Ah...what do I need to change to make it work?
I'm super new to all this templates stuff
I'm trying to add the sensor in my sensors.yaml
https://www.home-assistant.io/integrations/template/
example of correct syntax in configuration.yaml
template:
- sensor:
- name: "Average temperature"
unit_of_measurement: "°C"
state: >
{% set bedroom = states('sensor.bedroom_temperature') | float %}
{% set kitchen = states('sensor.kitchen_temperature') | float %}
{{ ((bedroom + kitchen) / 2) | round(1, default=0) }}
Yeah, I've read that...but that doesn't work in my sensors.yaml...so I wasn't sure what I needed to do to make it work there
Probably because your sensor.yaml is still build on the legacy format
- attribute: >-
{%- if "essid" in states.this.attributes -%}essid{%-endif-%}
name: WiFi```
Having some trouble with this...anyone?
Right okay. How do I change that? Sorry, I'm a complete newbie to templates stuff haha
Legacy format for you is:
- platform: template
sensors:
tv_media:
friendly_name: Television Media
value_template: "{{ state_attr('media_player.kitchen_tv', 'app_open') }}"
Getting undefeined even when attribute essid exists
OFC its auto-entities
i am aware my question bordelines between frontend and templates
Okay thank you, so that should work. But shouldn't I be changing it to the new format? I was wondering how I would change it to the new format, so I am not using the legacy format in my sensors.yaml
I think the best thing to do is to ditch (for now) the splitted setup of sensors.yaml and just build the template sensors in configuration.yaml like the documentation does. After you get a feeling for the mechanisms you can convert everything again into a split config
Okay honestly that sounds like the best plan. I was just trying to start out with the split config because it seemed like it might be a good idea just to start out as organised as possible to reduce clutter later down the track...
It's always best to first understand the basics, from that you can build a more custom/advanced setup
Very true. I have a habit of wanting to go for the most complicated, great looking/functioning stuff immediately without taking time to learn the basics first 😅
Do you use this in auto-entities?
if you really need to use states.your.entity then you need to use square brackets if the object_id starts with a numer
as mentioned in the docs
Entity options
In the options: option of the filters, the string this.entity_id will be replaced with the matched entity_id. Useful for service calls - see below.
Can you show the full auto-entities card config you try to use? I think you are missing the filter option it has
Yes, i did missunderstand...however i am rewriting the whole thing with the template option instead... wish me luck 😉
Getting close... Can somone spot my error probably formatting....
It lists everything weith ip as secondry however state is shown and i dont see the extra attribute in the row....
@grave solstice I converted your message into a file since it's above 15 lines :+1:
Non templated code that works:
filter:
include:
- entity_id: device_tracker.*
attributes:
source_type: router
options:
type: custom:multiple-entity-row
secondary_info:
attribute:
- ip
show_state: false
state_color: true
entities:
- attribute: essid
name: WiFi```
So no need to template it right?
Well yes because essid doesnt always exist and the i want to use dynamic value
Thats why i am rewriting it
WiFI
Undefined is quite ugly
So you would only pass in entities that have the attribute essid
you can't template the entire config
but you can use a template to find the device trackers which match your needs
so for example those with the required attribute
@fickle sand I converted your message into a file since it's above 15 lines :+1:
Does anyone have an idea on how to set a default value for a rest sensor using value_template? When the request fails or times out, it doesn't use float(0) as a default value
just add that attribute to the filter from auto-entities
filter:
include:
- entity_id: device_tracker.*
attributes:
source_type: router
essid: "*"
what's your current template
Well my internet doesn't work so i can't copy the code from pc
@fickle sand @grave solstice this seems more #frontend-archived related
especially as you are not using templates
then it will be difficult to help you
But it's just
-platform: rest
Value_template {{value.json_data | float(0)}}
scan_interval: 3600
I know, just wanted to mention it by my self 😄
Obviously has other parameters but these are the basic
But i want to show the entity... if it doesnt have essid i still want to show it...
Currently it shows NaN when the request fails/times out. Which means in the graphs it retains the previous value. I want it to show 0 instead.
This wil fail if value doesn't have an attribute json_data
you can use the default filter to work around that default
but is json_data a number? I would expect that to be a mapping itself
It's a number
anyway {{ value.json_data | default(0) | float(0) }}
Let me try
or {{ value.get('json_data', 0) | float(0) }}
The point i want it to be 0 is because as I said. My internet is currently down so i want my graphs to reflect that
Oh it worked
Thank you
Before it would just say my internet is 30Mbit or whatever the previous value was, even if there was an outage by my ISP. I didn't have a chance to test it but since now my internet has been down for an hour, that's an opportunity. Thank you once more!
👍
Oh man. Localtuya can't initialize with internet outage. What a joke 🙃
But it is templates. I posted the non template code I want to generate. Check the post above.
Before the non template code which the bot changed to file
I already commented on that, you can't template the entire config
And you'll get more help on how you can use auto-entities in #frontend-archived
Ok thanks
Hi! I'm struggling with round() or format() round had no effect here : value_template: "{{ value | float / 1000 | round(2) }}"
and this returned nothing at all: value_template: "{{ value | float // 1000 }}"
ah, thanks. I'll try that
Hello everyone,
i currently struggling with the translation of states into my language
I would prefer to do this in template -> sensors
I've googled around and tried different code-snippets but nothing worked so far
post what you've tried
i get from openweathermap_forecast_condition "rainy" and would like to have "regnerisch"
@frail scarab I converted your message into a file since it's above 15 lines :+1:
i'm not sure if the file (/config/sensors.yaml) is correct
that looks good, what's the problem
that's the old style so it goes in sensors.yaml
I would suggest to stick to one language 😉
and i'm not sure if the position (2 space from the left) is correct
this looks good for the legacy template format
yaml looks fine
it's copy&paste. i'll fix it as soon as it works
- platform: template
sensors:
openweathermap_forecast_condition:
value_template: >-
{%- set state = states('openweathermap_forecast_condition') -%}
{% if state == 'clear-night' %} Ясно, ночь
{% elif state == 'cloudy' %} Bewölkt
{% elif state == 'exceptional' %} Предупреждение
{% elif state == 'fog' %} Туман
{% elif state == 'hail' %} Град
{% elif state == 'lightning' %} Молния
{% elif state == 'lightning-rainy' %} Молния, дождь
{% elif state == 'partlycloudy' %} Переменная облачность
{% elif state == 'pouring' %} Ливень
{% elif state == 'rainy' %} regnerisch
{% elif state == 'snowy' %} Снег
{% elif state == 'snowy-rainy' %} Снег с дождем
{% elif state == 'sunny' %} Ясно
{% elif state == 'windy' %} Ветрено
{% elif state == 'windy-variant' %} Ветрено
{% else %} Нет данных
{% endif %}
sensor:
- platform: template
sensors:
openweathermap_forecast_condition:
bare minimum that goes into the sensors.yaml
@frail scarab I converted your message into a file since it's above 15 lines :+1:
that's the complete file
and that's completely wrong
😦
your yaml is wrong
look at what I wrote vs what you have
just put what I wrote into your file
@mighty ledge how can i keep both "things" in one file?
this could work with the right inlcude.. well the translated states.. the one above that looks like a total trainwreck
the main issue is that whatever you have above your template sensor is also a mess
sorry, i'm not good with yaml
you can keep both things in 1 file, but the other thing is very wrong
it works so far
I have no idea how it works as the spacing is wrong
@mighty ledge can you please help me to fix it?
I can't tell what it should be doing
friendly_name: Pricelevel
entity_id:
- sensor.electricity_price_blabla
value_template: '{{ states.electricity_price_blabla.attributes.level }}'
these 4 lines need indentation
and how did you include this file?
@mighty ledge it creates a new entity from a existing sensor attribute
- platform: template
sensors:
pricelevel_electricity_price_blabla:
friendly_name: Pricelevel
value_template: '{{ states.electricity_price_blabla.attributes.level }}'
openweathermap_forecast_condition:
value_template: >-
{%- set state = states('openweathermap_forecast_condition') -%}
{% if state == 'clear-night' %} Ясно, ночь
{% elif state == 'cloudy' %} Bewölkt
{% elif state == 'exceptional' %} Предупреждение
{% elif state == 'fog' %} Туман
{% elif state == 'hail' %} Град
{% elif state == 'lightning' %} Молния
{% elif state == 'lightning-rainy' %} Молния, дождь
{% elif state == 'partlycloudy' %} Переменная облачность
{% elif state == 'pouring' %} Ливень
{% elif state == 'rainy' %} regnerisch
{% elif state == 'snowy' %} Снег
{% elif state == 'snowy-rainy' %} Снег с дождем
{% elif state == 'sunny' %} Ясно
{% elif state == 'windy' %} Ветрено
{% elif state == 'windy-variant' %} Ветрено
{% else %} Нет данных
{% endif %}
okay, the entity_id line can go 🙂
there's a bunch of crap that was in it that was outdated or comments
and the spacing was wacky
BTW I was just looking at the templating docs, seems I missed the new contains filter which was added in January
and more functionality incoming https://github.com/home-assistant/core/pull/88625
@mighty ledge do i have to restart the whole HA to get the new yaml-file loaded?
I was looking at the next docs to see if it was already added
you don't need to tag petro every time, he is here, chatting 😛
and no, you can reload template entities in devtools > yaml
as you can see, there are also others who can answer questions 😉
😉
in this channel are currently many people online. how does you know that i'm talking to you? or my question reffers to that what you told me 5 minutes ago?
that's why i tagging him
wrong?
it can be kinda annoying..
and i don't want to reduce your answer 😉
ohhh...
i think i found my issue.
i wanted to push the state to alexa.
i read anywhere that this is a different thing and what we have done does not work.
correct?
but it does not work 😦
it's still "rainy"
what do you mean?
you are creating a new sensor
so it will not translate the old sensor, it will create a new sensor which has the translated state of the existing sensor
yes, this doesn't overwrite your existing sensor, you need to ask for your new sensors status
probably sensor.openweathermap_forecast_condition_2
as you used the same object_id as the existing sensor
but try to find it in developer tools > states to be sure
Open your Home Assistant instance and show your state developer tools
hmmm...
no. no _2
only sensor.openweathermap_forecast_condition with "rainy"
okay, back to the start
where did you place the code petro suggested
in which file?
/config/sensors.yaml
😮
there should be a line
sensor: !include sensors.yaml
is there a emojie for "shame"?
probably 😛
afk doogo wants to go outside
back
that explains why you both was so confused about the file
okay, i removed the # in from of the include and removed the part above which is somewhere else
now i have a sensor.openweathermap_forecast_condition_2
but it seems it does not match
sensor.openweathermap_forecast_condition state: rainy
sensor.openweathermap_forecast_condition_2 state: Нет данных
which means "no Data"
it works
"{%- set state = states('**sensor.**openweathermap_forecast_condition') -%}" does the trick
@marble jackal @mighty ledge Thank you so much for your help!
BTW, alternative approach would be this:
- platform: template
sensors:
openweathermap_forecast_condition:
value_template: >-
{%- set state = states('sensor.openweathermap_forecast_condition') -%}
{%- set translations =
{
'clear-night': 'Ясно, ночь',
'cloudy': 'Bewölkt',
'exceptional': 'Предупреждение',
'fog': 'Туман',
'hail': 'Град',
'lightning': 'Молния',
'lightning-rainy': 'Молния, дождь',
'partlycloudy': 'Переменная облачность',
'pouring': 'Ливень',
'rainy': 'regnerisch',
'snowy': 'Снег',
'snowy-rainy': 'Снег с дождем',
'sunny': 'Ясно',
'windy': 'Ветрено',
'windy-variant': 'Ветрено',
}
%}
{{ translations[state] | default('Нет данных') }}
thank you. currently it works so far for me
@frank sand I converted your message into a file since it's above 15 lines :+1:
You should ask this on the ESPhome discord server, this channel is for jinja #templates-archived
@frank sand ^
@carmine island I converted your message into a file since it's above 15 lines :+1:
@carmine island I converted your message into a file since it's above 15 lines :+1:
Hi can anyone please help with jinja2 code that that dynamically loops through a long list of multiple attributes for an entity called "sensor.gas_stations_search" and prints the the value of 'price' associated with the address at ‘7625 Sawmill Rd’ from my attributes. The end result should be one print & close the loop after it finds the price associated with ‘7625 Sawmill Rd’. currently I get multiple price prints
{% for result in state_attr(‘sensor.gas_stations_search’, ‘stations’).results %}
{% if result.address.line1 == ‘7625 Sawmill Rd’ %}
{% for price in result.prices %}
{% if price.credit.price %}
{{ price.credit.price }}
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
HELP