Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The Medcom BLE integration."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 
8 from bleak import BleakError
9 from medcom_ble import MedcomBleDeviceData
10 
11 from homeassistant.components import bluetooth
12 from homeassistant.config_entries import ConfigEntry
13 from homeassistant.const import Platform
14 from homeassistant.core import HomeAssistant
15 from homeassistant.exceptions import ConfigEntryNotReady
16 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
17 from homeassistant.util.unit_system import METRIC_SYSTEM
18 
19 from .const import DEFAULT_SCAN_INTERVAL, DOMAIN
20 
21 # Supported platforms
22 PLATFORMS: list[Platform] = [Platform.SENSOR]
23 
24 _LOGGER = logging.getLogger(__name__)
25 
26 
27 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
28  """Set up Medcom BLE radiation monitor from a config entry."""
29 
30  address = entry.unique_id
31  elevation = hass.config.elevation
32  is_metric = hass.config.units is METRIC_SYSTEM
33  assert address is not None
34 
35  ble_device = bluetooth.async_ble_device_from_address(hass, address)
36  if not ble_device:
37  raise ConfigEntryNotReady(
38  f"Could not find Medcom BLE device with address {address}"
39  )
40 
41  async def _async_update_method():
42  """Get data from Medcom BLE radiation monitor."""
43  ble_device = bluetooth.async_ble_device_from_address(hass, address)
44  inspector = MedcomBleDeviceData(_LOGGER, elevation, is_metric)
45 
46  try:
47  data = await inspector.update_device(ble_device)
48  except BleakError as err:
49  raise UpdateFailed(f"Unable to fetch data: {err}") from err
50 
51  return data
52 
53  coordinator = DataUpdateCoordinator(
54  hass,
55  _LOGGER,
56  config_entry=entry,
57  name=DOMAIN,
58  update_method=_async_update_method,
59  update_interval=timedelta(seconds=DEFAULT_SCAN_INTERVAL),
60  )
61 
62  await coordinator.async_config_entry_first_refresh()
63 
64  hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
65 
66  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
67 
68  return True
69 
70 
71 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
72  """Unload a config entry."""
73  if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
74  hass.data[DOMAIN].pop(entry.entry_id)
75 
76  return unload_ok
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:27
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:71