Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Landis+Gyr Heat Meter integration."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 import logging
7 from typing import Any
8 
9 import serial
10 from serial.tools import list_ports
11 import ultraheat_api
12 import voluptuous as vol
13 
14 from homeassistant.components import usb
15 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
16 from homeassistant.const import CONF_DEVICE
17 from homeassistant.core import HomeAssistant
18 from homeassistant.exceptions import HomeAssistantError
19 
20 from .const import DOMAIN, ULTRAHEAT_TIMEOUT
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 CONF_MANUAL_PATH = "Enter Manually"
25 
26 STEP_USER_DATA_SCHEMA = vol.Schema(
27  {
28  vol.Required(CONF_DEVICE): str,
29  }
30 )
31 
32 
33 class LandisgyrConfigFlow(ConfigFlow, domain=DOMAIN):
34  """Handle a config flow for Ultraheat Heat Meter."""
35 
36  VERSION = 2
37 
38  async def async_step_user(
39  self, user_input: dict[str, Any] | None = None
40  ) -> ConfigFlowResult:
41  """Step when setting up serial configuration."""
42  errors = {}
43 
44  if user_input is not None:
45  if user_input[CONF_DEVICE] == CONF_MANUAL_PATH:
46  return await self.async_step_setup_serial_manual_pathasync_step_setup_serial_manual_path()
47 
48  dev_path = await self.hass.async_add_executor_job(
49  usb.get_serial_by_id, user_input[CONF_DEVICE]
50  )
51  _LOGGER.debug("Using this path : %s", dev_path)
52 
53  try:
54  return await self.validate_and_create_entryvalidate_and_create_entry(dev_path)
55  except CannotConnect:
56  errors["base"] = "cannot_connect"
57 
58  ports = await get_usb_ports(self.hass)
59  ports[CONF_MANUAL_PATH] = CONF_MANUAL_PATH
60 
61  schema = vol.Schema({vol.Required(CONF_DEVICE): vol.In(ports)})
62  return self.async_show_formasync_show_formasync_show_form(step_id="user", data_schema=schema, errors=errors)
63 
65  self, user_input: dict[str, Any] | None = None
66  ) -> ConfigFlowResult:
67  """Set path manually."""
68  errors = {}
69 
70  if user_input is not None:
71  dev_path = user_input[CONF_DEVICE]
72  try:
73  return await self.validate_and_create_entryvalidate_and_create_entry(dev_path)
74  except CannotConnect:
75  errors["base"] = "cannot_connect"
76 
77  schema = vol.Schema({vol.Required(CONF_DEVICE): str})
78  return self.async_show_formasync_show_formasync_show_form(
79  step_id="setup_serial_manual_path",
80  data_schema=schema,
81  errors=errors,
82  )
83 
84  async def validate_and_create_entry(self, dev_path):
85  """Try to connect to the device path and return an entry."""
86  model, device_number = await self.validate_ultraheatvalidate_ultraheat(dev_path)
87 
88  _LOGGER.debug("Got model %s and device_number %s", model, device_number)
89  await self.async_set_unique_idasync_set_unique_id(f"{device_number}")
90  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
91  data = {
92  CONF_DEVICE: dev_path,
93  "model": model,
94  "device_number": device_number,
95  }
96  return self.async_create_entryasync_create_entryasync_create_entry(
97  title=model,
98  data=data,
99  )
100 
101  async def validate_ultraheat(self, port: str) -> tuple[str, str]:
102  """Validate the user input allows us to connect."""
103 
104  reader = ultraheat_api.UltraheatReader(port)
105  heat_meter = ultraheat_api.HeatMeterService(reader)
106  try:
107  async with asyncio.timeout(ULTRAHEAT_TIMEOUT):
108  # validate and retrieve the model and device number for a unique id
109  data = await self.hass.async_add_executor_job(heat_meter.read)
110 
111  except (TimeoutError, serial.SerialException) as err:
112  _LOGGER.warning("Failed read data from: %s. %s", port, err)
113  raise CannotConnect(f"Error communicating with device: {err}") from err
114 
115  _LOGGER.debug("Successfully connected to %s. Got data: %s", port, data)
116  return data.model, data.device_number
117 
118 
119 async def get_usb_ports(hass: HomeAssistant) -> dict[str, str]:
120  """Return a dict of USB ports and their friendly names."""
121  ports = await hass.async_add_executor_job(list_ports.comports)
122  port_descriptions = {}
123  for port in ports:
124  # this prevents an issue with usb_device_from_port
125  # not working for ports without vid on RPi
126  if port.vid:
127  usb_device = usb.usb_device_from_port(port)
128  dev_path = usb.get_serial_by_id(usb_device.device)
129  human_name = usb.human_readable_device_name(
130  dev_path,
131  usb_device.serial_number,
132  usb_device.manufacturer,
133  usb_device.description,
134  usb_device.vid,
135  usb_device.pid,
136  )
137  port_descriptions[dev_path] = human_name
138 
139  return port_descriptions
140 
141 
143  """Error to indicate we cannot connect."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:40
ConfigFlowResult async_step_setup_serial_manual_path(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:66
None _abort_if_unique_id_configured(self, dict[str, Any]|None updates=None, bool reload_on_update=True, *str error="already_configured")
ConfigEntry|None async_set_unique_id(self, str|None unique_id=None, *bool raise_on_progress=True)
ConfigFlowResult async_create_entry(self, *str title, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None, Mapping[str, Any]|None options=None)
ConfigFlowResult async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_create_entry(self, *str|None title=None, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None)
dict[str, str] get_usb_ports(HomeAssistant hass)
Definition: config_flow.py:119