import asyncio
from homeassistant.components import bluetooth
from homeassistant.components.bluetooth import BluetoothChange, BluetoothServiceInfoBleak
from homeassistant.core import callback
from bleak import BleakClient
TARGET_DEVICE_ADDRESS = "11:22:33:44:55:66"
CHARACTERISTIC_UUID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
@service
async def ble_scan(action=None, id=None):
scanner = bluetooth.async_get_scanner(hass)
devices = await scanner.discover(timeout=10.0)
log.info(f"Found {len(devices)} devices:")
try:
ble_device = await bluetooth.async_ble_device_from_address(hass, TARGET_DEVICE_ADDRESS)
if ble_device is None:
log.error(f"Error: A device with address {TARGET_DEVICE_ADDRESS} could not be found.")
# Handle the error (e.g., exit the function, raise an exception)
else:
async with BleakClient(TARGET_DEVICE_ADDRESS) as client:
log.info("reading client")
# if client.is_connected:
# # Read the characteristic value
# value = await client.read_gatt_char(CHARACTERISTIC_UUID)
# log.info(f"Read value: {value}")
# # You can then log this value to Home Assistant as a sensor state
# # Example (requires pyscript specific calls):
# # pyscript.set_state('sensor.my_ble_sensor', value.decode('utf-8'))
# return value
# else:
# log.info("Failed to connect")
except Exception as e:
log.error(f"An error occurred: {e}")
log.info("ble_scan ended")
2026-01-01 23:42:36.750 INFO (MainThread) [custom_components.pyscript.file.bluetooth.ble_scan] Found 37 devices:
2026-01-01 23:42:36.750 DEBUG (MainThread) [custom_components.pyscript.eval] file.bluetooth.ble_scan: calling async_ble_device_from_address(<HomeAssistant RUNNING>, "11:22:33:44:55:66", {})
2026-01-01 23:42:36.751 DEBUG (MainThread) [custom_components.pyscript.eval] file.bluetooth.ble_scan: calling BleakClient("11:22:33:44:55:66", {})
2026-01-01 23:42:36.757 DEBUG (MainThread) [custom_components.pyscript.eval] file.bluetooth.ble_scan: calling error("An error occurred: 'NoneType' object has no attribute 'address'", {})
2026-01-01 23:42:36.757 ERROR (MainThread) [custom_components.pyscript.file.bluetooth.ble_scan] An error occurred: 'NoneType' object has no attribute 'address'
2026-01-01 23:42:36.758 DEBUG (MainThread) [custom_components.pyscript.eval] file.bluetooth.ble_scan: calling info("ble_scan ended", {})
2026-01-01 23:42:36.758 INFO (MainThread) [custom_components.pyscript.file.bluetooth.ble_scan] ble_scan ended
I keep getting the above error An error occurred: 'NoneType' object has no attribute 'address', it seems to be coming from BleakClient. It doesn’t matter if I use the TARGET_DEVICE_ADDRESS or ble_device.
Any idea how I can get hold of a client to read_gatt_char a characteristic?