Skip to content

Commit

Permalink
Process multiple messages from single response
Browse files Browse the repository at this point in the history
  • Loading branch information
icetomcat committed Jan 12, 2021
1 parent b2cc4f5 commit f4a3caa
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions blynklib_mp.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ def _pack_msg(self, msg_type, *args, **kwargs):

def parse_response(self, rsp_data, msg_buffer):
msg_args = []
msg_tail = b''
try:
msg_type, msg_id, h_data = struct.unpack('!BHH', rsp_data[:self.MSG_HEAD_LEN])
except Exception as p_err:
Expand All @@ -83,9 +84,10 @@ def parse_response(self, rsp_data, msg_buffer):
elif msg_type in (self.MSG_HW, self.MSG_BRIDGE, self.MSG_INTERNAL, self.MSG_REDIRECT):
msg_body = rsp_data[self.MSG_HEAD_LEN: self.MSG_HEAD_LEN + h_data]
msg_args = [itm.decode('utf-8') for itm in msg_body.split(b'\0')]
msg_tail = rsp_data[self.MSG_HEAD_LEN + h_data:]
else:
raise BlynkError("Unknown message type: '{}'".format(msg_type))
return msg_type, msg_id, h_data, msg_args
return msg_type, msg_id, h_data, msg_args, msg_tail

def heartbeat_msg(self, heartbeat, rcv_buffer):
return self._pack_msg(self.MSG_INTERNAL, 'ver', __version__, 'buff-in', rcv_buffer, 'h-beat', heartbeat,
Expand Down Expand Up @@ -214,7 +216,7 @@ def _authenticate(self):
rsp_data = self.receive(self.rcv_buffer, self.SOCK_MAX_TIMEOUT)
if not rsp_data:
raise BlynkError('Auth stage timeout')
msg_type, _, status, args = self.parse_response(rsp_data, self.rcv_buffer)
msg_type, _, status, args, _ = self.parse_response(rsp_data, self.rcv_buffer)
if status != self.STATUS_OK:
if status == self.STATUS_INVALID_TOKEN:
raise BlynkError('Invalid Auth Token')
Expand All @@ -229,7 +231,7 @@ def _set_heartbeat(self):
rcv_data = self.receive(self.rcv_buffer, self.SOCK_MAX_TIMEOUT)
if not rcv_data:
raise BlynkError('Heartbeat stage timeout')
_, _, status, _ = self.parse_response(rcv_data, self.rcv_buffer)
_, _, status, _, _ = self.parse_response(rcv_data, self.rcv_buffer)
if status != self.STATUS_OK:
raise BlynkError('Set heartbeat returned code={}'.format(status))
self.log('Heartbeat = {} sec. MaxCmdBuffer = {} bytes'.format(self.heartbeat, self.rcv_buffer))
Expand Down Expand Up @@ -353,8 +355,9 @@ def read_response(self, timeout=0.5):
rsp_data = self.receive(self.rcv_buffer, self.SOCK_TIMEOUT)
if rsp_data:
self._last_rcv_time = ticks_ms()
msg_type, msg_id, h_data, msg_args = self.parse_response(rsp_data, self.rcv_buffer)
self.process(msg_type, msg_id, h_data, msg_args)
while rsp_data:
msg_type, msg_id, h_data, msg_args, rsp_data = self.parse_response(rsp_data, self.rcv_buffer)
self.process(msg_type, msg_id, h_data, msg_args)

def run(self):
if not self.connected():
Expand Down

0 comments on commit f4a3caa

Please sign in to comment.