init home-assistant
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
"""The TRIGGERcmd component."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from triggercmd import client, ha
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
|
||||
from .const import CONF_TOKEN
|
||||
|
||||
PLATFORMS = [
|
||||
Platform.SWITCH,
|
||||
]
|
||||
|
||||
type TriggercmdConfigEntry = ConfigEntry[ha.Hub]
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: TriggercmdConfigEntry) -> bool:
|
||||
"""Set up TRIGGERcmd from a config entry."""
|
||||
hub = ha.Hub(entry.data[CONF_TOKEN])
|
||||
|
||||
status_code = await client.async_connection_test(entry.data[CONF_TOKEN])
|
||||
if status_code != 200:
|
||||
raise ConfigEntryNotReady
|
||||
|
||||
entry.runtime_data = hub
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
return True
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: TriggercmdConfigEntry) -> bool:
|
||||
"""Unload a config entry."""
|
||||
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Config flow for TRIGGERcmd integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import jwt
|
||||
from triggercmd import TRIGGERcmdConnectionError, client
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
|
||||
from .const import CONF_TOKEN, DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DATA_SCHEMA = vol.Schema({(CONF_TOKEN): str})
|
||||
|
||||
|
||||
async def validate_input(hass: HomeAssistant, data: dict) -> str:
|
||||
"""Validate the user input allows us to connect.
|
||||
|
||||
Data has the keys from DATA_SCHEMA with values provided by the user.
|
||||
"""
|
||||
if len(data[CONF_TOKEN]) < 100:
|
||||
raise InvalidToken
|
||||
|
||||
token_data = jwt.decode(data[CONF_TOKEN], options={"verify_signature": False})
|
||||
if not token_data["id"]:
|
||||
raise InvalidToken
|
||||
|
||||
try:
|
||||
await client.async_connection_test(data[CONF_TOKEN])
|
||||
except Exception as e:
|
||||
raise TRIGGERcmdConnectionError from e
|
||||
else:
|
||||
return token_data["id"]
|
||||
|
||||
|
||||
class TriggerCMDConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow."""
|
||||
|
||||
VERSION = 1
|
||||
|
||||
async def async_step_user(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle the initial step."""
|
||||
errors = {}
|
||||
if user_input is not None:
|
||||
try:
|
||||
identifier = await validate_input(self.hass, user_input)
|
||||
except InvalidToken:
|
||||
errors[CONF_TOKEN] = "invalid_token"
|
||||
except TRIGGERcmdConnectionError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception: # pylint: disable=broad-except
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
errors["base"] = "unknown"
|
||||
else:
|
||||
await self.async_set_unique_id(identifier)
|
||||
self._abort_if_unique_id_configured()
|
||||
|
||||
return self.async_create_entry(title="TRIGGERcmd Hub", data=user_input)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="user", data_schema=DATA_SCHEMA, errors=errors
|
||||
)
|
||||
|
||||
|
||||
class InvalidToken(HomeAssistantError):
|
||||
"""Invalid token."""
|
||||
@@ -0,0 +1,4 @@
|
||||
"""Constants for the TRIGGERcmd integration."""
|
||||
|
||||
DOMAIN = "triggercmd"
|
||||
CONF_TOKEN = "token"
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"domain": "triggercmd",
|
||||
"name": "TRIGGERcmd",
|
||||
"codeowners": ["@rvmey"],
|
||||
"config_flow": true,
|
||||
"documentation": "https://www.home-assistant.io/integrations/triggercmd",
|
||||
"integration_type": "hub",
|
||||
"iot_class": "cloud_polling",
|
||||
"requirements": ["triggercmd==0.0.27"]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"user": {
|
||||
"data": {
|
||||
"token": "[%key:common::config_flow::data::access_token%]"
|
||||
},
|
||||
"data_description": {
|
||||
"token": "The token from the TRIGGERcmd instructions page"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
|
||||
"invalid_token": "Invalid token",
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
|
||||
}
|
||||
}
|
||||
}
|
||||
85
home-assistant/homeassistant/components/triggercmd/switch.py
Normal file
85
home-assistant/homeassistant/components/triggercmd/switch.py
Normal file
@@ -0,0 +1,85 @@
|
||||
"""Platform for switch integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from triggercmd import client, ha
|
||||
|
||||
from homeassistant.components.switch import SwitchEntity
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
|
||||
from . import TriggercmdConfigEntry
|
||||
from .const import DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
config_entry: TriggercmdConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Add switch for passed config_entry in HA."""
|
||||
hub = config_entry.runtime_data
|
||||
async_add_entities(TRIGGERcmdSwitch(trigger) for trigger in hub.triggers)
|
||||
|
||||
|
||||
class TRIGGERcmdSwitch(SwitchEntity):
|
||||
"""Representation of a Switch."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
_attr_assumed_state = True
|
||||
_attr_should_poll = False
|
||||
|
||||
computer_id: str
|
||||
trigger_id: str
|
||||
firmware_version: str
|
||||
model: str
|
||||
hub: ha.Hub
|
||||
|
||||
def __init__(self, trigger: TRIGGERcmdSwitch) -> None:
|
||||
"""Initialize the switch."""
|
||||
self._switch = trigger
|
||||
self._attr_is_on = False
|
||||
self._attr_unique_id = f"{trigger.computer_id}.{trigger.trigger_id}"
|
||||
self._attr_name = trigger.trigger_id
|
||||
self._attr_device_info = DeviceInfo(
|
||||
identifiers={(DOMAIN, trigger.computer_id)},
|
||||
name=trigger.computer_id.capitalize(),
|
||||
sw_version=trigger.firmware_version,
|
||||
model=trigger.model,
|
||||
manufacturer=trigger.hub.manufacturer,
|
||||
)
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
"""Return True if hub is available."""
|
||||
return self._switch.hub.online
|
||||
|
||||
async def async_turn_on(self, **kwargs):
|
||||
"""Turn the switch on."""
|
||||
await self.trigger("on")
|
||||
self._attr_is_on = True
|
||||
self.async_write_ha_state()
|
||||
|
||||
async def async_turn_off(self, **kwargs):
|
||||
"""Turn the switch off."""
|
||||
await self.trigger("off")
|
||||
self._attr_is_on = False
|
||||
self.async_write_ha_state()
|
||||
|
||||
async def trigger(self, params: str):
|
||||
"""Trigger the command."""
|
||||
r = await client.async_trigger(
|
||||
self._switch.hub.token,
|
||||
{
|
||||
"computer": self._switch.computer_id,
|
||||
"trigger": self._switch.trigger_id,
|
||||
"params": params,
|
||||
"sender": "Home Assistant",
|
||||
},
|
||||
)
|
||||
_LOGGER.debug("TRIGGERcmd trigger response: %s", r.json())
|
||||
Reference in New Issue
Block a user