Template binary sensors to indicate bluetooth device connected in Phone App become unavailable

This is my first question on here, so please be gentle. Apologies if this is something obvious, but it’s not to me and I couldn’t find anything else similar to this. I was also unable to find anything on creating binary sensors for the application for which I am using them, so maybe I have got something wrong in the template.

Anyway, I am using the Android app to bring in the bluetooth connection(s) sensors for two phones:

sensor.rob_s_phone1_bluetooth_connection
and
sensor.rob_s_phone2_bluetooth_connection

I have setup a number of template binary sensors in configuration.yaml to show the connection state of various devices, two examples below:

      # Rob's Phone1 Bluetooth Watch Connection sensor
      rob_s_phone1_bluetooth_watch:
        friendly_name: 'Rob''s Phone1 Bluetooth Watch'
        device_class: connectivity
        icon_template: >-
          {% if is_state('binary_sensor.rob_s_phone1_bluetooth_watch', 'on') %}
            mdi:watch-vibrate
          {% else %}
            mdi:watch-vibrate-off
          {% endif %}
        value_template: "{{ 'XX:XX:XX:XX:XX:97' in state_attr('sensor.rob_s_phone1_bluetooth_connection', 'connected_paired_devices') }}"
      # Rob's Phone2 Bluetooth Laptop Connection sensor
      rob_s_phone1_bluetooth_laptop:
        friendly_name: 'Rob''s Phone1 Bluetooth Laptop'
        device_class: connectivity
        icon_template: >-
          {% if is_state('binary_sensor.rob_s_phone1_bluetooth_laptop', 'on') %}
            mdi:laptop
          {% else %}
            mdi:laptop-off
          {% endif %}
        value_template: "{{ 'XX:XX:XX:XX:XX:FA' in state_attr('sensor.rob_s_phone1_bluetooth_connection', 'connected_paired_devices') }}"

I have the same binary sensors created for sensor.rob_s_phone2_bluetooth_connection.

These have been working fine for the last few days since I created them, until early this morning, when the sensors for sensor.rob_s_phone1_bluetooth_connection all became unavailable at 07:02.07 and have been like that for coming up 11 hours now.

Bluetooth Connections Unavailable

The equivalent sensors for sensor.rob_s_phone2_bluetooth_connection are all fine.

I haven’t restarted Home Assistant yet, as I wanted to find/understand the root cause, so I can prevent it happening again, as I need these sensors to be reliable, as I am triggering automations on connect/disconnect of certain bluetooth devices.

I wondered if I needed to use a filter for the MAC addresses, in case the source sensor sensor.rob_s_phone1_bluetooth_connection became temporarily unavailable at around 07:02:07, leaving the template sensors still unavailable? However, I am not sure how to do this and cannot see anything to indicate this in the Logbook or History. The one thing that may be relevant is that the source sensor sensor.rob_s_phone1_bluetooth_connection shows that it connected to the watch at the exact same time as the other binary sensors for sensor.rob_s_phone1_bluetooth_connection becoming unavailable. The watch is also the 1 device showing as connected to the source sensor.

Can anyone shed some light on what might be causing this and offer any suggestions on how to fix it / improve reliability, so it doesn’t do it again? Many thanks.

UPDATE: The sensors came back online at 18:57:48 this evening, almost exactly 12 hours after they went offline. This coincided exactly with the watch disconnecting from Bluetooth. The watch has disconnected and reconnected a few times since then and they have not become unavailable again despite this.

UPDATE 21/02/2021: This has happened again and I have spotted that the attributes for sensor.rob_s_phone1_bluetooth_connection are no longer visible for the entity. Additionally, the following is showing in the log, which is actually how I found that the attributes are no longer available, as it is trying to evaluate NoneType. Are the disappearing attributes a bug in the Android app? Note, this is not resolved by restarting Home Assistant and the error is issued again on restart.

2021-02-21 18:52:39 ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template("{{ '08:97:98:0E:93:97' in state_attr('sensor.rob_s_phone1_bluetooth_connection', 'connected_paired_devices') }}")
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 353, in async_render
render_result = compiled.render(kwargs)
File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 1090, in render
self.environment.handle_exception()
File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 832, in handle_exception
reraise(*rewrite_traceback_stack(source=source))
File "/usr/local/lib/python3.8/site-packages/jinja2/_compat.py", line 28, in reraise
raise value.with_traceback(tb)
File "<template>", line 1, in top-level template code
TypeError: argument of type 'NoneType' is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 462, in async_render_to_info
render_info._result = self.async_render(variables, **kwargs)
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 355, in async_render
raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: TypeError: argument of type 'NoneType' is not iterable

Hi friend!

Same thing here!! Im tring to find some how to solve it, but I cannot find the way. Have you some news???

{% set items = state_attr('sensor.rob_s_phone1_bluetooth_connection', 'connected_paired_devices') %}
{{ items is iterable and 'XX:XX:XX:XX:XX:97' in items }}

Not sure if this helps, but I was using a Galaxy S9, which regularly had this problem and once I upgraded to a Galaxy S21 it stopped. It looks like the change in code that @petro provided may also be worthwhile making.