Update requirement version and add switcher_kis services (#23477)

* Update aioswitcher requirement to 2019.4.26.

* Removed unnecessary legacy function call.

* Fixed log message capital first letter.

* Replaced None argument with empty dict.

* Replaced guard.

* Added ServiceCallType.

* Added set_auto_off and update_device_name services to the component.

* Added test cases for service calls.

* Conditioned the component services registry with the platform discovery.

* Update homeassistant/components/switcher_kis/__init__.py

Co-Authored-By: TomerFi <tomer.figenblat@gmail.com>

* Update homeassistant/components/switcher_kis/__init__.py

Co-Authored-By: TomerFi <tomer.figenblat@gmail.com>

* Resolved change requests.

* Added ContextType.

* Addes permission verification for service calls.

* Added test cases for permision verification and more.

* Replaced POLICY_CONTROL with the more suited POLICY_EDIT.

* More appropriate function name.

* Added domain and entity_id validation for calling services.

* Removed service for setting the vendor's device name.
This commit is contained in:
Tomer Figenblat authored and Paulus Schoutsen committed 2019-06-14 15:48:21 -07:00
1 parent f9b3ba2887
commit fe8a330a45
10 files changed
+202 -16

No files matched your search

@@ -7,19 +7,25 @@ from typing import Dict, Optional
import voluptuous as vol
from homeassistant.auth.permissions.const import POLICY_EDIT
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import callback
from homeassistant.const import CONF_ENTITY_ID, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import callback, split_entity_id
from homeassistant.exceptions import Unauthorized, UnknownUser
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.discovery import async_load_platform
from homeassistant.helpers.discovery import (async_listen_platform,
async_load_platform)
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.typing import EventType, HomeAssistantType
from homeassistant.helpers.typing import (ContextType, EventType,
HomeAssistantType, ServiceCallType)
from homeassistant.loader import bind_hass
_LOGGER = getLogger(__name__)
DOMAIN = 'switcher_kis'
CONF_AUTO_OFF = 'auto_off'
CONF_DEVICE_ID = 'device_id'
CONF_DEVICE_PASSWORD = 'device_password'
CONF_PHONE_ID = 'phone_id'
@@ -40,6 +46,32 @@ CONFIG_SCHEMA = vol.Schema({
})
}, extra=vol.ALLOW_EXTRA)
SERVICE_SET_AUTO_OFF_NAME = 'set_auto_off'
SERVICE_SET_AUTO_OFF_SCHEMA = vol.Schema({
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Required(CONF_AUTO_OFF): cv.time_period_str
})
@bind_hass
async def _validate_edit_permission(
hass: HomeAssistantType, context: ContextType,
entity_id: str) -> None:
"""Use for validating user control permissions."""
splited = split_entity_id(entity_id)
if splited[0] != SWITCH_DOMAIN or not splited[1].startswith(DOMAIN):
raise Unauthorized(
context=context, entity_id=entity_id, permission=(POLICY_EDIT, ))
user = await hass.auth.async_get_user(context.user_id)
if user is None:
raise UnknownUser(
context=context, entity_id=entity_id, permission=(POLICY_EDIT, ))
if not user.permissions.check_entity(entity_id, POLICY_EDIT):
raise Unauthorized(
context=context, entity_id=entity_id, permission=(POLICY_EDIT, ))
async def async_setup(hass: HomeAssistantType, config: Dict) -> bool:
"""Set up the switcher component."""
@@ -58,13 +90,12 @@ async def async_setup(hass: HomeAssistantType, config: Dict) -> bool:
"""On homeassistant stop, gracefully stop the bridge if running."""
await v2bridge.stop()
hass.async_add_job(hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, async_stop_bridge))
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_stop_bridge)
try:
device_data = await wait_for(v2bridge.queue.get(), timeout=10.0)
except (Asyncio_TimeoutError, RuntimeError):
_LOGGER.exception("failed to get response from device")
_LOGGER.exception("Failed to get response from device")
await v2bridge.stop()
return False
@@ -72,8 +103,33 @@ async def async_setup(hass: HomeAssistantType, config: Dict) -> bool:
DATA_DEVICE: device_data
}
async def async_switch_platform_discovered(
platform: str, discovery_info: Optional[Dict]) -> None:
"""Use for registering services after switch platform is discoverd."""
if platform != DOMAIN:
return
async def async_set_auto_off_service(service: ServiceCallType) -> None:
"""Use for handling setting device auto-off service calls."""
from aioswitcher.api import SwitcherV2Api
await _validate_edit_permission(
hass, service.context, service.data[CONF_ENTITY_ID])
async with SwitcherV2Api(hass.loop, device_data.ip_addr, phone_id,
device_id, device_password) as swapi:
await swapi.set_auto_shutdown(service.data[CONF_AUTO_OFF])
hass.services.async_register(
DOMAIN, SERVICE_SET_AUTO_OFF_NAME,
async_set_auto_off_service,
schema=SERVICE_SET_AUTO_OFF_SCHEMA)
async_listen_platform(
hass, SWITCH_DOMAIN, async_switch_platform_discovered)
hass.async_create_task(async_load_platform(
hass, SWITCH_DOMAIN, DOMAIN, None, config))
hass, SWITCH_DOMAIN, DOMAIN, {}, config))
@callback
def device_updates(timestamp: Optional[datetime]) -> None:
@@ -6,7 +6,7 @@
"@tomerfi"
],
"requirements": [
"aioswitcher==2019.3.21"
"aioswitcher==2019.4.26"
],
"dependencies": []
}
@@ -0,0 +1,9 @@
set_auto_off:
description: 'Update Switcher device auto off setting.'
fields:
entity_id:
description: "Name of the entity id associated with the integration, used for permission validation."
example: "switch.switcher_kis_boiler"
auto_off:
description: 'Time period string containing hours and minutes.'
example: '"02:30"'
@@ -30,7 +30,8 @@ async def async_setup_platform(hass: HomeAssistantType, config: Dict,
async_add_entities: Callable,
discovery_info: Dict) -> None:
"""Set up the switcher platform for the switch component."""
assert DOMAIN in hass.data
if discovery_info is None:
return
async_add_entities([SwitcherControl(hass.data[DOMAIN][DATA_DEVICE])])