1 """The LED BLE integration."""
3 from __future__
import annotations
6 from datetime
import timedelta
9 from led_ble
import BLEAK_EXCEPTIONS, LEDBLE
19 from .const
import DEVICE_TIMEOUT, DOMAIN, UPDATE_SECONDS
20 from .models
import LEDBLEData
22 PLATFORMS: list[Platform] = [Platform.LIGHT]
24 _LOGGER = logging.getLogger(__name__)
28 """Set up LED BLE from a config entry."""
29 address: str = entry.data[CONF_ADDRESS]
30 ble_device = bluetooth.async_ble_device_from_address(hass, address.upper(),
True)
33 f
"Could not find LED BLE device with address {address}"
36 led_ble = LEDBLE(ble_device)
39 def _async_update_ble(
40 service_info: bluetooth.BluetoothServiceInfoBleak,
41 change: bluetooth.BluetoothChange,
43 """Update from a ble callback."""
44 led_ble.set_ble_device_and_advertisement_data(
45 service_info.device, service_info.advertisement
48 entry.async_on_unload(
49 bluetooth.async_register_callback(
53 bluetooth.BluetoothScanningMode.PASSIVE,
57 async
def _async_update() -> None:
58 """Update the device state."""
60 await led_ble.update()
61 except BLEAK_EXCEPTIONS
as ex:
64 startup_event = asyncio.Event()
65 cancel_first_update = led_ble.register_callback(
lambda *_: startup_event.set())
71 update_method=_async_update,
72 update_interval=
timedelta(seconds=UPDATE_SECONDS),
76 await coordinator.async_config_entry_first_refresh()
77 except ConfigEntryNotReady:
82 async
with asyncio.timeout(DEVICE_TIMEOUT):
83 await startup_event.wait()
84 except TimeoutError
as ex:
86 "Unable to communicate with the device; "
87 f
"Try moving the Bluetooth adapter closer to {led_ble.name}"
92 hass.data.setdefault(DOMAIN, {})[entry.entry_id] =
LEDBLEData(
93 entry.title, led_ble, coordinator
96 await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
97 entry.async_on_unload(entry.add_update_listener(_async_update_listener))
100 """Close the connection."""
103 entry.async_on_unload(
104 hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_stop)
110 """Handle options update."""
111 data: LEDBLEData = hass.data[DOMAIN][entry.entry_id]
112 if entry.title != data.title:
113 await hass.config_entries.async_reload(entry.entry_id)
117 """Unload a config entry."""
118 if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
119 data: LEDBLEData = hass.data[DOMAIN].pop(entry.entry_id)
120 await data.device.stop()
None _async_stop(HomeAssistant hass, bool restart)
None _async_update_listener(HomeAssistant hass, ConfigEntry entry)
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)