#templates-archived
1 messages · Page 96 of 1
@warm isle The XY problem is asking about your attempted solution rather than your actual problem. This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.
The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.
We have no idea what you're trying to solve.
You're not telling us anything about what you're trying to achieve
Just ... vague hints about dimming
Have to get back to it later this evening. Birthday party incoming. Wasted already to much time (and energy) to it 😅
does anyone know how i could get this working:
- platform: mqtt
name: "BlueIris"
state_topic: "BlueIris/status"
command_topic: "BlueIris/admin"
payload_on: "profile=1&lock=1"
payload_off: "profile=5&lock=1"
state_on: "profile=1"
state_off:- condition: template
value_template: "{{ not is_state('sensor.blueiris_profile', 'profile=1') }}"
optimistic: true
qos: 0
- condition: template
@lilac dust 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:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
the templating doesnt work
And remember that over 15 lines you must use a code share site...
What is that?
Switch? Sensor? Cover?
Where did you se that it supports a template for the off state?
nowhere, hence the question
Well... then you can't
ok, thats to bad
any other idea how i should go about this?
ok so value template is the right way after all?
A valid configuration is the right way
There's no condition in there
You also still need to set the state_off string
ok, then i need to do it some other way
Or just
value_template: "{{ 'profile=1&lock=1' if is_state('sensor.blueiris_profile', 'profile=1') else 'profile=5&lock=1' }}"
``` and don't set either `state_on` or `state_off`
Assuming your sensor returns those exact states
it does, but there can be 7 different states, one of them is ON
will do, and i have tried reading i just dont get it - sorry
i will try your suggestion, just a sec
Pseudo-code:
if sensor.blueiris_profile is 'profile=1'
return 'profile=1&lock=1'
otherwise
return 'profile=5&lock=1'
The first is your defined on payload (default for the on state)
The second is your defined off payload (default for the off state)
So, if that sensor is 'long=john' then it'll return the off state string
Invalid config for [switch.mqtt]: value should be a string for dictionary value @ data['state_off']. Got [OrderedDict([('condition', 'template'), ('value_template', "{{ 'profile=1&lock=1' if is_state('sensor.blueiris_profile', 'profile=1') else 'profile=5&lock=1' }}")])]. (See ?, line ?).
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
☝️
https://paste.ubuntu.com/p/tGjMkMShRP/ there you go

- condition: template
``` 
Please stop making stuff up
As I said and as you found - there is no such option
I didn't say just replace that template - I said a lot more
yes you did but unfortunately thats what i understood
the value template, how should i use it?
your line?

its state off im trying to define
yupp!
You also still need to set the
state_offstring
Just like you did for state_on
ok but the state_off can have more than one value
it can have six diffrent values
Two people... separated by a common language
well, to be fair: this isnt my language...
Got it working - Thanks
never tried templating before
Is it just me, or is the header now covering part of the template editor in developer tools? https://i.imgur.com/oM56U31.png
Fixed in 0.112.1
Oh, updates so fast. 🙂
Ha that’s funny . Doctor Cox is actually the character that I imagine Tinkerer as most often, except with a Glaswegian accent
How would I set a variable to the value of the state_attr I'm pulling?
{% set current_date = now().strftime("%Y-%m-%d ") %}
{{ current_date }}
{{ state_attr('weather.kelp_daynight', 'forecast')[0].datetime }}
ah whoops. I tried keeping the {{}} within the statement
@hollow bramble absolutely
Dr. Cox = I'm gonna love the shit out of you and help you in everything you do. But I'm gonna make you feel like a complete and total idiot while I do it. Ya got that newbie?
Pretty accurate 🤣 earned respect is necessary to get rid of that last part
well. I needed to get mad jinja skills for work. So this is good practice
in jinja do I need to set an empty variable outside of a for loop so that after setting it in the for loop it still exists outside of said loop?
The problem you may run into is custom functions are going to be different
You need to put it in a namespace for that
{% set ns = namespace(entity_id="") %}
{% for switch in states.switch %}
{% if switch.name | lower == whatever_the_name_is | lower %}
{% set ns.entity_id = switch.entity_id %}
{% endif %}
{% endfor %}
{{ns.entity_id}}
example
cool. thanks
how do I say tomorrow?
now().strftime("%Y-%m-%d ")
will now() + 1 work?
that should be easy enough to google 😉
I am
@dull ledge posted a code wall, it is moved here --> https://paste.ubuntu.com/p/DqdG5hC77h/
i thought the limit was 15 lines. lesigh
any tips for improvements on that?
other than remove the extra print statement
ah. I thought it only counted what was in the code block. My mistake
It counts everything so we don't have to look at a wall of text.
found one issue. It was going to break on saturdays.
{% if forecast_day == tomorrow or (tomorrow == 0 and forecast_day == 0) %}
https://paste.ubuntu.com/p/7pxbMSJbVC/
Do I have to create the same loop to get each value for the attributes or is there a better way to do it?
trying to set up an automation for some of my LEDVance tunable white bulbes to turn on to the right color depending on the time of day. I wound up using the custom compponent hass-variables. I know that light_temp.state is set to 3500 right now. My automation is turning the lights on with kelvin: '{{ light_temp.state | int }}' but I am getting an error: expected int for dictionary value @ data['kelvin']
Sounds like a rule one of templating violation
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
There it is
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find the docs at https://www.home-assistant.io/docs/automation/templating/ - and don't forget rule #1! Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs
it's also there 😉
well, wish I found that page sooner. Thanks!
Woof
That looks so repetitive repetitive repetitive
Input number
Ok fe
Hi Guys, I'm trying to setup a air quality monitor based on arduino but I'm havo no developer skills. Thus, I'm having a lot of difficult to create an entity sensor based on the information received in the broker (I know, shame on me)>
Anyone available to review it for me?
name: "Air Quality"
state_topic: "home/gasleak"
value_template: >-
{% set value = {{value_json.measure}} %}
{%- if value < '100' -%}
Good
{% endif %}
{%- if '100' < value < 130-%}
Attention
{% endif %}
{%- if value > 130-%}
Danger
{% endif %}```
Thank you!
The information arrived in the topic this way:
{"value":"81","Status":"Ready"}
Can somebody help me extract the entire line for id=0 from this XML?
https://paste.ubuntu.com/p/jnpVt4qQ9x/
What have you tried?
You always seem to want other people to do all the work 🤷♂️
You haven't even said where that data comes from. Is it a sensor? A webpage?
A sensor
I can't parse it tbh
There is a JSON here as well https://paste.ubuntu.com/p/3H85gz4K4N/
What's the syntax again for set = in the template editor for JSON?
What kind of sensor is it?
Command Line sensor
Do you know the difference between a Dict and a List in Python?
I do not.
They're both simple. Read it, understand it. It'll help you with templates so you don't have to ask other people to do simple things every time.
It doesn't matter what your data looks like, it'll always follow the same pattern.
@hollow elm what error message are you getting that makes the code you have a problem?
How do I test the JSON data in the template editor?
There are examples on the templating documentation. https://www.home-assistant.io/docs/configuration/templating/
Google has the answers to a lot of these questions. Just first type them exactly into Google, come back with questions
Hi, currently struggling with a template from https://community.home-assistant.io/t/media-player-universal-source-in-overview/135331/13
Message malformed: invalid template (TemplateSyntaxError: Encountered unknown tag 'mapper'.) for dictionary value @ data['sequence'][0]['data_template']['source']
seems to be the multiline part in source:
found it... was missing the "set" before the mapper
Hi Guys,.. battling my own lack of yaml formatting knowledge,.. and what the error messages are telling me,... Component error: sensors - Integration 'sensors' not found. Component error: time_of_day - Integration 'time_of_day' not found. Invalid config for [sensor.template]: [time_of_day] is an invalid option for [sensor.template]. Check: sensor.template->time_of_day. (See ?, line ?). Component error: sensors - Integration 'sensors' not found. Component error: time_of_day - Integration 'time_of_day' not found. https://pastebin.ubuntu.com/p/jr56ycn7fB/
I cannot seem to work out whether I need a sensor entry or sensors,.. even though I use
- platform: entry
There is no sensors integration
vscode says its happy,.. but alass HA has other ideas...
Well, yes 😉
It's sensor: not sensors:, and you can only have one sensor: key
And every sensor platform can go under that (or use the second method linked above)
confused,.. so why are these entries not in the sensor.yaml file,.. or can they..
You've commented out the line that would use that file
#sensor: !include yamlconf/sensors.yaml
ok,.. so I have removed the sensors: entry,.. but then vscode says missing property "sensors", and property 'time-of-day' not allowed..
time_of_day:
value_template: >
{% if states.sun.sun.state == 'above_horizon' and as_timestamp(now()) < as_timestamp(states.sensor.date.state ~ ' 12:00:00') %}
morning```
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
Ignore VSCode, trust that
Your template sensor needs to look like https://www.home-assistant.io/integrations/template
Which currently it doesn't
https://hasteb.in/ukajayin.lua would be more correct
tx guys,.. let me play some more the checker is a new tool to play with,.. and the yes vscode checker is not reliable I have decided...
the online tester seems good,.. at least it gives some more meaningful output unlike VS,... and I can now play and break things to see what is reported,... just updated to 112.2,... and the tools=> template has changed,... and I now have my 'time-of-day' as a service,... ( more to play with,...) so I now have a 'sensor:' device called 'time-of-day',.. so what is a sensors: within that entity...? where do I find the docs on that pls... Tx again one and all
Still no luck in extracting the JSON, if someone could take a look that would be appreciated https://community.home-assistant.io/t/unable-to-parse-json/209520
Sorry, bit too drunk to dig in to that right now
Might take the edge off you never know 😉
Can someone spot why this template is not working? State is always "off" rather than "up" or "down".
- platform: template
sensors:
sun_state:
entity_id:
- sun.sun
friendly_name: "Sun State Test"
value_template: >-
{% if is_state('sun.sun', 'above_horizon') %}
up
{% else %}
down
{% endif %}```
I also have an icon_template with the same condition and that works just fine.
A binary sensor is only reporting as on/off? What a surprise.
You probably want a sensor.
value_template
(template)(Required)The sensor is on if the template evaluates as True and off otherwise. The actual appearance in the frontend (Open/Closed, Detected/Clear etc) depends on the sensor’s device_class value
From the binary sensor docs: https://www.home-assistant.io/integrations/binary_sensor.template/#value_template
How did I miss that 😖 Thanks
Hello again 🙂 How to operate with two entities and two different service calls based on trigger?
here is the example what Im trying to do
- service_template: >-
{%- if trigger.event.data.switch == 'switch.bedroom_led_light_trafo' -%}
switch.turn_on
entity_id: trigger.event.data.switch
{%- else -%}
light.turn_on
data_template:
entity_id: >
{{trigger.event.data.entity}}
{%- endif -%}```
service_template for the service
You're trying to jam it all under the service template
maybe two actions to put?
- service_template: >-
{%- if trigger.event.data.switch == 'switch.bedroom_led_light_trafo' -%}
switch.turn_on
{%- else -%}
light.turn_on
{%- endif -%}
Then a data_template block with the entity_id section
data_template:
entity_id:
{%- if trigger.event.data.switch == 'switch.bedroom_led_light_trafo' -%}
{{ trigger.event.data.switch }}
{%- else -%}
{{ trigger.event.data.entity }}
{%- endif -%}
tnx @arctic sorrel I get it now
just I have an error
I think I need to add > at entity_id?
in data_template section?
maybe you missed it?
hehe ofc 🙂
It's worth taking the time to read through all the templating docs and examples
tnx
I am reading, but when it comes to logic, suddenly, I dont have an idea..
I was ready to write separate automations..but at the end, I think this is the right way..why not to use templates
Neither is right or wrong 😉
Hi, I'm not sure whether this is the right channel to ask, but didn't find anything better... I've upgraded from 0.111 to 0.112 and now all my template sensors/template switches/template lights are not working anymore 😦 Did I miss something in the breaking changes?
If it is not the right channel, can someone please point me to the right one?
Any errors in the log?
none related to the templates. It might be abigger issue though: the time sensor is also stuck to the time I (re)start hass (using hass core/virutal env)
The first line in the log is a warning from the recorder "Ending an unfinished session". Could it be that the recorder is having a problem?
That’s a whole lot of no-information
I tried disabling everything and enabling the whole sensors one by one and seems to work now. Only the recorder is still disabled.
So there might have been something wrong with my database for the conversion.
Seems that I managed to get it working again; sorry for the noise.
The strange thing is that I did not see any errors in the logs 😦
ok, I reenabled the recorder as well, and now everything seems to work again as it should. Very strange behaviour. But as long as everything works again, I am happy.
Seems like you didn’t wait for the database to update
It’s in the release notes that a new database was deployed on .112 and existing databases needed to be converted. Which could take upwards of 3 hours depending on the size of your db
well, I updated yesterday at 23:00; I restart the server every day at 03:00, so it did have about 4 hours...
and later on I even deleted the whole DB and restarted HA (so , nothing to convert), but it didn't help either
So, if the biggest issue is that I lost the history, I can live with it; it will be regenerated in a couple of days 😄
Thanks!
(and sorry again)
If you have to restart daily you've got major issues with that host
Can anyone help me work out how to cast the output value of a template to an array? I am trying to call service device_tracker.see and set gps In my data_template I have gps: "{{ trigger.json.gps }}" where gps in the trigger data is "gps": [51.509802, -0.086692] <- location data is dummy data
When the action runs it logs Error executing script. Invalid data for call_service at pos 1: None for dictionary value @ data['gps']
Found an answer to my issue 🙂 https://community.home-assistant.io/t/update-a-device-tracker-gps-from-a-telegram-command/122944/2
Hi Team, I have a power monitoring smart plug set up with tasmota to notify when the washing is finished. I have a binary sensor template created but how would I get this into Homekit so I can see the washing machine state?
nvm, think I got it 😛
dam, almost had it. I have device_class: power but Homekit shows it as an occupancy sensor . . . . any ideas?
no, cool username though.
I didn’t know that delay_on and delay_off existed, so that’s cool. I always use for: in automations triggers and conditions
hey y'all. is there a button or an addon that lets you execute an API command in button press?
Depends how on what you mean by ‘API command’. You probably want call-service
And tap-action
Anyway to change unit_of_measurement so its set by template. i.e. I want to display ml, litres or kL depending on the flow rate of my water valve?
Unfortunately not
any work around, I considered setting the unit to "" but this breaks stuff on my influxdb side
the problem is flow rate changes from tiny values to massive values
Do you need to set a unit of measurement for it at all?
If so, apparently setting it to 1 is a workaround for when you want a unit of measurement (like if you want it to display a graph when looking at history)
I mean I'd prefer to all the rest of the values do, I don't have to but you know, I'd like to
hmmm maybe I could make multiple sensors and display those depending on flow rate
I wonder if lovelace can be dynamically updated based on a template
Or you can just display the value + whatever units you want in the UI if that’s what you want
Custom button card lets you use a template for the value
Yeah it would mess up influxdb as I pull stuff out based on units thou
Indeed
hmm.. not quite what I'm after, I kind of like the list of entities with Voltage, Flow Rate, kA and kW
I know its not feasible now at least
Hi, I've set up a template cover, which I want to use from lovelace. My config looks like this:
- platform: template
covers:
templ_tertuer:
friendly_name: "Rollade Terrassentür"
position_template: '{{ states.cover.rollade_terrassentur.attributes.current_position | int }}'
set_cover_position:
service: cover.set_cover_position
data:
entity_id: cover.rollade_terrassentur
position: "{{position}}"
If I call the service "cover.set_cover_position" and position: 50 I get this error: Fehler beim Aufrufen des Service cover/set_cover_position. expected int for dictionary value @ data['position']
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:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
or if it's approaching the line limit like yours is:
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
and this is correct "position: "{{position}}"" ?
thanks for the hint with pastebin...
yeah that's fine, but again, you need to use data_template: instead of data:
yeah I've changed it and now it works... thanks @buoyant pine

Good Evening, I am using the traccar plugin, and my device reports my bikes battery voltage, could someone tell me how I might be able to use a template to create a sensor please.
You'll have to start by sharing what format the data is in, otherwise we're just guessing 😉
thundercat_battery:
friendly_name: Thundercat Battery
unit_of_measurement: 'V'
value_template: >-
{%- if state_attr('device_tracker.thundercat', 'power') %}
{{ state_attr('device_tracker.thundercat', 'power')|round }}
{% else %}
{{ states('device_tracker.thundercat') }}
{%- endif %}
device_class: battery
I think this works, but i'd like to round to two decimal places rather than a whole number, is that possible please. At the moment it seems a little overkill... 12.341000000000001
@ivory delta Sorry for not giving more info.
So use round(2)
i wasn;t sure on how to format that. Thank you.
The templates use Jinja. Bookmark this for next time: https://jinja.palletsprojects.com/en/2.11.x/templates/#builtin-filters
Thank you. I'm just going to try and figure out how to get life360 battery charging information on a couple of phones as separate sensors.
- platform: template
sensors:
phone_battery_dad_charging:
friendly_name: "Dad's Phone Battery Charging"
value_template: >-
{%- if state_attr('device_tracker.dad', 'battery_charging') %}
{{ state_attr('device_tracker.dad', 'battery_charging') }}
{% else %}
{{ states('device_tracker.dad') }}
{%- endif %}
not sure what i've done wrong, but if the device is charging it shows true, if it isnt it shows the location. do i just need to add
, 'battery_charging'
to the else argument?
hey guys I've got an idea in mind, not sure is viable so need some help
persistent notifications acumulate while I'm away from home. When I come back I'd like alexa to spell them, either is there only one on if here are 4 or more notifications
is that possible?
I can't find a template to retrieve the message or title of the current notifications
either if there is only one*
@glacial matrix is_state_attr instead maybe?
instead of state_attr
I need a template expert :-)
I currently counting if there is an attribute in an Json Response with:
{% for id in value_json if id.status != "delivered" -%}
{%- if loop.last -%}
{{ loop.length }}
{%- endif -%}
{%- endfor -%}
Unfortunatelly there is also the case the there is no response. So there is no loop count.
In case there is no resonse I need to return a 0:
Any Idea how to achieve this?
Would need to know what the payload looks like
@dreamy sinew Here you are: https://gist.github.com/leinich/a42b042621a7392c2efd57575011ada6
The goal is to count the items where the status are not delivered
Morning guys and gals, I'm trying to create a sensor to see if a phone is charging. I'm monitoring that with life 360. I've made a template, but it just shows as unknown now. My previous attempt wasn't working either:
- platform: template
sensors:
phone_battery_dad_charging:
friendly_name: "Dad's Phone Battery Charging"
value_template: >-
{%- if state_attr('device_tracker.dad', 'battery_charging') %}
{{ state_attr('device_tracker.dad', 'battery_charging') }}
{% else %}
{{ is_state_attr('device_tracker.dad', 'battery_charging') }}
{%- endif %}
many thanks.
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
Other than testing, your indenting is somewhat all over the place
I didnt know i could test a template, thank you. I think i might have cracked it, i don't an if else statement in there so i think this might be correct:
- platform: template
sensors:
phone_battery_dad_charging:
friendly_name: "Dad's Phone Battery Charging"
value_template: {{ state_attr('device_tracker.dad', 'battery_charging') }}
nope. something wrong with the syntax i think.
You're not trying to create a binary_sensor there are you?
ohhh, it might be, it will just be reporting true or false based on if the device is charging or not. It is showing true or false in the testing editor, but when i run the config check i get:
Error loading /config/configuration.yaml: while parsing a flow mapping
in "/config/sensors.yaml", line 405, column 25
expected ',' or '}', but got '<scalar>'
in "/config/sensors.yaml", line 405, column 80
That's down to the lack of quotes 😉
value_template: "{{ state_attr('device_tracker.dad', 'battery_charging') }}"
Perfect thank you!
I get this error 2020-07-07 10:29:41 WARNING (MainThread) [homeassistant.components.mqtt.light.schema_template] Invalid brightness value received
when i do brightness_template: '{{ value_json.brightness * 2.55 }}'
when I try to multiply that is..
but if I use brightness_template: '{{ value_json.brightness }}' there is no error
why so?
i have tried brightness_template: '{{ value_json.brightness | float * 2.55 }}'
still same error
any ideaS?
brightness_template: '{{ (value_json.brightness * 2.55)|round(0) }}'
brightness_template: '{{ (value_json.brightness * 2.55)|round(0) }}'
thanks!
i must have spent more than an hour at this 😦
Integer between 0 and 255 for how bright the light should be
Integers are whole numbers
yes.... too used to auto typecasting various other scripting languages
hi, can someone tell me why my sensor isnt displaying in the webui?
sensor:
- platform: file
name: teststatus
file_path: "/tmp/test.txt"
added this to my configuration.yml and text.txt contains the string True
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:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
also did you whitelist the /tmp dir (and is that the correct path)?
path is correct but i didnt do any whitelisting
keep in mind if tmp is in your config dir, then /tmp is not the correct path
hm added it to my config.yml but now ha tells me something is wrong:
The following integrations and platforms could not be set up:
whitelist_external_dirs
needs to be nested under homeassistant: in your config
should be sensor.teststatus
check the log for errors
oh wait. this is an #integrations-archived topic
ok thx for helping me!
so my ecobee thermostat has an attribute named 'equipment running' and is a comma separated list (there is more than one running at the time). What do you think is the best way to keep track of this? I eventually want to be able to graph and calculate how long each one is on
This way i can see how long the compressor and/or fan has been running
binary sensor template?
yeah, you could make a template binary sensor for each piece of equipment with this as the value template:
"{{ 'fan' in state_attr('climate.thermostat', 'equipment_running') }}"
``` naturally, adjust as needed for your specific setup
and then use each of those template binary sensors in history stats sensors (or whatever you want to use to track their history)
@green wasp ☝️
@buoyant pine is there anyway to make such templates more dynamic or do you really have to manually create a sensor for each possible value?
its really only two in this case, but more wanting to know for other use cases
not really
ok, no problem. wasnt sure you could loop through values and have it create the sensors. makes sense though
i mean, you can use a for loop at developer tools > template to generate the code for multiple template sensors (or whatever) to copy and paste in the config file
i've done that before for some things
i did that, but doesnt that go into a value template for a single sensor? i mean, how could it dynamically create different sensors based on that
i'm saying if you want to generate several template sensors that all use the same code except for the entity (or whatever), you can generate the code for those several sensors that way
to then copy and paste in your config file
not really a standard use but can be helpful
write code to write code 👍
basically lol
you'll engineer yourself right out of a job, son
ha, no, i meant for maybe situations where you dont know what the different values could be in that comma separated list
friendly_name: "HVAC Compressor"
value_template: >-
"{{ 'compCool1' in state_attr('climate.thermostat', 'equipment_running') }}"```
hmm, when i check the value_template code in the developers tool, its coming up as true, but looking at states, its listed as off
shouldnt true be 'on'?
ditch the outside quotes
you don't use outside quotes when making it a multi-line template with >
or just do this:
value_template: "{{ 'compCool1' in state_attr('climate.thermostat', 'equipment_running') }}"
yep. thanks
trying to extend functionality and create power saving mode by only turning on half of lights when motion initially activated,.. but if motion continues,.. then turn all lights on... and of course using a variable timeout delay depending on the time of day... Have tried several approaches but got stumped trying to create yaml logic flow,.. have drafted 'mickey mouse' version in C'ish,. but not able to see a way forward to create within yaml code,.. does anyone have any suggestions.. Many tx https://pastebin.ubuntu.com/p/PzM8hzR99M/
Looks like you're overcomplicating things. Just make two automations, one for initial motion, one for prolonged motion. If you're good with automations, it can even be written as one. But... you're in the wrong place for that. #automations-archived
yes,.. you could be right,.. I will think some more,.. and pay the #automations-archived folks a visit maybe later...
This might be the wrong channel but is there a way of using a template to change the status of an input Boolean so rather than the template saying the status of the input Boolean is on, it says the status is home or away for example?
sure.
value_template: "{{ 'Home' if is_state('input_boolean.whatever', 'on') else 'Away' }}"
Amazing thanks!
note that it doesn't change the state of the boolean, just the template sensor
I've just tried this and it's still showing as on rather than home?
sensors:
amy_status:
friendly_name: "Amy Home"
value_template: "{{ 'Home' if is_state('input_boolean.amy_home', 'on') else 'Away' }}"
is what I've set up and when I try this template
Amy is {{ states("input_boolean.amy_home") }}.
The response is on or off rather than Home or Away?
Sorry if I am missing something silly....
sounds like your sensor is a binary sensor which can only ever be on or off
Ah okay, thanks, will need to do something else with that then!
could do Amy is {{ 'Home' if is_state('input_boolean.amy_home', 'on') else 'Away' }}
or make that sensor not a binary_sensor
Ah that's perfect thanks! I probably misread the help above!
Template sensors create new sensors with a state based on the template you provide. The original entity is unaffected (that's what I meant by it doesn't change the state of the boolean)
Understood thank you!
something something i have a sensor, i need to to read out 3 different templates for 3 different parts of the rgb value of a light, it currently returns a string, how do i make it not?
so if I got it right this should work:
rgb_color: [{{ states.light.light1.attributes.rgb_color.1 }},{{ states.light.light1.attributes.rgb_color.2 }},{{ states.light.light1.attributes.rgb_color.3}}]
ops, now
maybe @arctic sorrel can correct me one more time 😄
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
Test there, the theory is ... reasonable
i did test it there, it was more about the function of the array now
If that provides the right output then yes
is that for the sensor or the automation?
As it's three values
what?
seems like state_attr() would be a bit better
that doesnt even look like the code of the sensor
@quaint saffron for the automation that does not require a sensor anymore
so i switched to the templates channel so i can get info on automations now?
not even gonna question it
now i have a configuration error
i didnt even edit the configuration file
'I have an error' is pretty useless if you're after help. Post the error and the config.
i dont even know what the error is
it opened a window and im currently reading through it
it seems to just be the values of every single sensor connected to home assistant together with a template that i 100% have never seen before and does not belong to me
only the first bit of the output from a config check is typically useful
a single error causes the rest of the file to look like crap
what's your quesiton?
i dont know
what do you mean "whats your question?"
No error 🤷♂️
and then you showed a screenshot of the default dev tools -> Templates screen
i changed the automation like i was told to do, then it told me i had a configuration error, and then it redirected me there
thats all i know
yes, i am also confused
we have yet to see your error
It redirected you to
> Templates? Odd, that's never happened before.
but clicking on the "see the logs" button in the notification redirects me to /developer-tools/logs, which is appearently not a valid location
the first time it then redirected me to templates, right now its just showing a blank screen
Go to Configuration > Logs
ah, that just changed and it's possible that the link wasn't updated
"Error loading /config/configuration.yaml: invalid key: "OrderedDict([('states.light.fakepixel1.attributes.rgb_color.1', None)])" in "/config/automations.yaml", line 63, column 0"
so the error isnt in configuration, its in the automation
its
All YAML is in the configuration, ultimately
i dont like working with home assistant, it can be a bit weird sometimes
ok so the new code doesnt work
now what?
~share the relevant section
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
that was literaly the only suggestion of a fix
An OrderedDict is like an array in any other language. It wants a string, I think....
that is the relevant section he wants
Man, the attitude is strong with this one.
People here are trying to help you, don't piss them off.
It's useful to get the actual section of the automation
i did the thing i was told to do
action:
- data_template:
brightness: '{{ states.sensor.brightness_fakepixel1.state }}'
rgb_color: [{{ states.light.fakepixel1.attributes.rgb_color.1 }},{{ states.light.fakepixel1.attributes.rgb_color.2 }},{{ states.light.fakepixel1.attributes.rgb_color.3}}]
entity_id: light.table_light
service: light.turn_on```
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:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
Possibly you need to |int everything
neither of those things tell me anything
As mentioned earlier, template output is a string - text
Most of the above needs an integer - number
{{ states.sensor.brightness_fakepixel1.state|int }}
``` for instance
the brightness works tho
"Error loading /config/configuration.yaml: invalid key: "OrderedDict([('states.light.fakepixel1.attributes.rgb_color.1|int', None)])""
How can I make a sensor entity (using templates I guessed) that grabs a part of a state from another entity?
i did the thing, it still doesnt work
@ivory delta i still dont know what youre talking about with rule 3
Never mind 🙂
Me? No. Be patient and wait for someone to answer.
sending google links os completely worthless as i 100% get different results than you do
main difference being that a lot of my results are in german
Did you even try the link?
I searched for "rgb_color template home assistant"
100% different to his top result...
this was my first result
so uhm
different result because different country and search history
fair enough, point was that it's findable with a simple Google search
and "ya gotta be willing to do some research"
Different result. Still has your answer.
I'm not really seeing the problem - RobC suggested a valid search which resulted in getting the right answer.
mate, i have absolutely no idea what the problem even is
someone suggested a fix, said fix throws up an error, i was waiting for a response from them on how to fix their fix
do you really want an answer?
With an attitude like yours, I'm not surprised you were left waiting.
But just to shut you up and get this over with: https://community.home-assistant.io/t/help-with-rgb-light-automation/122824/9?u=mono
It needs to be a list of ints. There's how to do your list of ints.
i want an answer, i dont want continual sass on "oh this is so eaaaassyy just google this thing where 90% of the terms used you dont even recognise as being valid words"
The irony.
<plonk>
Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/automations.yaml", line 62, column 7
expected <block end>, but found '<block mapping start>'
in "/config/automations.yaml", line 63, column 10```
Formatting problem
i dont even know what that meeeaaaans
It means you messed up indenting or quotes
- data_template:
brightness: '{{ states.sensor.brightness_fakepixel1.state }}'
rgb_color:
- '{{ (what_color[0],what_color[1])|join|int(0,16) }}'
- '{{ (what_color[2],what_color[3])|join|int(0,16) }}'
- '{{ (what_color[4],what_color[5])|join|int(0,16) }}'
entity_id: light.table_light
service: light.turn_on```
Yup
action:
- data_template:
brightness: '{{ states.sensor.brightness_fakepixel1.state }}'
rgb_color:
- '{{ (what_color[0],what_color[1])|join|int(0,16) }}'
- '{{ (what_color[2],what_color[3])|join|int(0,16) }}'
- '{{ (what_color[4],what_color[5])|join|int(0,16) }}'
entity_id: light.table_light
service: light.turn_on```
You can't just indent things at random. You indent things that belong to something slightly less indented.
And I probably still messed it up but it's an improvement 😄
If you're going to stick with HA it's really important (hell, critical) you understand YAML
or JSON
i didnt indent that, i just pasted the code i was given
You pasted it with incorrect indentation. Don't blame the pasting.
You still need to proof read things.
I don't often use the 🤢 emoji... but when I do 😉
Remote 1: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'rgb_fakepixel1' is undefined
i would really like it if home assistant could stop deselecting all the text i have selected the moment i get 2 pixel too far from the line im trying to select
TIL that HA is to blame for everything.
it does it on both chrome and firefox
Two different browsers? Must be the fingers then.
and its the only thing ive ever seen anywhere that does it
most things dont care if you go outside the line a little, because thats just what happens when you move a mouse
wrists arent made to move a perfectly straight line
hell, notepad plus doesnt even care if i leave the window
Home Assistant does not do that in any of it's editors
im pretty sure i could connect a second screen and move my mouse there and it wouldnt loose my selection
Can we get back on topic? What's your issue?
I left the window to write this, and it's still selected
it does when youre trying to select text in the logs
i mean you move your mouse while still holding left click to select it
This is #templates-archived, not #complainabouteverything
brightness: '{{ states.sensor.brightness_fakepixel1.state }}'
rgb_color:
- '{{ (rgb_fakepixel1[0],rgb_fakepixel1[1])|join|int(0,16) }}'
- '{{ (rgb_fakepixel1[2],rgb_fakepixel1[3])|join|int(0,16) }}'
- '{{ (rgb_fakepixel1[4],rgb_fakepixel1[5])|join|int(0,16) }}'
entity_id: light.table_light
service: light.turn_on```
i know why this doesnt work
that's clearly #the-water-cooler
rgb_fakepixel1 isnt a valid value because fakepixel1 is supposed to be a sensor
I'm surprised that ever worked when you tested it

thats why im here
Well, where do you think the data is?
so, how do i change that code to work with the sensor?
i dont know
somewhere in the ram
I'm done...
No-one can tell you where the data is. You're the one providing it.
Our crystal balls clearly aren't working today.
Question: ~8ball when will the crystal ball work
Answer: As If
rgb_fakepixel1:
friendly_name: "RGB Fake Pixel 1"
value_template: '{{ states.light.fake_neopixel_1.attributes.rgb_color }}'```
And what does {{ states.light.fake_neopixel_1.attributes.rgb_color }} give you in
> Templates?
i have never been asked the question "where is the data"
gonna be honest, that one threw me a teeny tiny bit
I'm very close too, Rob
the rgb fake pixel 1 is (71, 71, 255),
its 3 integers in a string, as we discussed earlier
or a template
or whatever we are calling this
does that count as a matrix?
and im sorry that i dont know what "where is the data" is supposed to mean
Well I wouldn't expect that to be a string. Your template was outputting a string.
well i was told my sensor was outputting a string
how do i work with a tuple then?
Your sensor was. That tuple isn't a string, your incorrect template transformed it into a string.
You Google it.
how is my template incorrect?
Man. The volunteers in here give up a lot of their time to help people out. They help with all kinds of questions and have a ton of patience for newbies. But this is the first time I've seen so many people give up on someone.
And I take no pleasure in admitting that I've run out of patience too. Good luck.
as someone who also voluntarily helps out on a different server, i completely understand the frustration of dealing with someone like me
You were handed a link to a complete working solution, that you butchered randomly 🤷
i also understand myself here, because as a volunteer i wouldnt act this way
You also clearly need to read the templating docs
That'd be over an hour and a very different solution ago
i "butchered" that code under the assumption that it could be made to work
That abomination would never work
It can be
If you read the templating docs
And learn how templates work
i made the change to the what_colour code so that the name would work with my sensor, which i assumed to be outputting a string
then i realized that it probably wont work because it needs to first get the data from the sensor
See the forum post you were linked to
so i asked about that, and them im informed that my sensor outputs a TUPLE
Probably also ditch the intermediate sensor
Until it works in the Templates test screen, it won't work in an automation
the problem is that i cant see where the guy got his "what_colour" string from
BTW, just a plug for pnbruckner's contributions on the forum. He's patient, provides complete solutions, and reads the core code to figure out how something works, whether it should work, or why it doesn't
believe that guy when he says something
thats also kind of my problem
i keep getting bits of solutions
and then i need to change something else
and it keeps getting more complicated until i arrive at a point where i have no idea why i have some piece of code
so i dont need the sensor anymore?
That, bluntly, suggests you're not taking the time to stop and learn the platform...
i can definitely for sure delete that?
A case of the sighted leading the blind, and the blind continually wandering in the wrong direction
i dont need to learn the platform, i need this one thing to work
no its a case of the sighted telling the blind to "turn right" and then only telling them to turn left again once they ran into the wall and posted a log file
i just need 1 piece of code that will make one lamp take the colour and brightness values from another lamp
i dont need an instruction on how to apply a string to a lamp unless i also get an instruction on where to get the string from
Today you need one piece of code. Then you'll be back in the future asking more stupid questions because you didn't learn anything this time.
i dont wanna have to spend 15 years reading through the absolutely massive list of things you can do in home assistant
'Give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime.'
The experts here didn't spend 15 years.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
teach a man to fish and he will be occupied for 8 hours trying to catch a fish, give a man a fish and hell just have his fish in 5 seconds
Bluntly, if you don't want to learn how HA works, HA isn't a good choice for you. Go pick something more pointy-clicky.
im not gonna actively avoid trying to learn things
but i need to know how to do the thing
But you are...
You're avoiding learning. You said yourself you just want to be given the answer.
then in the future ill know "oh, last time i did this thing"
@quaint saffron http://slash7.com/2006/12/22/vampires/
Honestly all the time spent complaining could have been spent reading the docs and you'd be able to solve your own problem by now
i just need to know where to get the string from the light
And, that's been answered, more times than I can count
where?
you said i should look at the forum post i was linked, i said i dont see where he gets his string from
and thats the last time we actually talked about the string
https://discordapp.com/channels/330944238910963714/672223497736421388/730524183343136778
https://discordapp.com/channels/330944238910963714/672223497736421388/730524517675565157
tbh I got sad when I continued to scroll up, so I'll just leave it at those two
usually when someone asks me "hey, i made this thing on an arduino, why doesnt my code work" i go "heres your mistake, heres the fixed version, heres how to avoid it in the future", not "read the refrence section and LEARN"
those two
the data it gives me is a tuple
as we have established
the tuple is appearently useless
because i need a string
@quaint saffron Go and read through the " Before You Ask:" section of #rules last warning!
Hi all, maybe an extra set of eyes can help me. In HA, i get values for the two attributes, but the statement always go to the 'else' https://pastebin.com/7K6v7XYg
Am I going about getting the values of the attribute the wrong way?
What is the output of the template in the templates dev tool?
I can't get one
if (state_attr('device_tracker.cgs9p', 'rssi') | int) > (state_attr('device_tracker.rha_cgs9p', 'rssi') | int)? You're checking that x is greater than x?
That'll always be false.
You could test with:
{{ state_attr('device_tracker.cgs9p', 'rssi') | int }}
{{ state_attr('device_tracker.rha_cgs9p', 'rssi') | int }}
Oh, different entities... my bad.
yea they look similar but different
@arctic sorrel that returns nothing in the editor
it's just blank
Then the entity_id's are wrong
Are you on 0.112.0?
@rugged laurel i did all of those things before i asked my question, then i got given part of a solution, then i asked "how do i finish making this solution", and now i need to troubleshoot the solution
ya 112.0
Upgrade 😉
and appearently ive already been given the solution for the solution
The top four lines are truncated
but i dont know where
even if the entity_ids are wrong it should produce two zeroes
lemme upgrade
Oh is there a template bug in 112?
The first few lines didn't render correctly.
UI bug, the top 65px are hidden
huh. interesting
and people are telling me that they told me the solution to the solution, and then i ask where it was, i get told read the "before you ask" section
technically, my question is "where did you tell me where to find that?", and im not getting much on the forums for that one, tbh
I believe you're being pointed to that section (by a mod, no less) partly for this:
When you ask your question, display the fact that you have done these things first; this will help establish that you're not being a lazy sponge and wasting people's time. Better yet, display what you have learned from doing these things. We like answering questions for people who have demonstrated they can learn from the answers.
aha! now i get two 0's. at least something is showing now lol
i must be typing the attribute or entity id wrong
Zeroes are good. It means your template is valid and finding something.
lemme double check
i have learned nothing from doing these things because appearently the things i was looking for are unrelated to my issue
If you wanted to learn to build a car, you're probably not going to find a single post that answers all your questions. You have to break down the problem into smaller parts and solve each one.
Do that. Figure out what you don't know and find those answers.
Build upon your knowledge piece by piece.
because appearently im getting a tuple, not a string, and i cannot figure out how to get a string
okay i figured it out! the string attribute output is '-16,'
the comma is throwing it off
i have never told someone "just build your knowledge"
when it trys to convert to int
i usually tell them how to solve their problem
now to find out how to filter out the comma
use replace or [:-1] at the end
this is the equivalent of asking my teacher "whats 15 + 9?" and my teacher going "come on, you know 15 + 9, you can figure this out. i believe in you, champ"
Pretty terrible analogy, if we're honest. If you're been taught addition, you should be able to add any two numbers.
no... this is the equivalent of banging to rocks together
We're trying to teach you 'addition' here, so you can solve your own problems next time.
just tell me how to get a string
The incessant complaining isn't doing you any favours.
dont tell me "go look up how to get a string"
i cant figure out how to get a string
You're far less likely to get help from anyone if you do nothing but piss them off.
im past the point of looking it up
And people are past the point of caring.
i just need to know "this is how you get a string, next time you want a string, this is how you get it"
@rugged laurel sorry not familiar with that, {{ state_attr('device_tracker.cgs9p', 'rssi') [:-1] }} produces blank
just quotes
No space before the [
The [] bit is operating on the result of the preceding function.
ill admit, the analogy doesnt wokr
@quaint saffron please stop complaining. It's getting very old. Put in the tiniest amount of effort. You are obviously not the first person to match light rgb values in a template.
It's just defining the start and end of an 'array' of characters from the original string.
its me, asking my teacher "HOW do i add these together" and my teacher going "you can just figure it out"
In this case, you don't care about the start (which would have been before the colon), only the end.
gotcha. I understand, but still blank when deleting the space
playing around with it now
appearently the only person who has done it uses code that physically cannot possibly work
What person?
It works for others.
If it doesn't work for you, you're doing something wrong somewhere.
also i figured out how the guy got the "what_color" string, he provides it to the function when he calls it
which doesnt work for me because i need it to get the string from the light value of the other light
this is the other guy that tried to have 2 lights match
Build upon your knowledge piece by piece.
thats the only thing i can find
and it only works for brightness, and i dont know how it worked for the second guy there that asked how to do it for rgb
because appearently it shouldnt work
I have no way to test this because I don’t have any lights that can change color
You mean this guy?
the other guy who thanked him and then appearently no longer had any issues
im counting that as "probably worked for him"
That's a major assumption
though there is a chance that it 0 people have done this before
okay, i ended up using split because there was parenthesis at the beggining and end i needed to filter out
Yes. There is also a chance that the sun is made of cotton candy
if youre thinking that his success is too big an assumption, ill gladly go with "literally no one has managed this before me"
it should work now. thanks for the tip about upgrading. I never would have realized that
because that was the only one i found
if youre thinking that his success is too big an assumption, ill gladly go with "literally no one has managed this before me"
You're definitely not that special.
ok
cool
then just get me like a forum post from a guy who did manage have 2 lights match each other, cause i cant
i got one guy who applied a string to a light, but i dont know how to get a string FROM a light
Wow. We're on to demands now?
you can take it like that if you want to
Haven't we been there?
I'm surprised the hammer hasn't come down already.
You can lead a horse to water, you can put its face in the water, but the horse can still choose to drown before it drinks
Last try, because I'm a glutton for banging my head against the wall, apparently.
https://community.home-assistant.io/t/question-about-arrays-in-templates-keys-how-to-find-key-if-i-know-the-value/78028
Now you have the template (from your sensor). You have the means of pulling out values from a tuple. The rest is up to you.
And yet, I feel this saga hasn't ended.
thanks, thats exactly what i needed, now i know how to get values from a tuple, now i can do it again in the future, my knowledge has expanded
Easiest way to achieve switch/case with if/elif?
that's kinda open-ended
there's the way:
{% if trigger.entity_id == "binary_sensor.garage_water_heater_leak_heartbeat" %}
"Water Heater heartbeat missed!"
{% elif trigger.entity_id == "binary_sensor.uph_humidifier_leak_heartbeat" %}
"Upstairs Humidifier heartbeat missed!"
{% elif trigger.entity_id == "binary_sensor.kit_refrigerator_leak_heartbeat" %}
"Refrigerator heartbeat missed!"
{% elif trigger.entity_id == "binary_sensor.mbath_vanity_leak_heartbeat" %}
"Master Bathroom Vanity heartbeat missed!"
{% else %}
"Espresso Machine heartbeat missed!"
{% endif %}
but there are other ways to skin that cat
Yep, seems to be the way. Sorted 🙂
I like the dictionary method
Mine is the "I came from some other language and am looking for something that looks like it" method
lowest-common-denominator programming 🙂
{% set map = {
"entity_1": "thing", "entity_2": "other thing"
} %}
{{ map.get(trigger.entity_id, "default") }}
It's a tad cleaner and a lot shorter my way
That IS cleaner! Didn't realise there was a get function. What about scope of the variable setting? Would I need to set the same map for both a value_template and a icon_template? Or does it persist the variable for the entity?
Figured that's likely the case. May even be safer for me to just use an input_text which is modified through AppDaemon based on state changes. That way I can maintain the map in a single location.
Though to be fair, likely overkill for "who unlocked the door" 😛
Lol
Hi all may I ask a question about tempalting. Question is make a very long template line readable for example to continu on a next line / row
Don't ask to ask, just ask your question. Then people can answer when they're around.
When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:
- What version of the Home Assistant are you running? (remember, last isn't a version)
- What exactly are you trying to do that won't work?
- Is the problem uniform or erratic?
- What's the exact error message?
- When did it arise?
- What exactly don't you "get"?
- Can you share sample code, ideally with line errors where the error occurs?
value_template: "{{ states('sensor.time') == (state_attr('input_datetime.spray_moment_morning', 'timestamp') | int | timestamp_custom('%H:%M', False)) or (states('sensor.time') == state_attr('input_datetime.spray_moment_afternoon', 'timestamp') | int | timestamp_custom('%H:%M', False)) or states('sensor.time') == (state_attr('input_datetime.spray_moment_evening', 'timestamp') | int | timestamp_custom('%H:%M', False)) }}"
I have this as one complete long line.....
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
It's likely going to be easier to spread over multiple lines, in a multi-line template, and test all the steps
value_template: >-
{{ states('sensor.time') == (state_attr('input_datetime.spray_moment_morning', 'timestamp') | int | timestamp_custom('%H:%M', False))
or
(states('sensor.time') == state_attr('input_datetime.spray_moment_afternoon', 'timestamp') | int | timestamp_custom('%H:%M', False))
or
states('sensor.time') == (state_attr('input_datetime.spray_moment_evening', 'timestamp') | int | timestamp_custom('%H:%M', False)) }}
A for loop would probably be the way I would go about it
Splitting it over multiple lines also highlights a possible bracket issue 😉
I tried a few ways. And it looks OK when I tried in the templating service in Hassio. But when compiling it / restarting HASSIO most of the ways give error
what error?
Hey - probably a noob question here, but I've tried to create a new template for a sonoff sensor, as the temperature value needs dividing by 100 to render correctly. I've spent hours looking around for why it's not working, and I have no idea. Is there a good guide that anyone can point me to that highlights how you get custom templates to render correctly for an entity? I'm using this integration https://github.com/AlexxIT/SonoffLAN/tree/v2.0.0#sonoff-th-and-pow and guide to implement the template but not having much luck
Ugh @arctic sorrel it seems this worked. is the " value_template: >- " the sentence the make multiple lines templating
{% set entities = ['spray_moment_morning', 'spray_moment_afternoon', 'spray_moment_evening'] %}
{% set ns = namespace(value=false) %}
{% for entity in entities %}
{% if (states('sensor.time') == state_attr('input_datetime.' + entity, 'timestamp') | int | timestamp_custom('%H:%M', False)) and ns.value == false %}
{% set ns.value = true %}
{% endif %}
{% endfor %}
{{ns.value}}
I don't know why I thought that would be cleaner, but it could be more readable 🤷
or it's garbage and belongs in the trash 🤷
Also a nice one ! gives me some inspiring for other stuff. Thx
sensor:
- platform: template
sensors:
temperature_th:
friendly_name: Temperature
device_class: temperature
value_template: "{{ (state_attr('switch.sonoff_1000abcdefg', 'temperature')|int)/100 }}"
``` Try that @thorny snow - replace the entity in there obviously
Thank you - I'll give that a try!
how do you paste / post the code like you did above here tinkerer?
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:
```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G
after the first three ticks you can add a language and it will provide syntax highlighting for said language
```yaml
blah
```
the list of languages supported is actually pretty impressive
Ok I tried the YAML above, with my entity put in, but the value is still showing as it's original - ( I have it as a badge at the moment, but even adding it as an entity card doesn't change it). I'm sure I'm missing a really simple step here to get that template to load?
Did you restart home assistant?
It won't change the original entity
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
Also the part about testing 😉
hah, yeah I'm testing it now too, I don't think it's getting the value from the sensor at all in the template
ok so testing {{ (state_attr('switch.sonoff_a40000678', 'temperature')|int)/100 }} and {{ (state_attr('sensor.sonoff_a40000678', 'temperature')|int)/100 }}, just comes back with 0.0 on the dev tools test - the value on my badge at the moment shows 2212, so something's not quite right
{{ state_attr('switch.sonoff_a40000678', 'temperature') }}
``` what does that show?
"None"
There's your problem 😉
Either the entity is wrong, or the attribute is wrong
{{ states('switch.sonoff_a40000678') }}
and
{{ states.switch.sonoff_a40000678.attributes }}
Aha, thanks. So I can get it working without the division on it now, adding the division part changes it from "2212" to 0.0
{{ state_attr('sensor.sonoff_a400006786_temperature', 'temperature') }}
{{(state_attr('sensor.sonoff_a400006786_temperature', 'temperature')|int)/100 }}
Returns
"2212"
0.0

sensor != switch
{{ state_attr('sensor.sonoff_a400006786_temperature', 'temperature') }}
{{ (state_attr('sensor.sonoff_a400006786_temperature', 'temperature')|int) }}
Though, I'd expect the state of a sensor called temperature to be a temperature 🤔
Casting to an int is forcing it to 0 for some reason:
"2212"
0
That would probably explain why it's not displaying correctly in the first place, then!
{'manufacturer': 'coolkit', 'model': 'ZCL_HA_DEVICEID_TEMPERATURE_SENSOR', 'sw_version': 'NON-OTA-GL v???', 'subDevId': '"9738781b004b1200"', 'parentid': '"1000deebda"', 'temperature': '"2212"', 'humidity': '"7859"', 'battery': '100', 'trigTime': '"1594307996017"', 'cloud': '"online"', 'unit_of_measurement': '°C', 'friendly_name': 'Graysons Room', 'device_class': 'temperature'}
yes, it does
It should be possible to fix that with templates at least, but it's not going to be fun
ok cool - this is going to require food and beer
{{ state_attr('sensor.sonoff_a400006786_temperature', 'temperature').split('"')[1] }}
yeaaaasss
{{ (state_attr('sensor.sonoff_a400006786_temperature', 'temperature').split('"')[1])|int /100 }}
22.12
Excellent, thank you so much!
I would too
is there any way to have a template output a non-string? I'm thinking about rest since the data has to be sent as json rather than a string
well yes, but actually no
so using '{x | tojson }' would work?
templates always return strings even if the output appears to be another data type
so how does rest work then? else I'm just stuck getting a 400 error
can you prime it to expect a string argument?
yup
Content-Type: application/json header
switch:
- platform: rest
name: "TV Sync"
resource: http://192.168.0.94:5000/tv_sync
body_on: '{"active": "true"}'
body_off: '{"active": "false"}'
is_on_template: '{{ value_json.active }}'
headers:
Content-Type: 'application/json'
is it literally the order being the issue here?
if so the docs might need a slight edit
was doing that earlier, no luck
is that a valid request to make for your TV python/flask program on your PC?
I'm sending it to a python/flask program on my PC
"TV Sync" is just an alias as I have a tv as one of my monitors lol
program takes the colour and sends it back to home assistant to set the led strip on the read of my tv
this is to make a switch accessible from the overlay for the program
I mean I don't know the syntax with which rest sends the request
postman is fine with the json in the body, just not as a string ofc
what does curl http://192.168.0.94:5000/tv_sync show
this being done from the command line on the pi?
or wherever you have a terminal, yeah
or just go to http://192.168.0.94:5000/tv_sync in a web browser
500 error
Traceback (most recent call last):
File "D:\Python\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "D:\Python\lib\site-packages\flask\app.py", line 1953, in full_dispatch_request
return self.finalize_request(rv)
File "D:\Python\lib\site-packages\flask\app.py", line 1968, in finalize_request
response = self.make_response(rv)
File "D:\Python\lib\site-packages\flask\app.py", line 2097, in make_response
raise TypeError(
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
does it require authorization at all?
shouldn't
have you been able to POST to it at all?
i'd assume not if it's not accepting GET requests
postman seemed to do fine
although that was from the same machine
I did make sure to make a firewall exception though
welp someone smarter than me in this regard will probably need to help
500 is internal serve error. It (the server) must be crashing with that request.
i think that's the stack trace above
still running it would seem
It must have passed authentication by then. Unless the error is in the authentication
the call is coming from inside the house
👀
Tried with curl or command line first?
ngl I don't know how to access command line on my pi in such a way I can use curl
does the ssh and web terminal have curl?
It can be from anywhere. Doesn’t have to be from pi - as long as the url is accessible.
500 server error
just to clarify that was from cmd on my laptop on the same network
not reiterating old news
Then something Is wrong. You need to fix or do some diagnostic on that before doing it from HA.
so I can now curl from the command line on the pi with minimal issues (it actually sends the data at least), literally just the template that doesn't work
curl --header "Content-Type: application/json" \ --request POST \ --data '{"active": "true"}' \ http://192.168.0.94:5000/tv_sync
although I do get this
Truecurl: (3) URL using bad/illegal format or missing URL
curl: (3) URL using bad/illegal format or missing URL
That looks pretty Googleable.
Not sure if this is for in here, or #frontend-archived - I created a template earlier (thanks to @arctic sorrel !) to correctly format my temperature sensor. I've added that template to my config.yaml, and restarted HA. But I can't see how I get that new template to load, the values showing when I add that sensor (as a gauge, for example, or a badge), are still showing the default value, not the new template value. Am I missing some config somewhere to tell HA to use that new template?
As I mentioned before.... that template sensor does not replace your original entity
You now have another entity
hellloo, i wanted to set an input_number when an automation triggers. But it's not working,...
data:
value: '{{states.sensor.arbeit_home.attributes.duration_in_traffic[0:3]|float}}'
entity_id: input_number.traffic_last_checked
service: input_number.set_value
The output of the term in value is 25.0 :/
You now have another entity
@arctic sorrel That's where i was getting confused, I couldn't see it on the entity selector, but now I've looked again, I can, it's just not named what I was expecting. But that makes perfect sense now, thanks again!
Use data_template instead of data @tulip viper
No s 😉
🤣
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
- Rule 1 and rule 2 (https://www.home-assistant.io/docs/automation/templating/#important-template-rules)
Yeah it's a pita on mobile
Try template editor on mobile and thank me later 😝
Heh I might have tried it
I cannot figure out a way to clear default text on iPhone in the template editor. That sucks ass.
The default text is useless and many people think it is real code and afraid to touch it.
Hmm, no long press context menu in iOS?
No long press.
Heh gg apple
There is in iOS, just not allowed in code mirror fields
It is probably intercepting keyboard or text changed events to render
Android ftw
Someone try that on iPhone. Doesn’t work like that in iPhone.
Can you actually select all and clear text?
You can, but for some reason not in code mirror editors
Actually, apparently not in Android
It'll select but you can't clear
And the cursor keeps jumping to the head of the file if you type
What good does it do if you can select and not clear? 🤣
Copying the very useful sample text 🙂
😂
Lol
You can actually do it on iOS too, as long as the keyboard is closed
Hmm. Let me try that
thanks for the help.. worked now
Is it possible to query entities from a specific integration?
I can’t do shit. Selecting text is a joke.
Kinda anyway
Yeah the rendering is a mess on mobile. I begrudgingly retract my apple snark
@warped hornet I'm not aware of any way to do that, I don't think the information is available
Hmm, the information is in the frontend, so I would suppose it is there somewhere
Might be at the device level but entities typically don't care
What specific integration? If you have code for it, you can access all the entities
Unless it's something domain specific
It is the ESPHome integration
I would like to fetch a list with all my esphome entities
Entity naming convention would make it trivial
You might want to think of other way of doing it. That’s not a good practice usually
Or do it outside.
@hollow bramble yea, that is my current idea, however I don't really like it that way
Probably in the device registry
Is it possible to access the device registry in any way?
Nope, everything in templates is reliant on the state machine
A simple “clear text” button/link would be nice in the template editor.
I hate Ui coding. 😝
Well it hates you too 
Hi, I'm trying to count the number of media players on at any one time and have this as my template but I'm not sure it's correct as it's not showing a numner in developer tools when I use
{{ states("sensor.media_players_on") }}
sensors:
media_players_on:
unit_of_measurement: 'on'
value_template: >
{% set media_players = [
states.media_player.kitchen_display,
states.media_player.living_room_mini,
states.media_player.living_room_sonos,
states.media_player.office_sonos,
states.media_player.bedroom
] %}
{{ media_players |
selectattr('state','eq','on') | list | count }} ```
That's an interesting way to get around the 15 line limit... and somehow takes even more screen space.
did you test the template before putting it in the sensor?
It wasnt intentional to do that...
the template is based on the same one I have for lights but I changed the reference from lights to media players
that one works
K, that doesn't really answer the question though 😉
No is probably the answer 🙂
@stone lintel I'm working on the exact same thing. I think you need to map your entity_id's to actual entities before applying your filter
Thanks, I think I've managed to get it working with
{% set media_players = [states.media_player.kitchen_display, states.media_player.living_room_mini, states.media_player.living_room_sonos, states.media_player.office_sonos,states.media_player.bedroom] %} {{ media_players | selectattr('state','eq','playing') | list | count }}
You can simplify even further.
@queen meteor How would you map a list of entity_ids (simply strings) to an list of actual entities ?
Not sure what you mean. Put them inside states?
Depending on where this is used, you should probably leave it as it is
@queen meteor Such that [<id1>, <id2>, <id3>] would become [<entity obj1>, <entity obj2>, <entity obj3>]
If you show the code, someone might help. I think I know what you are trying to do.
It is usually never a problem. Just share the code.
usually never
You can simplify even further.
@queen meteor oooh how would I do that?
carefully
@queen meteor Something like:
{% set hosts = ['bedroom_ceiling', 'coffee_machine', 'fan_power_plug'] %}
{% set entity_ids = hosts | map('regex_replace', '^(.*)$', 'binary_sensor.\\1_status') | list %}
{% set entities = <map entity_id to states(entity_id)> | list %}
You can’t convert strings to objects like that unfortunately.
Wherever you are going to use entities, you need to figure out a way to use those strings.
Yea, ended up with a group instead and this template {{ states|selectattr('entity_id','in',state_attr('group.esphome_hosts_connected_status','entity_id'))|selectattr('state','eq','on')|list|count }}
Hello all, need a quick hand with the logic in one of my templates for my HVAC.
I recently gained some roommates and I need HASS to track multiple users to determine what temp the HVAC is set to. Im pretty sure 'home' and 'away' are fine. Im just not sure how to handle the 'near home' portion, where one roommate entering the 'near home' state would not raise the temp on someone thats already home. This is what I have so far.
https://hasteb.in/xapiceci.py
there is no near_home state unless you use proximity sensor, and the states are home and not_home
there is no
near_homestate unless you use proximity sensor, and the states arehomeandnot_home
@queen meteor Its a custom zone, and yes it works and has worked fine when it was just me here in the house.
ok... custom zone works - if you use proximity sensor you can even tell if the person is traveling towards or away from your home
Ill get to that when I get to it. LOL
Right now, Im just trying to get the basics of this thing working.
Updated to correct the 'not_home' section of the data template.
I just need to figure out the logic for 'near_home'
https://hasteb.in/eyixohuy.py
use long/lat for custom zone, and use zone enter and zone leave events to know if you are near a zone
use that as a trigger point - you could also use for: x minutes to ensure they are in that zone and not just passing through
Thats fine and all, I just trying to figure out how to do that for multiple people.
What I dont want happening is someone to be home, and another person enters the near_home zone, and the HVAC turns up the temperature.
The logic 'or' logic makes sense in the template for determining if "anyone" is home.
The 'and' logic makes sense in the template for determining if "everyone" is not home.
I just can't seem to figure out the logic for writing out the 'near-home' without it causing conflicts with anyone being home.
I understand. Best way to do that is use input booleans, and toggle them based on who is at home. Use those input booleans in the automation - that way you can decouple things, and do it cleanly.
you can also use those input booleans for other reasons - like turning on/off home security system, turn lights on/off..etc
So write a condition to not do anything if someone is home using the input booleans?
yup
Ok thanks
Hey all, can I access state timestamp data from templates? For example I want to be able to only do something in a template sensor if a input_boolean has been set to true for x minutes
Something like: if input_boolean is true for 10 minutes then get temp data from entity_1
it feels like I am trying to do something that I shouldnt be doing in templates, but wanted to see
That sounds like an automation with a ‘for:’ clause
@inner mesa yeah I use that often but I need to be able to set the active state of a sensor entity
sorry, I should have mentioned that I am trying to use this within a template sensor
I am trying to take the highest temperature from various sensors and store it in a sensor template. The catch is I want to only use sensor data if my input boolean has been set to true for x minutes
You don’t really ‘store’ things in a template sensor
right, I guess I mean I want the "state" of the sensor to be from a specific sensor
based on input_bool behavior/offsets
You can store the max of a bunch of things in an input_number
And use the trigger I mentioned
I’m wondering if the focus on the template sensor is overlooking a diff solution
I’m not convinced that you do what you want with just a template sensor
I am using template sensor since I eventually want to use it in the generic_thermostat as the source temp
although I think youre onto something, maybe I store the number in input_number, do all the logic using automations, then just render that input_number into a template sensor (instead of trying to do all the logic in templates)
Won’t any entity with a number work?
let me check!
Yeah, that’s how I would do it
entity_id for a temperature sensor, target_sensor.state must be temperature.
So the problem is units, or a type?
its a bit unclear to me, but if I do it using a template sensor then I can just make whatever the input_number is be in degrees F
Units are just a string. They don’t mean anything
ohhh

