Skip to content

Commit

Permalink
fix: set event loop for client
Browse files Browse the repository at this point in the history
  • Loading branch information
muhlba91 committed Dec 12, 2023
1 parent 45b1d6b commit b5e3fae
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
9 changes: 8 additions & 1 deletion custom_components/hella_onyx/api_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,17 @@ def __init__(self, hass, fingerprint, token):
self.token = token
self.devices = {}
self.groups = {}
self._loop = None
self.__client = None

def _client(self):
if self.__client is None:
self._loop = asyncio.new_event_loop()
self.__client = create(
fingerprint=self.fingerprint,
access_token=self.token,
client_session=async_get_clientsession(self.hass),
event_loop=asyncio.new_event_loop(),
event_loop=self._loop,
)
return self.__client

Expand Down Expand Up @@ -85,6 +87,8 @@ async def send_device_command_properties(self, uuid: str, properties: dict):
def start(self, include_details):
"""Start the event loop."""
_LOGGER.info("Starting ONYX")
asyncio.set_event_loop(self._loop)
self._loop.run_forever()
self._client().start(include_details, MAX_BACKOFF_TIME)

def set_event_callback(self, callback):
Expand All @@ -95,6 +99,9 @@ def stop(self, **kwargs: Any):
"""Stop the event loop."""
_LOGGER.info("Shutting down ONYX")
self._client().stop()
self._loop.stop()
self.__client = None
self._loop = None


class CommandException(Exception):
Expand Down
14 changes: 9 additions & 5 deletions tests/test_api_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,17 +131,21 @@ async def test__client(self, api):
assert client is not None
assert isinstance(client, OnyxClient)

@patch("asyncio.set_event_loop")
@pytest.mark.asyncio
async def test_start(self, api, client):
async def test_start(self, mock_set_event_loop, api, client):
with patch.object(api, "_client", new=client.make):
api.start(True)
assert client.is_called
with patch.object(api, "_loop"):
api.start(True)
assert client.is_called
assert mock_set_event_loop.called

@pytest.mark.asyncio
async def test_stop(self, api, client):
with patch.object(api, "_client", new=client.make):
api.stop()
assert client.is_called
with patch.object(api, "_loop"):
api.stop()
assert client.is_called

@pytest.mark.asyncio
async def test_set_event_callback(self, api, client):
Expand Down

0 comments on commit b5e3fae

Please sign in to comment.