Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert "Significantly reduce heartbeat overhead (#301)" #611

Merged
merged 4 commits into from
Aug 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 2 additions & 77 deletions aioshelly/rpc_device/wsrpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@

_LOGGER = logging.getLogger(__name__)

WS_HEATBEAT_HALF_INTERVAL = WS_HEARTBEAT / 2

BUFFER_SIZE = 1024 * 64


Expand Down Expand Up @@ -166,10 +164,7 @@ def __init__(
self._calls: dict[int, RPCCall] = {}
self._call_id = 0
self._session = SessionData(f"aios-{id(self)}", None, None)
self._heartbeat_cb: asyncio.TimerHandle | None = None
self._pong_response_cb: asyncio.TimerHandle | None = None
self._loop = asyncio.get_running_loop()
self._last_time: float = 0
self._background_tasks: set[Task] = set()

@property
Expand All @@ -188,7 +183,7 @@ async def connect(self, aiohttp_session: ClientSession) -> None:
URL.build(
scheme="http", host=self._ip_address, port=self._port, path="/rpc"
),
autoping=False,
heartbeat=WS_HEARTBEAT,
)
except (
client_exceptions.WSServerHandshakeError,
Expand All @@ -210,69 +205,8 @@ async def connect(self, aiohttp_session: ClientSession) -> None:
)

self._rx_task = asyncio.create_task(self._rx_msgs())
self._schedule_heartbeat()
_LOGGER.info("Connected to %s", self._ip_address)

def _cancel_heartbeat(self) -> None:
"""Cancel heartbeat."""
if self._heartbeat_cb is not None:
self._heartbeat_cb.cancel()
self._heartbeat_cb = None

def _cancel_pong_response_cb(self) -> None:
"""Cancel pong response callback."""
if self._pong_response_cb is not None:
self._pong_response_cb.cancel()
self._pong_response_cb = None

def _cancel_heatbeat_and_pong_response_cb(self) -> None:
"""Cancel heartbeat and pong response callback."""
self._cancel_heartbeat()
self._cancel_pong_response_cb()

def _schedule_heartbeat(self) -> None:
"""Schedule heartbeat."""
self._cancel_heatbeat_and_pong_response_cb()
self._heartbeat_cb = self._loop.call_later(
WS_HEATBEAT_HALF_INTERVAL, self._maybe_send_heartbeat
)

def _schedule_pong_response_cb(self) -> None:
"""Schedule pong response callback."""
self._cancel_pong_response_cb()
self._pong_response_cb = self._loop.call_later(
WS_HEATBEAT_HALF_INTERVAL, self._pong_not_received
)

def _maybe_send_heartbeat(self) -> None:
"""Send heartbeat if no messages have been received.

Heartbeat will be sent if there are no messages for WS_HEARTBEAT seconds.
"""
if not self._client or self._client.closed:
return
if time.time() - self._last_time < WS_HEARTBEAT:
# No need to send heartbeat
# so schedule next heartbeat
self._schedule_heartbeat()
return
self._create_and_track_task(self._ping_if_not_closed())

async def _ping_if_not_closed(self) -> None:
"""Send ping if the client is not closed."""
if not self._client or self._client.closed:
return
self._schedule_pong_response_cb()
await self._client.ping()

def _pong_not_received(self) -> None:
"""Pong not received."""
_LOGGER.error(
"%s:%s: Pong not received, device is likely unresponsive; disconnecting",
self._ip_address,
self._port,
)
self._create_and_track_task(self.disconnect())
_LOGGER.info("Connected to %s", self._ip_address)

async def disconnect(self) -> None:
"""Disconnect all sessions."""
Expand All @@ -281,7 +215,6 @@ async def disconnect(self) -> None:
with contextlib.suppress(asyncio.CancelledError):
await self._rx_task
self._rx_task = None
self._cancel_heatbeat_and_pong_response_cb()
if self._client is None:
return

Expand Down Expand Up @@ -348,13 +281,6 @@ async def _rx_msgs(self) -> None:
while not self._client.closed:
try:
msg = await self._client.receive()
self._last_time = time.time()
if msg.type is WSMsgType.PONG:
self._schedule_heartbeat()
continue
if msg.type is WSMsgType.PING:
await self._client.pong(msg.data)
continue
frame = _receive_json_or_raise(msg)
_LOGGER.debug(
"recv(%s:%s): %s", self._ip_address, self._port, frame
Expand All @@ -380,7 +306,6 @@ async def _rx_msgs(self) -> None:
self._ip_address,
self._port,
)
self._cancel_heatbeat_and_pong_response_cb()

for call_item in self._calls.values():
if not call_item.resolve.done():
Expand Down