Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for NuHeat thermostats."""
2 
3 from datetime import timedelta
4 from http import HTTPStatus
5 import logging
6 
7 import nuheat
8 import requests
9 
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
12 from homeassistant.core import HomeAssistant
13 from homeassistant.exceptions import ConfigEntryNotReady
14 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
15 
16 from .const import CONF_SERIAL_NUMBER, DOMAIN, PLATFORMS
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 
21 def _get_thermostat(api, serial_number):
22  """Authenticate and create the thermostat object."""
23  api.authenticate()
24  return api.get_thermostat(serial_number)
25 
26 
27 async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
28  """Set up NuHeat from a config entry."""
29 
30  conf = entry.data
31 
32  username = conf[CONF_USERNAME]
33  password = conf[CONF_PASSWORD]
34  serial_number = conf[CONF_SERIAL_NUMBER]
35 
36  api = nuheat.NuHeat(username, password)
37 
38  try:
39  thermostat = await hass.async_add_executor_job(
40  _get_thermostat, api, serial_number
41  )
42  except requests.exceptions.Timeout as ex:
43  raise ConfigEntryNotReady from ex
44  except requests.exceptions.HTTPError as ex:
45  if (
46  ex.response.status_code > HTTPStatus.BAD_REQUEST
47  and ex.response.status_code < HTTPStatus.INTERNAL_SERVER_ERROR
48  ):
49  _LOGGER.error("Failed to login to nuheat: %s", ex)
50  return False
51  raise ConfigEntryNotReady from ex
52  except Exception as ex: # noqa: BLE001
53  _LOGGER.error("Failed to login to nuheat: %s", ex)
54  return False
55 
56  async def _async_update_data():
57  """Fetch data from API endpoint."""
58  await hass.async_add_executor_job(thermostat.get_data)
59 
60  coordinator = DataUpdateCoordinator(
61  hass,
62  _LOGGER,
63  config_entry=entry,
64  name=f"nuheat {serial_number}",
65  update_method=_async_update_data,
66  update_interval=timedelta(minutes=5),
67  )
68 
69  hass.data.setdefault(DOMAIN, {})
70  hass.data[DOMAIN][entry.entry_id] = (thermostat, coordinator)
71 
72  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
73 
74  return True
75 
76 
77 async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
78  """Unload a config entry."""
79  unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
80  if unload_ok:
81  hass.data[DOMAIN].pop(entry.entry_id)
82 
83  return unload_ok
def _get_thermostat(api, serial_number)
Definition: __init__.py:21
bool async_setup_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:27
bool async_unload_entry(HomeAssistant hass, ConfigEntry entry)
Definition: __init__.py:77