Skip to content

Commit

Permalink
Add support for redirect command (#14)
Browse files Browse the repository at this point in the history
* Add support for redirect command
  • Loading branch information
egueli authored and antohaUa committed Aug 26, 2019
1 parent f3d1b76 commit 2ebcf31
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions blynklib.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ def stub_log(*args):
class BlynkError(Exception):
pass

class RedirectError(Exception):
def __init__(self, server, port):
self.server = server
self.port = port


class Protocol(object):
MSG_RSP = const(0)
Expand All @@ -53,9 +58,11 @@ class Protocol(object):
MSG_INTERNAL = const(17)
MSG_PROPERTY = const(19)
MSG_HW = const(20)
MSG_REDIRECT = const(41)
MSG_HEAD_LEN = const(5)

STATUS_INVALID_TOKEN = const(9)
STATUS_NO_DATA = const(17)
STATUS_OK = const(200)
VPIN_MAX_NUM = const(32)

Expand Down Expand Up @@ -83,7 +90,7 @@ def parse_response(self, rsp_data, msg_buffer):
raise BlynkError('Command too long. Length = {}'.format(h_data))
elif msg_type in (self.MSG_RSP, self.MSG_PING, self.MSG_INTERNAL):
pass
elif msg_type in (self.MSG_HW, self.MSG_BRIDGE):
elif msg_type in (self.MSG_HW, self.MSG_BRIDGE, 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')]
else:
Expand Down Expand Up @@ -214,10 +221,12 @@ def _authenticate(self):
rsp_data = self.receive(self.rcv_buffer, self.SOCK_MAX_TIMEOUT)
if not rsp_data:
raise BlynkError('Auth stage timeout')
_, _, status, _ = 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')
if msg_type == self.MSG_REDIRECT:
raise RedirectError(*args)
raise BlynkError('Auth stage failed. Status={}'.format(status))
self._state = self.AUTHENTICATED
self.log('Access granted')
Expand Down Expand Up @@ -271,6 +280,11 @@ def connect(self, timeout=_CONNECT_TIMEOUT):
except BlynkError as b_err:
self.disconnect(b_err)
sleep_ms(self.TASK_PERIOD_RES)
except RedirectError as r_err:
self.disconnect()
self.server = r_err.server
self.port = r_err.port
sleep_ms(self.TASK_PERIOD_RES)
if time.time() >= end_time:
return False

Expand Down

0 comments on commit 2ebcf31

Please sign in to comment.