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

Commit 7ce1537

Browse files
authored
Migrate to aiohttp, fix update_interval (#23)
* Migrate aiohttp, fix update_interval * Request data refresh after service calls
1 parent 0c3a1c0 commit 7ce1537

File tree

10 files changed

+151
-125
lines changed

10 files changed

+151
-125
lines changed

custom_components/fullykiosk/__init__.py

Lines changed: 18 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,62 +3,47 @@
33
import logging
44
import voluptuous as vol
55

6-
from datetime import timedelta
7-
8-
from fullykiosk import FullyKiosk
9-
106
from homeassistant.config_entries import ConfigEntry
11-
from homeassistant.core import HomeAssistant
127
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PASSWORD
138
from homeassistant.exceptions import ConfigEntryNotReady
14-
from homeassistant.helpers.dispatcher import async_dispatcher_send
15-
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
16-
17-
from .const import DOMAIN, COORDINATOR, CONTROLLER
9+
from homeassistant.helpers.aiohttp_client import async_get_clientsession
10+
from homeassistant.helpers.typing import HomeAssistantType
1811

19-
_LOGGER = logging.getLogger(__name__)
12+
from .const import DOMAIN
13+
from .coordinator import FullyKioskDataUpdateCoordinator
2014

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

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

27-
28-
async def async_setup(hass: HomeAssistant, config: dict):
29-
"""Set up the Fully Kiosk Browser component."""
30-
return True
19+
_LOGGER = logging.getLogger(__name__)
3120

3221

33-
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
34-
"""Set up Fully Kiosk Browser from a config entry."""
22+
async def async_setup(hass: HomeAssistantType, config: dict):
23+
"""Set up the Fully Kiosk Browser component."""
3524

3625
hass.data.setdefault(DOMAIN, {})
37-
hass.data[DOMAIN][entry.entry_id] = {}
26+
return True
3827

39-
config = entry.data
40-
fully = FullyKiosk(config[CONF_HOST], config[CONF_PORT], config[CONF_PASSWORD])
4128

42-
async def async_update_data():
43-
"""Fetch data from REST API."""
44-
data = await hass.async_add_executor_job(fully.getDeviceInfo)
45-
return data
29+
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
30+
"""Set up Fully Kiosk Browser from a config entry."""
4631

47-
coordinator = DataUpdateCoordinator(
32+
entry_data = entry.data
33+
coordinator = FullyKioskDataUpdateCoordinator(
4834
hass,
49-
_LOGGER,
50-
name="deviceInfo",
51-
update_method=async_update_data,
52-
update_interval=timedelta(seconds=30),
35+
async_get_clientsession(hass),
36+
entry_data[CONF_HOST],
37+
entry_data[CONF_PORT],
38+
entry_data[CONF_PASSWORD],
5339
)
5440

5541
await coordinator.async_refresh()
5642

5743
if not coordinator.last_update_success:
5844
raise ConfigEntryNotReady
5945

60-
hass.data[DOMAIN][entry.entry_id][COORDINATOR] = coordinator
61-
hass.data[DOMAIN][entry.entry_id][CONTROLLER] = fully
46+
hass.data[DOMAIN][entry.entry_id] = coordinator
6247

6348
for component in PLATFORMS:
6449
hass.async_create_task(
@@ -68,7 +53,7 @@ async def async_update_data():
6853
return True
6954

7055

71-
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
56+
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry):
7257
"""Unload a config entry."""
7358
unload_ok = all(
7459
await asyncio.gather(

custom_components/fullykiosk/binary_sensor.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
import logging
33

44
from homeassistant.components.binary_sensor import BinarySensorEntity, DEVICE_CLASS_PLUG
5+
from homeassistant.helpers.update_coordinator import CoordinatorEntity
56

6-
from .const import DOMAIN, COORDINATOR
7+
from .const import DOMAIN
78

89
_LOGGER = logging.getLogger(__name__)
910

@@ -16,7 +17,7 @@
1617

1718
async def async_setup_entry(hass, config_entry, async_add_entities):
1819
"""Set up the Fully Kiosk Browser sensor."""
19-
coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR]
20+
coordinator = hass.data[DOMAIN][config_entry.entry_id]
2021

2122
sensors = []
2223

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

2829

29-
class FullyBinarySensor(BinarySensorEntity):
30+
class FullyBinarySensor(CoordinatorEntity, BinarySensorEntity):
3031
"""Representation of a Fully Kiosk Browser binary sensor."""
3132

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

4243
@property
4344
def is_on(self):
44-
return self.coordinator.data[self._sensor]
45+
if self.coordinator.data:
46+
return self.coordinator.data[self._sensor]
4547

4648
@property
4749
def device_class(self):

custom_components/fullykiosk/const.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
"""Constants for the Fully Kiosk Browser integration."""
2+
from datetime import timedelta
23

34
DOMAIN = "fullykiosk"
4-
COORDINATOR = "coordinator"
5-
CONTROLLER = "controller"
65

76
ATTR_APPLICATION = "application"
87
ATTR_CONFIG_TYPE = "config_type"
@@ -16,7 +15,10 @@
1615
SERVICE_LOAD_START_URL = "load_start_url"
1716
SERVICE_LOAD_URL = "load_url"
1817
SERVICE_PLAY_AUDIO = "play_audio"
18+
SERVICE_REBOOT_DEVICE = "reboot_device"
1919
SERVICE_RESTART_APP = "restart"
2020
SERVICE_SET_CONFIG = "set_config"
2121
SERVICE_START_APPLICATION = "start_application"
2222
SERVICE_TO_FOREGROUND = "to_foreground"
23+
24+
UPDATE_INTERVAL = 30
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""Provides the The Fully Kiosk Browser DataUpdateCoordinator."""
2+
from datetime import timedelta
3+
import logging
4+
5+
from aiohttp import ClientSession
6+
from aiohttp.client_exceptions import ClientConnectorError
7+
from async_timeout import timeout
8+
from fullykiosk import FullyKiosk
9+
from fullykiosk.exceptions import FullyKioskError
10+
11+
from homeassistant.helpers.typing import HomeAssistantType
12+
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
13+
14+
from .const import UPDATE_INTERVAL
15+
16+
_LOGGER = logging.getLogger(__name__)
17+
18+
19+
class FullyKioskDataUpdateCoordinator(DataUpdateCoordinator):
20+
"""Define an object to hold Fully Kiosk Browser data."""
21+
22+
def __init__(
23+
self, hass: HomeAssistantType, session: ClientSession, host, port, password
24+
):
25+
"""Initialize."""
26+
self.fully = FullyKiosk(session, host, port, password)
27+
28+
super().__init__(
29+
hass, _LOGGER, name=f"{host} deviceInfo", update_interval=timedelta(seconds=UPDATE_INTERVAL)
30+
)
31+
32+
async def _async_update_data(self):
33+
"""Update data via library."""
34+
try:
35+
with timeout(10):
36+
return await self.fully.getDeviceInfo()
37+
except (FullyKioskError, ClientConnectorError) as error:
38+
raise UpdateFailed(error) from error

custom_components/fullykiosk/light.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,25 @@
66
LightEntity,
77
SUPPORT_BRIGHTNESS,
88
)
9+
from homeassistant.helpers.update_coordinator import CoordinatorEntity
910

10-
from .const import DOMAIN, COORDINATOR, CONTROLLER
11+
from .const import DOMAIN
1112

1213
_LOGGER = logging.getLogger(__name__)
1314

1415

1516
async def async_setup_entry(hass, config_entry, async_add_entities):
1617
"""Set up the Fully Kiosk Browser light."""
17-
coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR]
18-
controller = hass.data[DOMAIN][config_entry.entry_id][CONTROLLER]
18+
coordinator = hass.data[DOMAIN][config_entry.entry_id]
19+
async_add_entities([FullyLight(coordinator)], False)
1920

20-
async_add_entities([FullyLight(coordinator, controller)], False)
2121

22-
23-
class FullyLight(LightEntity):
22+
class FullyLight(CoordinatorEntity, LightEntity):
2423
"""Representation of a Fully Kiosk Browser light."""
2524

26-
def __init__(self, coordinator, controller):
25+
def __init__(self, coordinator):
2726
self._name = f"{coordinator.data['deviceName']} Screen"
2827
self.coordinator = coordinator
29-
self.controller = controller
3028
self._unique_id = f"{coordinator.data['deviceID']}-screen"
3129

3230
@property
@@ -35,9 +33,10 @@ def name(self):
3533

3634
@property
3735
def is_on(self):
38-
if self.coordinator.data["appVersionCode"] < 784:
39-
return self.coordinator.data["isScreenOn"]
40-
return self.coordinator.data["screenOn"]
36+
if self.coordinator.data:
37+
if self.coordinator.data["appVersionCode"] < 784:
38+
return self.coordinator.data["isScreenOn"]
39+
return self.coordinator.data["screenOn"]
4140

4241
@property
4342
def brightness(self):
@@ -62,19 +61,17 @@ def unique_id(self):
6261
return self._unique_id
6362

6463
async def async_turn_on(self, **kwargs):
65-
await self.hass.async_add_executor_job(self.controller.screenOn)
64+
await self.coordinator.fully.screenOn()
6665
brightness = kwargs.get(ATTR_BRIGHTNESS)
6766
if brightness is None:
6867
await self.coordinator.async_refresh()
6968
return
7069
if brightness != self.coordinator.data["screenBrightness"]:
71-
await self.hass.async_add_executor_job(
72-
self.controller.setScreenBrightness, brightness
73-
)
70+
await self.coordinator.fully.setScreenBrightness(brightness)
7471
await self.coordinator.async_refresh()
7572

7673
async def async_turn_off(self, **kwargs):
77-
await self.hass.async_add_executor_job(self.controller.screenOff)
74+
await self.coordinator.fully.screenOff()
7875
await self.coordinator.async_refresh()
7976

8077
async def async_added_to_hass(self):

custom_components/fullykiosk/manifest.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"config_flow": true,
55
"documentation": "https://www.home-assistant.io/integrations/fullykiosk",
66
"requirements": [
7-
"python-fullykiosk==0.0.6"
7+
"python-fullykiosk==0.0.8"
88
],
99
"ssdp": [],
1010
"zeroconf": [],

0 commit comments

Comments
 (0)