From b4cb7a76cf34028f4e766ff50b1c6ee39b8ca62f Mon Sep 17 00:00:00 2001 From: Jonh Sady Date: Mon, 17 Feb 2025 18:44:16 -0300 Subject: [PATCH] adjustments --- homeassistant/components/redgtech/__init__.py | 55 ++++++------ .../components/redgtech/config_flow.py | 39 ++++----- .../components/redgtech/manifest.json | 2 +- .../components/redgtech/services.yaml | 12 --- homeassistant/components/redgtech/switch.py | 84 ++++++++++++++----- requirements_all.txt | 2 +- 6 files changed, 102 insertions(+), 92 deletions(-) diff --git a/homeassistant/components/redgtech/__init__.py b/homeassistant/components/redgtech/__init__.py index 701a7b98b5d..74a24c80baa 100644 --- a/homeassistant/components/redgtech/__init__.py +++ b/homeassistant/components/redgtech/__init__.py @@ -2,9 +2,7 @@ import logging from homeassistant.core import HomeAssistant from homeassistant.config_entries import ConfigEntry from homeassistant.const import Platform -from .const import DOMAIN, API_URL -from homeassistant.helpers.aiohttp_client import async_get_clientsession -import aiohttp +from .const import DOMAIN from redgtech_api import RedgtechAPI _LOGGER = logging.getLogger(__name__) @@ -14,8 +12,8 @@ PLATFORMS: list[Platform] = [Platform.SWITCH] async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Redgtech from a config entry.""" _LOGGER.debug("Setting up Redgtech entry: %s", entry.entry_id) - hass.data.setdefault(DOMAIN, {}) - hass.data[DOMAIN][entry.entry_id] = { + + entry.runtime_data = { "config": entry.data, "entities": [] } @@ -25,45 +23,40 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: _LOGGER.error("No access token found in config entry") return False - session = async_get_clientsession(hass) + api = RedgtechAPI(access_token) try: - async with session.get(f'{API_URL}/home_assistant?access_token={access_token}', timeout=10) as response: - response.raise_for_status() - data = await response.json() - _LOGGER.debug("Received data from API: %s", data) + data = await api.get_data() + _LOGGER.debug("Received data from API: %s", data) - entities = [] - for item in data.get("boards", []): - entity_id = item.get('endpointId', '') - entity_name = item.get("name", f"Entity {entity_id}") - entity_value = item.get("value", False) - entity_state = "on" if entity_value else "off" - _LOGGER.debug("Processing entity: id=%s, name=%s, value=%s, state=%s", entity_id, entity_name, entity_value, entity_state) + entities = [] + for item in data.get("boards", []): + entity_id = item.get('endpointId', '') + entity_name = item.get("name", f"Entity {entity_id}") + entity_value = item.get("value", False) + entity_state = "on" if entity_value else "off" + _LOGGER.debug("Processing entity: id=%s, name=%s, value=%s, state=%s", entity_id, entity_name, entity_value, entity_state) - entities.append({ - "id": entity_id, - "name": entity_name, - "state": entity_state, - "type": 'switch' - }) + entities.append({ + "id": entity_id, + "name": entity_name, + "state": entity_state, + "type": 'switch' + }) - hass.data[DOMAIN][entry.entry_id]["entities"] = entities + entry.runtime_data["entities"] = entities await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) _LOGGER.debug("Successfully set up Redgtech entry: %s", entry.entry_id) return True - except aiohttp.ClientResponseError as e: - _LOGGER.error("HTTP error while setting up Redgtech entry: %s - Status: %s", e.message, e.status) - return False - except aiohttp.ClientError as e: - _LOGGER.error("Client error while setting up Redgtech entry: %s", e) - return False except Exception as e: - _LOGGER.exception("Unexpected error setting up Redgtech entry: %s", entry.entry_id) + _LOGGER.error("Error setting up Redgtech entry: %s", e) return False async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" _LOGGER.debug("Unloading Redgtech entry: %s", entry.entry_id) + # Fechar a sessão HTTP + api = RedgtechAPI(entry.data.get("access_token")) + await api.close() return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) \ No newline at end of file diff --git a/homeassistant/components/redgtech/config_flow.py b/homeassistant/components/redgtech/config_flow.py index 7807a2ab9c8..7913fca4772 100644 --- a/homeassistant/components/redgtech/config_flow.py +++ b/homeassistant/components/redgtech/config_flow.py @@ -1,8 +1,8 @@ from homeassistant import config_entries import voluptuous as vol -import aiohttp import logging -from .const import DOMAIN, API_URL +from .const import DOMAIN +from redgtech_api import RedgtechAPI _LOGGER = logging.getLogger(__name__) @@ -19,30 +19,21 @@ class RedgtechConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): email = user_input.get("email") password = user_input.get("password") + api = RedgtechAPI() try: - async with aiohttp.ClientSession() as session: - async with session.post( - f'{API_URL}/home_assistant/login', - json={'email': email, 'password': password} - ) as response: - if response.status == 200: - data = await response.json() - access_token = data.get("data", {}).get("access_token") - if access_token: - _LOGGER.info("Login successful") + access_token = await api.login(email, password) + if access_token: + _LOGGER.info("Login successful") - return self.async_create_entry( - title="Redgtech", - data={"access_token": access_token} - ) - else: - _LOGGER.error("Login failed: No access token received") - errors["base"] = "invalid_auth" - else: - _LOGGER.error("Login failed: Invalid credentials") - errors["base"] = "invalid_auth" - except aiohttp.ClientError as e: - _LOGGER.error("Login failed: Cannot connect to server: %s", e) + return self.async_create_entry( + title="Redgtech", + data={"access_token": access_token} + ) + else: + _LOGGER.error("Login failed: No access token received") + errors["base"] = "invalid_auth" + except Exception as e: + _LOGGER.error("Login failed: %s", e) errors["base"] = "cannot_connect" return self.async_show_form( diff --git a/homeassistant/components/redgtech/manifest.json b/homeassistant/components/redgtech/manifest.json index 124a4ca5156..6afebc8e5d1 100644 --- a/homeassistant/components/redgtech/manifest.json +++ b/homeassistant/components/redgtech/manifest.json @@ -8,5 +8,5 @@ "integration_type": "service", "config_flow": true, "quality_scale": "silver", - "requirements": ["redgtech-api==0.1.9"] + "requirements": ["redgtech-api==0.1.14"] } \ No newline at end of file diff --git a/homeassistant/components/redgtech/services.yaml b/homeassistant/components/redgtech/services.yaml index 0aa6f3494bc..e69de29bb2d 100644 --- a/homeassistant/components/redgtech/services.yaml +++ b/homeassistant/components/redgtech/services.yaml @@ -1,12 +0,0 @@ -login: - description: "Log in to the Redgtech service" - fields: - email: - description: "The email address for the Redgtech account" - example: "user@example.com" - password: - description: "The password for the Redgtech account" - example: "your_password" - -logout: - description: "Log out from the Redgtech service" \ No newline at end of file diff --git a/homeassistant/components/redgtech/switch.py b/homeassistant/components/redgtech/switch.py index 59abd471908..68b316767d9 100644 --- a/homeassistant/components/redgtech/switch.py +++ b/homeassistant/components/redgtech/switch.py @@ -1,38 +1,63 @@ import logging +from datetime import timedelta from homeassistant.components.switch import SwitchEntity +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from redgtech_api import RedgtechAPI -from .const import DOMAIN, API_URL +from .const import DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the switch platform.""" access_token = config_entry.data.get("access_token") - if access_token: - api = RedgtechAPI(access_token) - try: - data = await api.get_data() - entities = [] - for item in data.get("boards", []): - categories = item.get("displayCategories", "") - if "SWITCH" in categories: - entities.append(RedgtechSwitch(item, api)) - async_add_entities(entities) - except Exception as e: - _LOGGER.error("Error fetching data from API: %s", e) - else: + if not access_token: _LOGGER.error("No access token available") + return + + api = RedgtechAPI(access_token) + coordinator = RedgtechDataUpdateCoordinator(hass, api) + await coordinator.async_config_entry_first_refresh() + + entities = [] + if coordinator.data: + for item in coordinator.data.get("boards", []): + categories = item.get("displayCategories", "") + if "SWITCH" in categories: + entities.append(RedgtechSwitch(coordinator, item, api)) + + async_add_entities(entities) + +class RedgtechDataUpdateCoordinator(DataUpdateCoordinator): + """Class to manage fetching data from the API.""" + + def __init__(self, hass, api): + """Initialize.""" + self.api = api + super().__init__( + hass, + _LOGGER, + name=DOMAIN, + update_interval=timedelta(seconds=1), + ) + + async def _async_update_data(self): + """Fetch data from API.""" + try: + _LOGGER.debug("Fetching data from Redgtech API") + return await self.api.get_data() + except Exception as e: + raise UpdateFailed(f"Error fetching data: {e}") class RedgtechSwitch(SwitchEntity): """Representation of a Redgtech switch.""" - def __init__(self, data, api): + def __init__(self, coordinator, data, api): + """Initialize the switch.""" + self.coordinator = coordinator + self.api = api self._state = data.get("value", False) self._name = data.get("friendlyName") self._endpoint_id = data.get("endpointId") - self._description = data.get("description") - self._manufacturer = data.get("manufacturerName") - self._api = api @property def name(self): @@ -53,19 +78,32 @@ class RedgtechSwitch(SwitchEntity): await self._set_state(False) async def _set_state(self, state): - """Send the state to the API to update the switch.""" - success = await self._api.set_switch_state(self._endpoint_id, state) + """Send the state to the API and update immediately.""" + _LOGGER.debug("Setting state of %s to %s", self._name, state) + + success = await self.api.set_switch_state(self._endpoint_id, state) if success: self._state = state self.async_write_ha_state() + _LOGGER.debug("State of %s set to %s", self._name, state) + await self.coordinator.async_request_refresh() else: _LOGGER.error("Failed to set state for %s", self._name) + async def async_update(self): + """Fetch new state data for the switch.""" + _LOGGER.debug("Updating switch state: %s", self._name) + await self.coordinator.async_request_refresh() + data = self.coordinator.data + if data: + for item in data.get("boards", []): + if item.get("endpointId") == self._endpoint_id: + self._state = item.get("value", False) + self.async_write_ha_state() + @property def extra_state_attributes(self): """Return the state attributes.""" return { "endpoint_id": self._endpoint_id, - "description": self._description, - "manufacturer": self._manufacturer, - } \ No newline at end of file + } diff --git a/requirements_all.txt b/requirements_all.txt index 5ebf43c5081..bb6d5219b94 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2600,7 +2600,7 @@ rapt-ble==0.1.2 raspyrfm-client==1.2.8 # homeassistant.components.redgtech -redgtech-api==0.1.2 +redgtech-api==0.1.14 # homeassistant.components.refoss refoss-ha==1.2.5