Skip to content

Commit

Permalink
Wrap TCP request reading in async_timeout.timeout()
Browse files Browse the repository at this point in the history
There have recently been [reports of `RuntimeError: coroutine ignored
GeneratorExit`] which are presumably triggered by timeouts on the
socket, without being raised as `TimeoutError`.  This case seems to be
mitigated by timing out the request after a default of 10 seconds which
doesn't give `GeneratorExit` - triggered by something yet unknown -
enough time to surface.

[reports of `RuntimeError: coroutine ignored GeneratorExit`]: robbinjanssen/home-assistant-omnik-inverter#116
  • Loading branch information
MarijnS95 committed Sep 30, 2022
1 parent 6c6b510 commit 26f77e7
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions omnikinverter/omnikinverter.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,20 +139,34 @@ async def tcp_request(self) -> dict[str, Any]:
raise OmnikInverterAuthError("serial_number is missing from the request")

try:
if self._socket_mock is not None:
reader, writer = await asyncio.open_connection(sock=self._socket_mock)
else: # pragma: no cover
reader, writer = await asyncio.open_connection(self.host, self.tcp_port)
async with async_timeout.timeout(self.request_timeout):
if self._socket_mock is not None:
reader, writer = await asyncio.open_connection(
sock=self._socket_mock
)
else: # pragma: no cover
reader, writer = await asyncio.open_connection(
self.host, self.tcp_port
)
except OSError as exception:
raise OmnikInverterConnectionError(
"Failed to open a TCP connection to the Omnik Inverter device"
) from exception
except asyncio.TimeoutError as exception:
raise OmnikInverterConnectionError(
"Timeout occurred while connecting to Omnik Inverter device"
) from exception

try:
writer.write(tcp.create_information_request(self.serial_number))
await writer.drain()
async with async_timeout.timeout(self.request_timeout):
writer.write(tcp.create_information_request(self.serial_number))
await writer.drain()

raw_msg = await reader.read(1024)
raw_msg = await reader.read(1024)
except asyncio.TimeoutError as exception:
raise OmnikInverterConnectionError(
"Timeout occurred while connecting to Omnik Inverter device"
) from exception
finally:
writer.close()
try:
Expand Down

0 comments on commit 26f77e7

Please sign in to comment.