Skip to content

Commit

Permalink
fix: reattach mqtt when token expires (#60)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
cdnninja and pre-commit-ci[bot] authored May 29, 2024
1 parent c9e5629 commit 4aedba1
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions yoto_api/YotoManager.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""YotoManager.py"""

import datetime
from datetime import datetime, timedelta
import logging
import pytz

Expand All @@ -22,6 +22,7 @@ def __init__(self, username: str, password: str) -> None:
self.token: Token = None
self.library: list = {}
self.mqtt_client: dict = {}
self.callback: None

def initialize(self) -> None:
self.token: Token = self.api.login(self.username, self.password)
Expand All @@ -37,6 +38,7 @@ def update_players_status(self) -> None:

def connect_to_events(self, callback=None) -> None:
# Starts and connects to MQTT. Runs a loop to receive events. Callback is called when event has been processed and player updated.
self.callback = callback
for player in self.players.values():
self.mqtt_client[player.id] = YotoMQTTClient()
self.mqtt_client[player.id].connect_mqtt(self.token, player, callback)
Expand Down Expand Up @@ -98,8 +100,13 @@ def check_and_refresh_token(self) -> bool:
self.initialize()
return True
# Check if valid and correct if not
if self.token.valid_until <= datetime.datetime.now(pytz.utc):
if self.token.valid_until - timedelta(hours=1) <= datetime.datetime.now(
pytz.utc
):
_LOGGER.debug(f"{DOMAIN} - access token expired")
self.token: Token = self.api.refresh_token(self.token)
if len(self.mqtt_client.keys()) != 0:
self.disconnect()
self.connect_to_events(self.callback)
return True
return False

0 comments on commit 4aedba1

Please sign in to comment.