mirror of
https://github.com/home-assistant/core.git
synced 2025-07-20 03:37:07 +00:00
adjustments
This commit is contained in:
parent
d3615af43c
commit
b4cb7a76cf
@ -2,9 +2,7 @@ import logging
|
|||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
from homeassistant.const import Platform
|
from homeassistant.const import Platform
|
||||||
from .const import DOMAIN, API_URL
|
from .const import DOMAIN
|
||||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
|
||||||
import aiohttp
|
|
||||||
from redgtech_api import RedgtechAPI
|
from redgtech_api import RedgtechAPI
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
@ -14,8 +12,8 @@ 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."""
|
||||||
_LOGGER.debug("Setting up Redgtech entry: %s", entry.entry_id)
|
_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,
|
"config": entry.data,
|
||||||
"entities": []
|
"entities": []
|
||||||
}
|
}
|
||||||
@ -25,11 +23,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
_LOGGER.error("No access token found in config entry")
|
_LOGGER.error("No access token found in config entry")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
session = async_get_clientsession(hass)
|
api = RedgtechAPI(access_token)
|
||||||
try:
|
try:
|
||||||
async with session.get(f'{API_URL}/home_assistant?access_token={access_token}', timeout=10) as response:
|
data = await api.get_data()
|
||||||
response.raise_for_status()
|
|
||||||
data = await response.json()
|
|
||||||
_LOGGER.debug("Received data from API: %s", data)
|
_LOGGER.debug("Received data from API: %s", data)
|
||||||
|
|
||||||
entities = []
|
entities = []
|
||||||
@ -47,23 +43,20 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
"type": 'switch'
|
"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)
|
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||||
_LOGGER.debug("Successfully set up Redgtech entry: %s", entry.entry_id)
|
_LOGGER.debug("Successfully set up Redgtech entry: %s", entry.entry_id)
|
||||||
return True
|
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:
|
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
|
return False
|
||||||
|
|
||||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||||
"""Unload a config entry."""
|
"""Unload a config entry."""
|
||||||
_LOGGER.debug("Unloading Redgtech entry: %s", entry.entry_id)
|
_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)
|
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
@ -1,8 +1,8 @@
|
|||||||
from homeassistant import config_entries
|
from homeassistant import config_entries
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
import aiohttp
|
|
||||||
import logging
|
import logging
|
||||||
from .const import DOMAIN, API_URL
|
from .const import DOMAIN
|
||||||
|
from redgtech_api import RedgtechAPI
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
@ -19,15 +19,9 @@ class RedgtechConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
email = user_input.get("email")
|
email = user_input.get("email")
|
||||||
password = user_input.get("password")
|
password = user_input.get("password")
|
||||||
|
|
||||||
|
api = RedgtechAPI()
|
||||||
try:
|
try:
|
||||||
async with aiohttp.ClientSession() as session:
|
access_token = await api.login(email, password)
|
||||||
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:
|
if access_token:
|
||||||
_LOGGER.info("Login successful")
|
_LOGGER.info("Login successful")
|
||||||
|
|
||||||
@ -38,11 +32,8 @@ class RedgtechConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
else:
|
else:
|
||||||
_LOGGER.error("Login failed: No access token received")
|
_LOGGER.error("Login failed: No access token received")
|
||||||
errors["base"] = "invalid_auth"
|
errors["base"] = "invalid_auth"
|
||||||
else:
|
except Exception as e:
|
||||||
_LOGGER.error("Login failed: Invalid credentials")
|
_LOGGER.error("Login failed: %s", e)
|
||||||
errors["base"] = "invalid_auth"
|
|
||||||
except aiohttp.ClientError as e:
|
|
||||||
_LOGGER.error("Login failed: Cannot connect to server: %s", e)
|
|
||||||
errors["base"] = "cannot_connect"
|
errors["base"] = "cannot_connect"
|
||||||
|
|
||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
|
@ -8,5 +8,5 @@
|
|||||||
"integration_type": "service",
|
"integration_type": "service",
|
||||||
"config_flow": true,
|
"config_flow": true,
|
||||||
"quality_scale": "silver",
|
"quality_scale": "silver",
|
||||||
"requirements": ["redgtech-api==0.1.9"]
|
"requirements": ["redgtech-api==0.1.14"]
|
||||||
}
|
}
|
@ -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"
|
|
@ -1,38 +1,63 @@
|
|||||||
import logging
|
import logging
|
||||||
|
from datetime import timedelta
|
||||||
from homeassistant.components.switch import SwitchEntity
|
from homeassistant.components.switch import SwitchEntity
|
||||||
|
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||||
from redgtech_api import RedgtechAPI
|
from redgtech_api import RedgtechAPI
|
||||||
from .const import DOMAIN, API_URL
|
from .const import DOMAIN
|
||||||
|
|
||||||
_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 switch 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 not access_token:
|
||||||
|
_LOGGER.error("No access token available")
|
||||||
|
return
|
||||||
|
|
||||||
api = RedgtechAPI(access_token)
|
api = RedgtechAPI(access_token)
|
||||||
try:
|
coordinator = RedgtechDataUpdateCoordinator(hass, api)
|
||||||
data = await api.get_data()
|
await coordinator.async_config_entry_first_refresh()
|
||||||
|
|
||||||
entities = []
|
entities = []
|
||||||
for item in data.get("boards", []):
|
if coordinator.data:
|
||||||
|
for item in coordinator.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(coordinator, item, api))
|
||||||
|
|
||||||
async_add_entities(entities)
|
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:
|
except Exception as e:
|
||||||
_LOGGER.error("Error fetching data from API: %s", e)
|
raise UpdateFailed(f"Error fetching data: {e}")
|
||||||
else:
|
|
||||||
_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, api):
|
def __init__(self, coordinator, data, api):
|
||||||
|
"""Initialize the switch."""
|
||||||
|
self.coordinator = coordinator
|
||||||
|
self.api = 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._manufacturer = data.get("manufacturerName")
|
|
||||||
self._api = api
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
@ -53,19 +78,32 @@ class RedgtechSwitch(SwitchEntity):
|
|||||||
await self._set_state(False)
|
await self._set_state(False)
|
||||||
|
|
||||||
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 and update immediately."""
|
||||||
success = await self._api.set_switch_state(self._endpoint_id, state)
|
_LOGGER.debug("Setting state of %s to %s", self._name, state)
|
||||||
|
|
||||||
|
success = await self.api.set_switch_state(self._endpoint_id, state)
|
||||||
if success:
|
if success:
|
||||||
self._state = state
|
self._state = state
|
||||||
self.async_write_ha_state()
|
self.async_write_ha_state()
|
||||||
|
_LOGGER.debug("State of %s set to %s", self._name, state)
|
||||||
|
await self.coordinator.async_request_refresh()
|
||||||
else:
|
else:
|
||||||
_LOGGER.error("Failed to set state for %s", self._name)
|
_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
|
@property
|
||||||
def extra_state_attributes(self):
|
def extra_state_attributes(self):
|
||||||
"""Return the state attributes."""
|
"""Return the state attributes."""
|
||||||
return {
|
return {
|
||||||
"endpoint_id": self._endpoint_id,
|
"endpoint_id": self._endpoint_id,
|
||||||
"description": self._description,
|
|
||||||
"manufacturer": self._manufacturer,
|
|
||||||
}
|
}
|
2
requirements_all.txt
generated
2
requirements_all.txt
generated
@ -2600,7 +2600,7 @@ rapt-ble==0.1.2
|
|||||||
raspyrfm-client==1.2.8
|
raspyrfm-client==1.2.8
|
||||||
|
|
||||||
# homeassistant.components.redgtech
|
# homeassistant.components.redgtech
|
||||||
redgtech-api==0.1.2
|
redgtech-api==0.1.14
|
||||||
|
|
||||||
# homeassistant.components.refoss
|
# homeassistant.components.refoss
|
||||||
refoss-ha==1.2.5
|
refoss-ha==1.2.5
|
||||||
|
Loading…
x
Reference in New Issue
Block a user