Skip to content
This repository has been archived by the owner on Jul 12, 2023. It is now read-only.

Commit

Permalink
Merge pull request #8 from mjmeli/reconnect-async
Browse files Browse the repository at this point in the history
ensure connects and reconnects are done async safe since they block
  • Loading branch information
mjmeli authored Dec 3, 2021
2 parents dc414ee + 1630ea2 commit b0b295e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 15 deletions.
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = pyduke-energy
version = 0.0.12
version = 0.0.13
author = Michael Meli
author_email = [email protected]
description = Python Wrapper for unofficial Duke Energy REST API
Expand Down
38 changes: 24 additions & 14 deletions src/pyduke_energy/realtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ def on_discon(self, _client: mqtt.Client, _userdata, conn_res):
if self.disconnecting:
self.disconnected.set_result(conn_res)
else:
self.mqtt_client.reconnect()
_LOGGER.warning("Unexpected MQTT disconnect. Attempting reconnect.")
self.async_mqtt_client_reconnect()

@staticmethod
def on_msg(msg):
Expand Down Expand Up @@ -212,18 +213,7 @@ async def connect_and_subscribe(self):
self.mqtt_client.tls_set_context(ssl.create_default_context())

mqtt_conn = MqttConnHelper(self.loop, self.mqtt_client)

# Run connect() within an executor thread, since it blocks on socket
# connection for up to `keepalive` seconds: https://git.io/Jt5Yc
await self.loop.run_in_executor(
None,
functools.partial(
self.mqtt_client.connect,
MQTT_HOST,
port=MQTT_PORT,
keepalive=MQTT_KEEPALIVE,
),
)
self.async_mqtt_client_connect()

try:
while not mqtt_conn.misc.cancelled():
Expand Down Expand Up @@ -292,7 +282,27 @@ async def _reconnect(self):
self.mqtt_client.username_pw_set(
self.mqtt_auth["user"], password=self.mqtt_auth["pass"]
)
self.mqtt_client.connect(MQTT_HOST, port=MQTT_PORT, keepalive=MQTT_KEEPALIVE)
self.async_mqtt_client_connect()

async def async_mqtt_client_connect(self):
"""Run connect() in an async safe manner to avoid blocking."""
# Run connect() within an executor thread, since it blocks on socket
# connection for up to `keepalive` seconds: https://git.io/Jt5Yc
await self.loop.run_in_executor(
None,
functools.partial(
self.mqtt_client.connect,
MQTT_HOST,
port=MQTT_PORT,
keepalive=MQTT_KEEPALIVE,
),
)

async def async_mqtt_client_reconnect(self):
"""Run reconnect() in an async safe manner to avoid blocking."""
# Run reconnect() within an executor thread, since it blocks on socket
# connection for up to `keepalive` seconds: https://git.io/Jt5Yc
await self.loop.run_in_executor(None, self.mqtt_client.reconnect)


class MqttConnHelper:
Expand Down

0 comments on commit b0b295e

Please sign in to comment.