1
0
mirror of https://github.com/no2chem/wideq.git synced 2025-05-16 15:20:09 -07:00

Try wrapping stuff up in a mutable client class

This commit is contained in:
Adrian Sampson 2018-01-20 21:33:44 -05:00
parent 0dde92b241
commit 948d51b1b6

View File

@ -34,70 +34,71 @@ def authenticate(gateway):
return wideq.Auth.from_url(gateway, callback_url) return wideq.Auth.from_url(gateway, callback_url)
def get_session(state, reauth=False): class Client(object):
"""Get a Session object we can use to make API requests. def __init__(self):
# The three steps required to get access to call the API.
self._gateway = None
self._auth = None
self._session = None
By default, try to use credentials from `state`. If `reauth` if # The last list of devices we got from the server.
true, instead force re-authentication. self._devices = None
Return the Session and, if they came along with session creation, @property
the information about the user's devices. def gateway(self):
""" if not self._gateway:
self._gateway = wideq.Gateway.discover()
return self._gateway
# Get the gateway, which contains the base URLs and hostnames for @property
# accessing the API. def auth(self):
if 'gateway' in state: if not self._auth:
gateway = wideq.Gateway.load(state['gateway']) assert False, "unauthenticated"
else: return self._auth
print('Discovering gateway servers.')
gateway = wideq.Gateway.discover()
state['gateway'] = gateway.dump() @property
save_state(state) def session(self):
if not self._session:
self._session, self._devices = self.auth.start_session()
return self._session
# Authenticate the user. def load(self, state):
if 'auth' in state and not reauth: """Load the client objects from the encoded state data.
auth = wideq.Auth.load(gateway, state['auth']) """
new_auth = False
else:
auth = authenticate(gateway)
new_auth = True
state['auth'] = auth.dump() if 'gateway' in state:
save_state(state) self._gateway = wideq.Gateway.load(state['gateway'])
# Start a session. if 'auth' in state:
if 'session' in state and not new_auth: self._auth = wideq.Auth.load(self._gateway, state['auth'])
session = wideq.Session.load(auth, state['session'])
devices = None
else:
print('Starting session.')
session, devices = auth.start_session()
state['session'] = session.dump() if 'session' in state:
save_state(state) self._session = wideq.Session.load(self._auth, state['session'])
return session, devices def dump(self):
"""Serialize the client state."""
out = {}
if self._gateway:
out['gateway'] = self._gateway.dump()
if self._auth:
out['auth'] = self._auth.dump()
if self._session:
out['session'] = self._session.dump()
return out
def refresh_session(state, session): def refresh(self):
print('Refreshing authentication.') self._auth = self.auth.refresh()
auth = session.auth.refresh() self._session, self._devices = self.auth.start_session()
state['auth'] = auth.dump()
save_state(state)
print('Restarting session.')
session, devices = auth.start_session()
state['session'] = session.dump()
save_state(state)
return session, devices
def example(args): def example(args):
state = load_state() state = load_state()
client = Client()
client.load(state)
session, devices = get_session(state) if not client._auth:
client._auth = authenticate(client.gateway)
# Loop to retry if session has expired. # Loop to retry if session has expired.
while True: while True:
@ -105,8 +106,9 @@ def example(args):
if not args or args[0] == 'ls': if not args or args[0] == 'ls':
# Request a list of devices, if we didn't get them "for free" # Request a list of devices, if we didn't get them "for free"
# already by starting the session. # already by starting the session.
devices = client._devices
if not devices: if not devices:
devices = session.get_devices() devices = client.session.get_devices()
for device in devices: for device in devices:
print('{deviceId}: {alias} ({modelNm})'.format(**device)) print('{deviceId}: {alias} ({modelNm})'.format(**device))
@ -114,7 +116,7 @@ def example(args):
elif args[0] == 'mon': elif args[0] == 'mon':
device_id = args[1] device_id = args[1]
with wideq.Monitor(session, device_id) as mon: with wideq.Monitor(client.session, device_id) as mon:
try: try:
while True: while True:
time.sleep(1) time.sleep(1)
@ -131,13 +133,16 @@ def example(args):
temp = args[1] temp = args[1]
device_id = args[2] device_id = args[2]
session.set_device_controls(device_id, {'TempCfg': temp}) client.session.set_device_controls(device_id,
{'TempCfg': temp})
break break
except wideq.NotLoggedInError: except wideq.NotLoggedInError:
print('Session expired.') print('Session expired.')
session, devices = refresh_session(state, session) client.refresh()
save_state(client.dump())
if __name__ == '__main__': if __name__ == '__main__':