When I paste the following into the Template Editor, it returns a correct on / off response. But when I add it to my config as a value_template, I get errors:
"{{ 'on' if "FD:81:5F:77:95:FF (Gregory's Pixel Buds Pro 2)" in state_attr('sensor.pixel_9_pro_xl_bluetooth_connection', 'connected_paired_devices') else 'off' }}"
When I put this into my config like this:
- platform: template
sensors:
ear_buds:
value_template: "{{ 'on' if "FC:91:5D:65:95:FF (Gregory's Pixel Buds Pro 2)" in state_attr('sensor.pixel_9_pro_xl_bluetooth_connection', 'connected_paired_devices') else 'off' }}"
friendly_name: "Ear Buds"
I get the following error when I try to validate:
Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/configuration.yaml", line 149, column 9
expected <block end>, but found '<scalar>'
in "/config/configuration.yaml", line 149, column 38
I kind of figured that the apostrophe in Gregory’s might be the issue, so I changed the name of the Bluetooth device in my Android settings. So now it shows up as a connected device as FC:91:5D:65:95:FF (Pixel Buds Pro 2) in Home Assistant.
I then used the helper template integration to add it as a binary sensor as suggested. Under “Template Optons” I put this:
“{{ ‘FC:91:5D:65:95:FF (Pixel Buds Pro 2)’ in state_attr(‘sensor.pixel_9_pro_xl_bluetooth_connection’, ‘connected_paired_devices’) }}”
The new sensor loads with no issues now, but shows the state as “off” all of the time. If I paste this same thing into the Template Editor it returns as “True” when I have the ear buds on, and “False” when I take them out. Working this way as it should.
If I only include the MAC address part of the attribute in the template statement, it doesn’t work at all in either method. Seems to need the whole thing, maybe because the attributes are returned as a LIST, and not a STRING.
Using search() will allow you to use just the MAC and will work whether the list is empty, contains just the desired device, or contains multiple items.