Skip to content
This repository has been archived by the owner on Jul 1, 2023. It is now read-only.

Commit

Permalink
Migrate to aiohttp, fix update_interval (#23)
Browse files Browse the repository at this point in the history
* Migrate aiohttp, fix update_interval

* Request data refresh after service calls
  • Loading branch information
bjw-s authored Oct 20, 2020
1 parent 0c3a1c0 commit 7ce1537
Show file tree
Hide file tree
Showing 10 changed files with 151 additions and 125 deletions.
51 changes: 18 additions & 33 deletions custom_components/fullykiosk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,62 +3,47 @@
import logging
import voluptuous as vol

from datetime import timedelta

from fullykiosk import FullyKiosk

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PASSWORD
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import DOMAIN, COORDINATOR, CONTROLLER
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.typing import HomeAssistantType

_LOGGER = logging.getLogger(__name__)
from .const import DOMAIN
from .coordinator import FullyKioskDataUpdateCoordinator

CONFIG_SCHEMA = vol.Schema({DOMAIN: vol.Schema({})}, extra=vol.ALLOW_EXTRA)

# TODO List the platforms that you want to support.
# For your initial PR, limit it to 1 platform.
PLATFORMS = ["binary_sensor", "light", "media_player", "sensor", "switch"]


async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Fully Kiosk Browser component."""
return True
_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up Fully Kiosk Browser from a config entry."""
async def async_setup(hass: HomeAssistantType, config: dict):
"""Set up the Fully Kiosk Browser component."""

hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = {}
return True

config = entry.data
fully = FullyKiosk(config[CONF_HOST], config[CONF_PORT], config[CONF_PASSWORD])

async def async_update_data():
"""Fetch data from REST API."""
data = await hass.async_add_executor_job(fully.getDeviceInfo)
return data
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
"""Set up Fully Kiosk Browser from a config entry."""

coordinator = DataUpdateCoordinator(
entry_data = entry.data
coordinator = FullyKioskDataUpdateCoordinator(
hass,
_LOGGER,
name="deviceInfo",
update_method=async_update_data,
update_interval=timedelta(seconds=30),
async_get_clientsession(hass),
entry_data[CONF_HOST],
entry_data[CONF_PORT],
entry_data[CONF_PASSWORD],
)

await coordinator.async_refresh()

if not coordinator.last_update_success:
raise ConfigEntryNotReady

hass.data[DOMAIN][entry.entry_id][COORDINATOR] = coordinator
hass.data[DOMAIN][entry.entry_id][CONTROLLER] = fully
hass.data[DOMAIN][entry.entry_id] = coordinator

for component in PLATFORMS:
hass.async_create_task(
Expand All @@ -68,7 +53,7 @@ async def async_update_data():
return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry):
"""Unload a config entry."""
unload_ok = all(
await asyncio.gather(
Expand Down
10 changes: 6 additions & 4 deletions custom_components/fullykiosk/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
import logging

from homeassistant.components.binary_sensor import BinarySensorEntity, DEVICE_CLASS_PLUG
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import DOMAIN, COORDINATOR
from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

Expand All @@ -16,7 +17,7 @@

async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Fully Kiosk Browser sensor."""
coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR]
coordinator = hass.data[DOMAIN][config_entry.entry_id]

sensors = []

Expand All @@ -26,7 +27,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
async_add_entities(sensors, False)


class FullyBinarySensor(BinarySensorEntity):
class FullyBinarySensor(CoordinatorEntity, BinarySensorEntity):
"""Representation of a Fully Kiosk Browser binary sensor."""

def __init__(self, coordinator, sensor):
Expand All @@ -41,7 +42,8 @@ def name(self):

@property
def is_on(self):
return self.coordinator.data[self._sensor]
if self.coordinator.data:
return self.coordinator.data[self._sensor]

@property
def device_class(self):
Expand Down
6 changes: 4 additions & 2 deletions custom_components/fullykiosk/const.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
"""Constants for the Fully Kiosk Browser integration."""
from datetime import timedelta

DOMAIN = "fullykiosk"
COORDINATOR = "coordinator"
CONTROLLER = "controller"

ATTR_APPLICATION = "application"
ATTR_CONFIG_TYPE = "config_type"
Expand All @@ -16,7 +15,10 @@
SERVICE_LOAD_START_URL = "load_start_url"
SERVICE_LOAD_URL = "load_url"
SERVICE_PLAY_AUDIO = "play_audio"
SERVICE_REBOOT_DEVICE = "reboot_device"
SERVICE_RESTART_APP = "restart"
SERVICE_SET_CONFIG = "set_config"
SERVICE_START_APPLICATION = "start_application"
SERVICE_TO_FOREGROUND = "to_foreground"

UPDATE_INTERVAL = 30
38 changes: 38 additions & 0 deletions custom_components/fullykiosk/coordinator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""Provides the The Fully Kiosk Browser DataUpdateCoordinator."""
from datetime import timedelta
import logging

from aiohttp import ClientSession
from aiohttp.client_exceptions import ClientConnectorError
from async_timeout import timeout
from fullykiosk import FullyKiosk
from fullykiosk.exceptions import FullyKioskError

from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import UPDATE_INTERVAL

_LOGGER = logging.getLogger(__name__)


class FullyKioskDataUpdateCoordinator(DataUpdateCoordinator):
"""Define an object to hold Fully Kiosk Browser data."""

def __init__(
self, hass: HomeAssistantType, session: ClientSession, host, port, password
):
"""Initialize."""
self.fully = FullyKiosk(session, host, port, password)

super().__init__(
hass, _LOGGER, name=f"{host} deviceInfo", update_interval=timedelta(seconds=UPDATE_INTERVAL)
)

async def _async_update_data(self):
"""Update data via library."""
try:
with timeout(10):
return await self.fully.getDeviceInfo()
except (FullyKioskError, ClientConnectorError) as error:
raise UpdateFailed(error) from error
29 changes: 13 additions & 16 deletions custom_components/fullykiosk/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,25 @@
LightEntity,
SUPPORT_BRIGHTNESS,
)
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import DOMAIN, COORDINATOR, CONTROLLER
from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Fully Kiosk Browser light."""
coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR]
controller = hass.data[DOMAIN][config_entry.entry_id][CONTROLLER]
coordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities([FullyLight(coordinator)], False)

async_add_entities([FullyLight(coordinator, controller)], False)


class FullyLight(LightEntity):
class FullyLight(CoordinatorEntity, LightEntity):
"""Representation of a Fully Kiosk Browser light."""

def __init__(self, coordinator, controller):
def __init__(self, coordinator):
self._name = f"{coordinator.data['deviceName']} Screen"
self.coordinator = coordinator
self.controller = controller
self._unique_id = f"{coordinator.data['deviceID']}-screen"

@property
Expand All @@ -35,9 +33,10 @@ def name(self):

@property
def is_on(self):
if self.coordinator.data["appVersionCode"] < 784:
return self.coordinator.data["isScreenOn"]
return self.coordinator.data["screenOn"]
if self.coordinator.data:
if self.coordinator.data["appVersionCode"] < 784:
return self.coordinator.data["isScreenOn"]
return self.coordinator.data["screenOn"]

@property
def brightness(self):
Expand All @@ -62,19 +61,17 @@ def unique_id(self):
return self._unique_id

async def async_turn_on(self, **kwargs):
await self.hass.async_add_executor_job(self.controller.screenOn)
await self.coordinator.fully.screenOn()
brightness = kwargs.get(ATTR_BRIGHTNESS)
if brightness is None:
await self.coordinator.async_refresh()
return
if brightness != self.coordinator.data["screenBrightness"]:
await self.hass.async_add_executor_job(
self.controller.setScreenBrightness, brightness
)
await self.coordinator.fully.setScreenBrightness(brightness)
await self.coordinator.async_refresh()

async def async_turn_off(self, **kwargs):
await self.hass.async_add_executor_job(self.controller.screenOff)
await self.coordinator.fully.screenOff()
await self.coordinator.async_refresh()

async def async_added_to_hass(self):
Expand Down
2 changes: 1 addition & 1 deletion custom_components/fullykiosk/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/fullykiosk",
"requirements": [
"python-fullykiosk==0.0.6"
"python-fullykiosk==0.0.8"
],
"ssdp": [],
"zeroconf": [],
Expand Down
Loading

0 comments on commit 7ce1537

Please sign in to comment.