|
| 1 | +"""Config and options flow for the DTSU666 Modbus TCP integration.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +import voluptuous as vol |
| 8 | + |
| 9 | +from homeassistant.config_entries import ( |
| 10 | + ConfigEntry, |
| 11 | + ConfigFlow, |
| 12 | + ConfigFlowResult, |
| 13 | + OptionsFlow, |
| 14 | +) |
| 15 | +from homeassistant.const import CONF_HOST, CONF_PORT, CONF_SCAN_INTERVAL |
| 16 | +from homeassistant.core import callback |
| 17 | +from homeassistant.exceptions import HomeAssistantError |
| 18 | + |
| 19 | +from pymodbus.client import AsyncModbusTcpClient |
| 20 | + |
| 21 | +from .const import ( |
| 22 | + CONF_SLAVE_ID, |
| 23 | + DEFAULT_PORT, |
| 24 | + DEFAULT_SCAN_INTERVAL, |
| 25 | + DEFAULT_SLAVE_ID, |
| 26 | + DOMAIN, |
| 27 | + MAX_SCAN_INTERVAL, |
| 28 | + MIN_SCAN_INTERVAL, |
| 29 | +) |
| 30 | + |
| 31 | + |
| 32 | +class CannotConnect(HomeAssistantError): |
| 33 | + """Raised when the meter cannot be reached.""" |
| 34 | + |
| 35 | + |
| 36 | +async def _validate(host: str, port: int, slave_id: int) -> None: |
| 37 | + """Open a Modbus TCP session and read one register to prove it works.""" |
| 38 | + client = AsyncModbusTcpClient(host, port=port, timeout=5) |
| 39 | + try: |
| 40 | + await client.connect() |
| 41 | + if not client.connected: |
| 42 | + raise CannotConnect |
| 43 | + try: |
| 44 | + rr = await client.read_holding_registers( |
| 45 | + 0x2000, count=2, device_id=slave_id |
| 46 | + ) |
| 47 | + except TypeError: |
| 48 | + rr = await client.read_holding_registers( |
| 49 | + 0x2000, count=2, slave=slave_id |
| 50 | + ) |
| 51 | + if rr.isError(): |
| 52 | + raise CannotConnect |
| 53 | + except (ConnectionError, OSError) as err: |
| 54 | + raise CannotConnect from err |
| 55 | + finally: |
| 56 | + client.close() |
| 57 | + |
| 58 | + |
| 59 | +def _user_schema() -> vol.Schema: |
| 60 | + return vol.Schema( |
| 61 | + { |
| 62 | + vol.Required(CONF_HOST): str, |
| 63 | + vol.Required(CONF_PORT, default=DEFAULT_PORT): int, |
| 64 | + vol.Required(CONF_SLAVE_ID, default=DEFAULT_SLAVE_ID): int, |
| 65 | + vol.Required( |
| 66 | + CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL |
| 67 | + ): vol.All(int, vol.Range(min=MIN_SCAN_INTERVAL, max=MAX_SCAN_INTERVAL)), |
| 68 | + } |
| 69 | + ) |
| 70 | + |
| 71 | + |
| 72 | +class Dtsu666ConfigFlow(ConfigFlow, domain=DOMAIN): |
| 73 | + """Handle the initial UI configuration.""" |
| 74 | + |
| 75 | + VERSION = 1 |
| 76 | + |
| 77 | + async def async_step_user( |
| 78 | + self, user_input: dict[str, Any] | None = None |
| 79 | + ) -> ConfigFlowResult: |
| 80 | + errors: dict[str, str] = {} |
| 81 | + if user_input is not None: |
| 82 | + await self.async_set_unique_id( |
| 83 | + f"{user_input[CONF_HOST]}:{user_input[CONF_PORT]}:" |
| 84 | + f"{user_input[CONF_SLAVE_ID]}" |
| 85 | + ) |
| 86 | + self._abort_if_unique_id_configured() |
| 87 | + try: |
| 88 | + await _validate( |
| 89 | + user_input[CONF_HOST], |
| 90 | + user_input[CONF_PORT], |
| 91 | + user_input[CONF_SLAVE_ID], |
| 92 | + ) |
| 93 | + except CannotConnect: |
| 94 | + errors["base"] = "cannot_connect" |
| 95 | + except Exception: # noqa: BLE001 |
| 96 | + errors["base"] = "unknown" |
| 97 | + else: |
| 98 | + return self.async_create_entry( |
| 99 | + title=f"DTSU666 ({user_input[CONF_HOST]})", |
| 100 | + data=user_input, |
| 101 | + ) |
| 102 | + |
| 103 | + return self.async_show_form( |
| 104 | + step_id="user", data_schema=_user_schema(), errors=errors |
| 105 | + ) |
| 106 | + |
| 107 | + @staticmethod |
| 108 | + @callback |
| 109 | + def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlow: |
| 110 | + return Dtsu666OptionsFlow() |
| 111 | + |
| 112 | + |
| 113 | +class Dtsu666OptionsFlow(OptionsFlow): |
| 114 | + """Allow changing the scan interval after setup.""" |
| 115 | + |
| 116 | + async def async_step_init( |
| 117 | + self, user_input: dict[str, Any] | None = None |
| 118 | + ) -> ConfigFlowResult: |
| 119 | + if user_input is not None: |
| 120 | + return self.async_create_entry(title="", data=user_input) |
| 121 | + |
| 122 | + current = self.config_entry.options.get( |
| 123 | + CONF_SCAN_INTERVAL, |
| 124 | + self.config_entry.data.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL), |
| 125 | + ) |
| 126 | + return self.async_show_form( |
| 127 | + step_id="init", |
| 128 | + data_schema=vol.Schema( |
| 129 | + { |
| 130 | + vol.Required( |
| 131 | + CONF_SCAN_INTERVAL, default=current |
| 132 | + ): vol.All( |
| 133 | + int, vol.Range(min=MIN_SCAN_INTERVAL, max=MAX_SCAN_INTERVAL) |
| 134 | + ) |
| 135 | + } |
| 136 | + ), |
| 137 | + ) |
0 commit comments