Home Assistant Unofficial Reference 2024.12.1
api.py
Go to the documentation of this file.
1 """API for Smappee bound to Home Assistant OAuth."""
2 
3 from asyncio import run_coroutine_threadsafe
4 
5 from pysmappee import api
6 
7 from homeassistant import config_entries, core
8 from homeassistant.const import CONF_PLATFORM
9 from homeassistant.helpers import config_entry_oauth2_flow
10 
11 from .const import DOMAIN
12 
13 
14 class ConfigEntrySmappeeApi(api.SmappeeApi):
15  """Provide Smappee authentication tied to an OAuth2 based config entry."""
16 
17  def __init__(
18  self,
19  hass: core.HomeAssistant,
20  config_entry: config_entries.ConfigEntry,
21  implementation: config_entry_oauth2_flow.AbstractOAuth2Implementation,
22  ) -> None:
23  """Initialize Smappee Auth."""
24  self.hasshass = hass
25  self.config_entryconfig_entry = config_entry
26  self.sessionsession = config_entry_oauth2_flow.OAuth2Session(
27  hass, config_entry, implementation
28  )
29 
30  platform_to_farm = {
31  "PRODUCTION": 1,
32  "ACCEPTANCE": 2,
33  "DEVELOPMENT": 3,
34  }
35  super().__init__(
36  None,
37  None,
38  token=self.sessionsession.token,
39  farm=platform_to_farm[hass.data[DOMAIN][CONF_PLATFORM]],
40  )
41 
42  def refresh_tokens(self) -> dict:
43  """Refresh and return new Smappee tokens using Home Assistant OAuth2 session."""
44  run_coroutine_threadsafe(
45  self.sessionsession.async_ensure_token_valid(), self.hasshass.loop
46  ).result()
47 
48  return self.sessionsession.token
None __init__(self, core.HomeAssistant hass, config_entries.ConfigEntry config_entry, config_entry_oauth2_flow.AbstractOAuth2Implementation implementation)
Definition: api.py:22