adjustments

This commit is contained in:
Jonh Sady 2025-02-02 18:03:21 -03:00
parent 8fdd8c0103
commit d820be91d0
4 changed files with 39 additions and 66 deletions

View File

@ -5,10 +5,11 @@ from homeassistant.const import Platform
from .const import DOMAIN, API_URL from .const import DOMAIN, API_URL
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
import aiohttp import aiohttp
from redgtech_api import RedgtechAPI
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
PLATFORMS: list[Platform] = [Platform.SWITCH, Platform.LIGHT] PLATFORMS: list[Platform] = [Platform.SWITCH]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Redgtech from a config entry.""" """Set up Redgtech from a config entry."""
@ -36,8 +37,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"id": item.get('endpointId', ''), "id": item.get('endpointId', ''),
"name": item.get("name", f"Entity {item.get('endpointId', '')}"), "name": item.get("name", f"Entity {item.get('endpointId', '')}"),
"state": "on" if item.get("value", False) else "off", "state": "on" if item.get("value", False) else "off",
"brightness": item.get("bright", 0), "type": 'switch'
"type": 'light' if 'dim' in item.get('endpointId', '').lower() else 'switch'
} }
for item in data.get("boards", []) for item in data.get("boards", [])
] ]

View File

@ -1,7 +1,6 @@
{ {
"domain": "redgtech", "domain": "redgtech",
"name": "Redgtech", "name": "Redgtech",
"version": "1.0.0",
"codeowners": [], "codeowners": [],
"documentation": "https://www.home-assistant.io/integrations/redgtech", "documentation": "https://www.home-assistant.io/integrations/redgtech",
"iot_class": "cloud_polling", "iot_class": "cloud_polling",
@ -9,5 +8,5 @@
"integration_type": "service", "integration_type": "service",
"config_flow": true, "config_flow": true,
"quality_scale": "bronze", "quality_scale": "bronze",
"requirements": [] "requirements": ["redgtech-api==0.1.0"]
} }

View File

@ -1,43 +1,38 @@
import logging import logging
import aiohttp
from homeassistant.components.switch import SwitchEntity from homeassistant.components.switch import SwitchEntity
from redgtech_api import RedgtechAPI
from .const import DOMAIN, API_URL from .const import DOMAIN, API_URL
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, config_entry, async_add_entities): async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the light platform.""" """Set up the switch platform."""
access_token = config_entry.data.get("access_token") access_token = config_entry.data.get("access_token")
if access_token: if access_token:
api = RedgtechAPI(access_token)
try: try:
async with aiohttp.ClientSession() as session: data = await api.get_data()
async with session.get(f'{API_URL}/home_assistant?access_token={access_token}') as response:
if response.status == 200:
data = await response.json()
entities = [] entities = []
for item in data.get("boards", []): for item in data.get("boards", []):
categories = item.get("displayCategories", "") categories = item.get("displayCategories", "")
if "SWITCH" in categories: if "SWITCH" in categories:
entities.append(RedgtechSwitch(item, api))
entities.append(RedgtechSwitch(item, access_token))
async_add_entities(entities) async_add_entities(entities)
else: except Exception as e:
_LOGGER.error("Error fetching data from API: %s", response.status) _LOGGER.error("Error fetching data from API: %s", e)
except aiohttp.ClientError as e:
_LOGGER.error("Error connecting to API: %s", e)
else: else:
_LOGGER.error("No access token available") _LOGGER.error("No access token available")
class RedgtechSwitch(SwitchEntity): class RedgtechSwitch(SwitchEntity):
"""Representation of a Redgtech switch.""" """Representation of a Redgtech switch."""
def __init__(self, data, token): def __init__(self, data, api):
self._state = data.get("value", False) self._state = data.get("value", False)
self._name = data.get("friendlyName") self._name = data.get("friendlyName")
self._endpoint_id = data.get("endpointId") self._endpoint_id = data.get("endpointId")
self._description = data.get("description") self._description = data.get("description")
self._manufacturer = data.get("manufacturerName") self._manufacturer = data.get("manufacturerName")
self._token = token self._api = api
@property @property
def name(self): def name(self):
@ -59,45 +54,18 @@ class RedgtechSwitch(SwitchEntity):
async def _set_state(self, state): async def _set_state(self, state):
"""Send the state to the API to update the switch.""" """Send the state to the API to update the switch."""
id_part, after_id = self._endpoint_id.split("-", 1) success = await self._api.set_switch_state(self._endpoint_id, state)
value = ''.join(filter(str.isdigit, after_id)) if success:
state_char = 'l' if state else 'd'
url = f"{API_URL}/home_assistant/execute/{id_part}?cod=?{value}{state_char}"
headers = {"Authorization": f"{self._token}"}
payload = {"state": state}
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, json=payload) as response:
if response.status == 200:
self._state = state self._state = state
self.async_write_ha_state() self.async_write_ha_state()
else: else:
_LOGGER.error("Failed to set state for %s, status code: %s", self._name, response.status) _LOGGER.error("Failed to set state for %s", self._name)
async def async_update(self): @property
"""Get the latest state of the switch.""" def extra_state_attributes(self):
id_part, after_id = self._endpoint_id.split("-", 1) """Return the state attributes."""
value = after_id return {
url = f"{API_URL}/home_assistant?access_token={self._token}" "endpoint_id": self._endpoint_id,
headers = {"Authorization": f"{self._token}"} "description": self._description,
"manufacturer": self._manufacturer,
try: }
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as response:
if response.status == 200:
data = await response.json()
for board in data.get("boards", []):
if board.get("endpointId") == self._endpoint_id:
value = board.get("value", False)
self._state = bool(value)
self.async_write_ha_state()
break
else:
_LOGGER.error(
"Failed to update state for %s, status code: %s",
self._name,
response.status,
)
except Exception as e:
_LOGGER.error("Error updating state for %s: %s", self._name, str(e))

6
requirements_all.txt generated
View File

@ -266,6 +266,9 @@ aiohasupervisor==0.2.2b5
# homeassistant.components.homekit_controller # homeassistant.components.homekit_controller
aiohomekit==3.2.7 aiohomekit==3.2.7
# homeassistant.components.redgtech
aiohttp==3.8.1
# homeassistant.components.mcp_server # homeassistant.components.mcp_server
aiohttp_sse==2.2.0 aiohttp_sse==2.2.0
@ -2584,6 +2587,9 @@ rapt-ble==0.1.2
# homeassistant.components.raspyrfm # homeassistant.components.raspyrfm
raspyrfm-client==1.2.8 raspyrfm-client==1.2.8
# homeassistant.components.redgtech
redgtech-api==0.1.0
# homeassistant.components.refoss # homeassistant.components.refoss
refoss-ha==1.2.5 refoss-ha==1.2.5