Skip to content

Commit

Permalink
Improve config flow behavior for wrong i2c address
Browse files Browse the repository at this point in the history
  • Loading branch information
jpcornil-git committed Jul 14, 2024
1 parent 889617c commit b89d7dd
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
8 changes: 8 additions & 0 deletions custom_components/mcp23017/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,14 @@ async def async_get_or_create(hass, config_entry, entity):
return component


def i2c_device_exist(address):
try:
smbus2.SMBus(DEFAULT_I2C_BUS).read_byte(address)
except (FileNotFoundError, OSError) as error:
return False
return True


class MCP23017(threading.Thread):
"""MCP23017 device driver."""

Expand Down
12 changes: 8 additions & 4 deletions custom_components/mcp23017/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from homeassistant import config_entries
from homeassistant.core import callback

from . import i2c_device_exist
from .const import (
CONF_FLOW_PIN_NAME,
CONF_FLOW_PIN_NUMBER,
Expand Down Expand Up @@ -79,10 +80,13 @@ async def async_step_user(self, user_input=None):
user_input[CONF_FLOW_PIN_NUMBER],
)

return self.async_create_entry(
title=self._title(user_input),
data=user_input,
)
if i2c_device_exist(user_input[CONF_I2C_ADDRESS]):
return self.async_create_entry(
title=self._title(user_input),
data=user_input,
)
else:
return self.async_abort(reason="Invalid I2C address")

return self.async_show_form(
step_id="user",
Expand Down

0 comments on commit b89d7dd

Please sign in to comment.