Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for redirect command #14

Merged
merged 3 commits into from
Aug 26, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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