Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
albaintor committed Jul 17, 2024
1 parent fa315ab commit 6e7fec4
Show file tree
Hide file tree
Showing 5 changed files with 149 additions and 75 deletions.
26 changes: 12 additions & 14 deletions intg-zidoo/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,7 @@ class DeviceInstance:
address: str
net_mac_address: str
wifi_mac_address: str

def __init__(self, id, name, address, net_mac_address=None, wifi_mac_address=None):
"""Initialize device instance config."""
self.id = id
self.name = name
self.address = address
if net_mac_address:
self.net_mac_address = net_mac_address
if wifi_mac_address:
self.wifi_mac_address = wifi_mac_address
always_on: bool


class _EnhancedJSONEncoder(json.JSONEncoder):
Expand Down Expand Up @@ -123,6 +114,7 @@ def update(self, device_instance: DeviceInstance) -> bool:
item.name = device_instance.name
item.net_mac_address = device_instance.net_mac_address
item.wifi_mac_address = device_instance.wifi_mac_address
item.always_on = device_instance.always_on
return self.store()
return False

Expand Down Expand Up @@ -175,10 +167,16 @@ def load(self) -> bool:
with open(self._cfg_file_path, "r", encoding="utf-8") as f:
data = json.load(f)
for item in data:
try:
self._config.append(DeviceInstance(**item))
except TypeError as ex:
_LOG.warning("Invalid configuration entry will be ignored: %s", ex)
# not using AtvDevice(**item) to be able to migrate old configuration files with missing attributes
device_instance = DeviceInstance(
item.get("id"),
item.get("name"),
item.get("address"),
item.get("net_mac_address", ""),
item.get("wifi_mac_address", ""),
item.get("always_on", False),
)
self._config.append(device_instance)
return True
except OSError:
_LOG.error("Cannot open the config file")
Expand Down
25 changes: 4 additions & 21 deletions intg-zidoo/driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,22 +35,6 @@
_R2_IN_STANDBY = False


async def device_status_poller(interval: float = 10.0) -> None:
"""Receiver data poller."""
while True:
await asyncio.sleep(interval)
if _R2_IN_STANDBY:
continue
try:
for device in _configured_devices.values():
if device.state == States.OFF:
continue
# TODO #20 run in parallel, join, adjust interval duration based on execution time for next update
await device.async_update_data()
except (KeyError, ValueError):
pass


@api.listens_to(ucapi.Events.CONNECT)
async def on_r2_connect_cmd() -> None:
"""Connect all configured receivers when the Remote Two sends the connect command."""
Expand All @@ -59,7 +43,7 @@ async def on_r2_connect_cmd() -> None:
for device in _configured_devices.values():
# start background task
await device.connect()
await device.async_update_data()
await _LOOP.create_task(device.update())
await api.set_device_state(ucapi.DeviceStates.CONNECTED)


Expand Down Expand Up @@ -100,7 +84,7 @@ async def on_r2_exit_standby() -> None:

for device in _configured_devices.values():
# start background task
await device.async_update_data()
await _LOOP.create_task(device.update())


@api.listens_to(ucapi.Events.SUBSCRIBE_ENTITIES)
Expand Down Expand Up @@ -316,7 +300,7 @@ def _configure_new_device(

if connect:
# start background connection task
_LOOP.create_task(device.async_update_data())
_LOOP.create_task(device.update())
_LOOP.create_task(on_device_connected(device_config.id))
_register_available_entities(device_config, device)

Expand Down Expand Up @@ -423,9 +407,8 @@ async def main():
for device in _configured_devices.values():
if device.state in [States.OFF, States.UNKNOWN]:
continue
_LOOP.create_task(device.async_update_data())
_LOOP.create_task(device.update())

_LOOP.create_task(device_status_poller())
# Patched method
# pylint: disable = W0212
IntegrationAPI._broadcast_ws_event = patched_broadcast_ws_event
Expand Down
12 changes: 11 additions & 1 deletion intg-zidoo/setup_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,15 @@ async def _handle_discovery(msg: UserDataResponse) -> RequestUserInput | SetupEr
"de": "Wähle deinen Zidoo",
"fr": "Choisissez votre décodeur Zidoo",
},
}
},
{
"id": "always_on",
"label": {
"en": "Keep connection alive (faster initialization, but consumes more battery)",
"fr": "Conserver la connexion active (lancement plus rapide, mais consomme plus de batterie)",
},
"field": {"checkbox": {"value": False}},
},
],
)

Expand All @@ -333,6 +341,7 @@ async def handle_device_choice(msg: UserDataResponse) -> SetupComplete | SetupEr
"""
# pylint: disable = W0718
host = msg.input_values["choice"]
always_on = msg.input_values.get("always_on") == "true"
_LOG.debug(
"Chosen Zidoo: %s. Trying to connect and retrieve device information...", host
)
Expand Down Expand Up @@ -368,6 +377,7 @@ async def handle_device_choice(msg: UserDataResponse) -> SetupComplete | SetupEr
address=host,
net_mac_address=net_mac_address,
wifi_mac_address=wifi_mac_address,
always_on=always_on
)
) # triggers ZidooAVR instance creation
config.devices.store()
Expand Down
Loading

0 comments on commit 6e7fec4

Please sign in to comment.