From afe15a9291852106525b9096fbc66222d128bd7b Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Tue, 4 Jan 2022 14:44:29 -1000 Subject: [PATCH] Fix reconnect race (#306) --- flux_led/aiodevice.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/flux_led/aiodevice.py b/flux_led/aiodevice.py index 6cb756de..c3810a6d 100644 --- a/flux_led/aiodevice.py +++ b/flux_led/aiodevice.py @@ -79,7 +79,7 @@ def __init__( ) -> None: """Init and setup the bulb.""" super().__init__(ipaddr, port, timeout, discovery) - self._lock = asyncio.Lock() + self._connect_lock = asyncio.Lock() self._aio_protocol: Optional[AIOLEDENETProtocol] = None self._get_time_lock: asyncio.Lock = asyncio.Lock() self._get_time_future: Optional[asyncio.Future[bool]] = None @@ -747,8 +747,10 @@ def process_remote_config_response(self, msg: bytes) -> None: async def _async_send_msg(self, msg: bytearray) -> None: """Write a message on the socket.""" if not self._aio_protocol: - async with self._lock: - await self._async_connect() + async with self._connect_lock: + # Check again under the lock + if not self._aio_protocol: + await self._async_connect() assert self._aio_protocol is not None self._aio_protocol.write(msg) @@ -758,7 +760,7 @@ async def _async_determine_protocol(self) -> None: protocol = protocol_cls() assert isinstance(protocol, (ProtocolLEDENET8Byte, ProtocolLEDENETOriginal)) self._protocol = protocol - async with self._lock: + async with self._connect_lock: await self._async_connect() assert self._aio_protocol is not None self._determine_protocol_future = asyncio.Future()