Skip to content

Commit

Permalink
fix: change the way server pings are handled
Browse files Browse the repository at this point in the history
- ping regularly, regardless of replies
- count the number of replies between pings
- reconnect if zero replies
- both SMSG_PING and SMSG_DEVICE_STATUS count as replies
- request map info on the first SMSG_PING.
  • Loading branch information
zzarne committed Sep 16, 2021
1 parent c61ea2c commit 8ed6a26
Showing 1 changed file with 22 additions and 9 deletions.
31 changes: 22 additions & 9 deletions custom_components/badconga/app/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def __init__(self):
self.password = None
self.session_id = None
self.timer = None
self.pongs = -1
self.device = Device()
self.builder = Builder()
self.map = Map()
Expand Down Expand Up @@ -85,12 +86,11 @@ def on_disconnect(self):

def handle_ping(self, _):
""" handlePing """
timer = self.timer
if timer:
timer.cancel()
timer = threading.Timer(30.0, self.ping)
timer.start()
self.timer = timer
self.pongs += 1

# request the map only after the device reponded to a ping
if not self.map.robot.isvalid():
self.get_map_info()

def handle_user_login(self, schema):
""" handle_user_login """
Expand All @@ -113,6 +113,7 @@ def handle_session_login(self, schema):

def handle_device_status(self, schema):
""" handle_device_status """
self.pongs += 1 # count status message as ping reply, too
self.device.battery_level = schema.battery
self.device.work_mode = schema.workMode
self.device.charge_status = schema.chargeStatus
Expand Down Expand Up @@ -201,8 +202,7 @@ def handle_user_logout(self, _):
def on_login(self):
""" on_login """
self.get_device_list()
self.get_map_info()
self.ping()
self.ping(first=True)

# methods

Expand All @@ -225,10 +225,23 @@ def disconnect_device(self):
""" disconnect_device """
self.send('CMSG_DISCONNECT_DEVICE')

def ping(self):
def ping(self, first=False):
""" ping """
if self.pongs < 1 and not first:
logger.debug('no response to ping, reconnecting')
self.socket.disconnect()
return

self.pongs = 0
self.send('CMSG_PING')

timer = self.timer
if timer:
timer.cancel()
timer = threading.Timer(30.0, self.ping)
timer.start()
self.timer = timer

def set_session(self, session_id, user_id, device_id):
""" set_session """
self.builder.user_id = user_id
Expand Down

0 comments on commit 8ed6a26

Please sign in to comment.