button functionality added for fluss device

This commit is contained in:
NjDaGreat
2024-06-28 13:40:34 +00:00
parent 52bc006a72
commit 196610fe33
13 changed files with 397 additions and 0 deletions
+1
View File
@@ -462,6 +462,7 @@ build.json @home-assistant/supervisor
/tests/components/flo/ @dmulcahey
/homeassistant/components/flume/ @ChrisMandich @bdraco @jeeftor
/tests/components/flume/ @ChrisMandich @bdraco @jeeftor
/homeassistant/components/fluss/ @fluss
/homeassistant/components/flux_led/ @icemanch
/tests/components/flux_led/ @icemanch
/homeassistant/components/forecast_solar/ @klaasnicolaas @frenck
@@ -0,0 +1,40 @@
"""The Fluss+ integration."""
from __future__ import annotations
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, Platform
from homeassistant.core import HomeAssistant
from .api import FlussApiClient
from .const import DOMAIN
LOGGER = logging.getLogger(__package__)
# For your initial PR, limit it to 1 platform.
# PLATFORMS: list[Platform] = [Platform.COVER]
PLATFORMS: list[Platform] = [Platform.BUTTON]
# type FlussConfigEntry = ConfigEntry[FlussData] # noqa: F821
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Fluss+ from a config entry."""
api = FlussApiClient(entry.data[CONF_API_KEY], hass)
response = await api.async_get_devices()
LOGGER.warning("D %s", response)
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = api
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
+112
View File
@@ -0,0 +1,112 @@
"""Fluss+ API Client."""
from __future__ import annotations
import asyncio
import datetime
import logging
import socket
import typing
import aiohttp
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
LOGGER = logging.getLogger(__package__)
class FlussApiClientError(Exception):
"""Exception to indicate a general API error."""
class FlussApiClientCommunicationError(FlussApiClientError):
"""Exception to indicate a communication error."""
class FlussApiClientAuthenticationError(FlussApiClientError):
"""Exception to indicate an authentication error."""
class FlussApiClient:
"""Sample API Client."""
def __init__(self, api_key: str, hass: HomeAssistant) -> None:
"""Sample API Client."""
self._api_key = api_key
self._session = aiohttp_client.async_get_clientsession(hass)
async def async_get_devices(self) -> typing.Any:
"""Get data from the API."""
return await self._api_wrapper(
method="get",
url="https://zgekzokxrl.execute-api.eu-west-1.amazonaws.com/v1/api/device/list",
headers={"Authorization": self._api_key},
)
# Cover functionality
# async def async_open_cover(self, deviceId: str) -> any:
# """Open the cover."""
# return await self._api_wrapper(
# method="post",
# url=f"https://zgekzokxrl.execute-api.eu-west-1.amazonaws.com/v1/api/device/{deviceId}/trigger",
# headers={"Authorization": self._api_key},
# )
# async def async_close_cover(self, deviceId: str) -> any:
# """Open the cover."""
# return await self._api_wrapper(
# method="post",
# url=f"https://zgekzokxrl.execute-api.eu-west-1.amazonaws.com/v1/api/device/{deviceId}/trigger",
# headers={"Authorization": self._api_key},
# data={
# "timeStamp": int(
# datetime.datetime.now().timestamp() * 1000
# ), # Convert to milliseconds
# "metaData": {},
# },
# )
async def async_trigger_device(self, deviceId: str) -> typing.Any:
"""Trigger the device."""
timestamp = int(datetime.datetime.now().timestamp() * 1000)
return await self._api_wrapper(
method="post",
url=f"https://zgekzokxrl.execute-api.eu-west-1.amazonaws.com/v1/api/device/{deviceId}/trigger",
headers={"Authorization": self._api_key},
data={"timeStamp": timestamp, "metaData": {}},
)
async def _api_wrapper(
self,
method: str,
url: str,
data: dict | None = None,
headers: dict | None = None,
) -> typing.Any:
"""Get information from the API."""
try:
async with asyncio.timeout(10):
response = await self._session.request(
method=method,
url=url,
headers=headers,
json=data,
)
if response.status in (401, 403):
raise FlussApiClientAuthenticationError(
"Invalid credentials",
)
response.raise_for_status()
return await response.json()
except TimeoutError as exception:
raise FlussApiClientCommunicationError(
"Timeout error fetching information",
) from exception
except (aiohttp.ClientError, socket.gaierror) as exception:
raise FlussApiClientCommunicationError(
"Error fetching information",
) from exception
except Exception as exception: # pylint: disable=broad-except
raise FlussApiClientError("Something really wrong happened!") from exception
+37
View File
@@ -0,0 +1,37 @@
"""Support for Fluss Devices."""
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .api import FlussApiClient
from .const import DOMAIN
from .device import FlussButton
LOGGER = logging.getLogger(__package__)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the Fluss Devices."""
api: FlussApiClient = hass.data[DOMAIN][entry.entry_id]
# for device in await api.async_get_devices():
# LOGGER.warning("INFO %s", device)
# # async_add_entities(FlussDevice() for device in )
devices = await api.async_get_devices()
LOGGER.warning("Devices %s", devices)
if isinstance(devices, dict) and "devices" in devices:
devices = devices["devices"]
if not isinstance(devices, list):
return
buttons = [
FlussButton(api, device) for device in devices if isinstance(device, dict)
]
async_add_entities(buttons, update_before_add=True)
@@ -0,0 +1,92 @@
"""Config flow for Fluss+ integration."""
from __future__ import annotations
import logging
from typing import Any
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_API_KEY
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema({vol.Required("apikey"): cv.string})
class PlaceholderHub:
"""Placeholder class to make tests pass.
TODO Remove this placeholder class and replace with things from your PyPI package.
"""
def __init__(self, apikey: str) -> None:
"""Initialize."""
self.apikey = apikey
async def authenticate(self) -> bool:
"""Test if we can authenticate with the host."""
# Actual authentication logic should be here.
return True
async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
"""Validate the user input allows us to connect.
Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
"""
hub = PlaceholderHub(data[CONF_API_KEY])
if not await hub.authenticate():
raise InvalidAuth
# If you cannot connect:
# throw CannotConnect
# If the authentication is wrong:
# InvalidAuth
# Return info that you want to store in the config entry.
return {"title": "Name of the device"}
class FlussConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Fluss+."""
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
if user_input is not None:
try:
info = await validate_input(self.hass, user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return self.async_create_entry(title=info["title"], data=user_input)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)
class CannotConnect(HomeAssistantError):
"""Error to indicate we cannot connect."""
class InvalidAuth(HomeAssistantError):
"""Error to indicate there is invalid auth."""
+3
View File
@@ -0,0 +1,3 @@
"""Constants for the Fluss+ integration."""
DOMAIN = "fluss"
+30
View File
@@ -0,0 +1,30 @@
"""Device for Fluss Device."""
import logging
from homeassistant.components.button import ButtonEntity
from .api import FlussApiClient
LOGGER = logging.getLogger(__package__)
DEFAULT_NAME = "Fluss +"
class FlussButton(ButtonEntity):
"""Representation of a Fluss cover device."""
def __init__(self, api: FlussApiClient, device: dict) -> None:
"""Initializr the cover."""
self.api = api
self.device = device
self._name = device["deviceName"]
self._attr_unique_id = f"fluss_{device['deviceId']}"
@property
def name(self) -> str:
"""Return name of the cover."""
return self._name
async def async_press(self) -> None:
"""Handle the button press."""
await self.api.async_trigger_device(self.device["deviceId"])
+42
View File
@@ -0,0 +1,42 @@
"""Base entities for the Motionblinds Bluetooth integration."""
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ADDRESS
from homeassistant.helpers.entity import Entity, EntityDescription
from .device import FlussButton
_LOGGER = logging.getLogger(__name__)
class FlussEntity(Entity):
"""Base class for Fluss entities."""
_attr_has_entity_name = True
_attr_should_poll = False
device: FlussButton
entry: ConfigEntry
def __init__(
self,
device: FlussButton,
entry: ConfigEntry,
entity_description: EntityDescription,
unique_id_suffix: str | None = None,
) -> None:
"""Initialize the entity."""
if unique_id_suffix is None:
self._attr_unique_id = entry.data[CONF_ADDRESS]
else:
self._attr_unique_id = f"{entry.data[CONF_ADDRESS]}_{unique_id_suffix}"
self.device = device
self.entry = entry
self.entity_description = entity_description
async def async_update(self) -> None:
"""Update state, called by HA if there is a poll interval and by the service homeassistant.update_entity."""
# _LOGGER.debug("(%s) Updating entity", self.entry.data[])
# await self.device.status_query()
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

@@ -0,0 +1,13 @@
{
"domain": "fluss",
"name": "Fluss +",
"codeowners": ["@fluss"],
"config_flow": true,
"dependencies": [],
"documentation": "https://www.home-assistant.io/integrations/fluss",
"homekit": {},
"iot_class": "cloud_polling",
"requirements": [],
"ssdp": [],
"zeroconf": []
}
@@ -0,0 +1,20 @@
{
"config": {
"step": {
"user": {
"description": "Your Fluss API key, available in the profile page of the Fluss+ app",
"data": {
"api_key": "[%key:common::config_flow::data::api_key%]"
}
}
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
"unknown": "[%key:common::config_flow::error::unknown%]"
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
}
}
}
+1
View File
@@ -178,6 +178,7 @@ FLOWS = {
"flipr",
"flo",
"flume",
"fluss",
"flux_led",
"folder_watcher",
"forecast_solar",
@@ -1953,6 +1953,12 @@
"config_flow": true,
"iot_class": "cloud_polling"
},
"fluss": {
"name": "Fluss +",
"integration_type": "hub",
"config_flow": true,
"iot_class": "cloud_polling"
},
"flux": {
"name": "Flux",
"integration_type": "hub",