Skip to content

Commit

Permalink
Merge pull request #1 from konnected-io/async
Browse files Browse the repository at this point in the history
Async
  • Loading branch information
kit-klein authored Jan 2, 2020
2 parents 0a3f2d0 + 313ac83 commit 577464f
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 47 deletions.
51 changes: 30 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,40 +11,49 @@ For more information see [konnected.io](https://konnected.io)
## Usage

```
>>> import konnected
import aiohttp
import asyncio
import konnected
# Initialize the Konnected client with a host and port.
# Every Konnected module uses a different HTTP port
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
>>> k = konnected.Client('192.168.86.10', '17000')
async def main():
async with aiohttp.ClientSession() as session:
k = konnected.Client('192.168.86.10', '17000', session)
# Sync settings to the device
# Sync settings to the device
>>> k.put_settings(sensors=[{"pin":1}], actuators=[], auth_token='secureToken', endpoint='http://example.com')
True
print(await k.put_settings(sensors=[{"pin":1}], actuators=[], auth_token='secureToken', endpoint='http://example.com'))
# True
# Get status of each input pin
>>> k.get_device()
[{'state': 0, 'pin': 1}, {'state': 1, 'pin': 2}]
# Get status of each input pin
# Get status of a single input pin
print(await k.get_device())
# [{'state': 0, 'pin': 1}, {'state': 1, 'pin': 2}]
>>> k.get_device(2)
[{'state': 1, 'pin': 2}]
# Get status of a single input pin
# Actuate an output pin
print(await k.get_device(2))
# [{'state': 1, 'pin': 2}]
>>> k.put_device(pin=8, state=1)
{'state': 1, 'pin': 8}
# Actuate an output pin
# Get device status
print(await k.put_device(pin=8, state=1))
# {'state': 1, 'pin': 8}
>>> k.get_status()
{'mac': '2c:3a:e8:43:8a:38', 'gw': '192.168.86.1', 'hwVersion': '2.0.5', 'rssi': -31, 'nm': '255.255.255.0', 'ip': '192.168.86.10', 'actuators': [{'trigger': 1, 'pin': 8}], 'port': 12426, 'uptime': 2349, 'heap': 23904, 'swVersion': '2.1.3', 'sensors': [{'state': 0, 'pin': 1}]}
# Get device status
'''
await k.get_status()
# {'mac': '2c:3a:e8:43:8a:38', 'gw': '192.168.86.1', 'hwVersion': '2.0.5', 'rssi': -31, 'nm': '255.255.255.0', 'ip': '192.168.86.10', 'actuators': [{'trigger': 1, 'pin': 8}], 'port': 12426, 'uptime': 2349, 'heap': 23904, 'swVersion': '2.1.3', 'sensors': [{'state': 0, 'pin': 1}]}
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
```

## Python version

This library was designed to work with Python 3. Parts may work with Python 2.7, but if it does it's totally accidental.
This library was designed to work with Python 3.5 and above.
42 changes: 20 additions & 22 deletions konnected/__init__.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,39 @@
# Python library for interacting with Konnected devices
# learn more at konnected.io

import requests
import asyncio
import aiohttp
import json
import os

from requests.exceptions import RequestException;

__author__ = 'Nate Clark, Konnected Inc <[email protected]>'


class Client(object):

def __init__(self, host, port):
def __init__(self, host, port, websession):
self.host = host
self.port = port
self.websession = websession
self.base_url = 'http://' + host + ':' + port

def get_device(self, pin=None):
async def get_device(self, pin=None):
""" Query the status of a specific pin (or all configured pins if pin is ommitted) """
url = self.base_url + '/device'
try:
r = requests.get(url, params={'pin': pin}, timeout=10)
return r.json()
except RequestException as err:
async with self.websession.get(url, params={'pin': pin}, timeout=10) as resp:
return await resp.json()
except (aiohttp.ClientError, asyncio.TimeoutError) as err:
raise Client.ClientError(err)

def get_status(self):
async def get_status(self):
""" Query the device status. Returns JSON of the device internal state """
url = self.base_url + '/status'
try:
r = requests.get(url, timeout=10)
return r.json()
except RequestException as err:
async with self.websession.get(url, timeout=10) as resp:
return await resp.json()
except (aiohttp.ClientError, asyncio.TimeoutError) as err:
raise Client.ClientError(err)

def put_device(self, pin, state, momentary=None, times=None, pause=None):
async def put_device(self, pin, state, momentary=None, times=None, pause=None):
""" Actuate a device pin """
url = self.base_url + '/device'

Expand All @@ -54,12 +52,12 @@ def put_device(self, pin, state, momentary=None, times=None, pause=None):
payload["pause"] = pause

try:
r = requests.put(url, json=payload, timeout=10)
return r.json()
except RequestException as err:
async with self.websession.put(url, json=payload, timeout=10) as resp:
return await resp.json()
except (aiohttp.ClientError, asyncio.TimeoutError) as err:
raise Client.ClientError(err)

def put_settings(self, sensors=[], actuators=[], auth_token=None,
async def put_settings(self, sensors=[], actuators=[], auth_token=None,
endpoint=None, blink=None, discovery=None,
dht_sensors=[], ds18b20_sensors=[]):
""" Sync settings to the Konnected device """
Expand All @@ -81,9 +79,9 @@ def put_settings(self, sensors=[], actuators=[], auth_token=None,
payload['discovery'] = discovery

try:
r = requests.put(url, json=payload, timeout=10)
return r.ok
except RequestException as err:
async with self.websession.put(url, json=payload, timeout=10) as resp:
return (resp.status >= 200 and resp.status < 300)
except (aiohttp.ClientError, asyncio.TimeoutError) as err:
raise Client.ClientError(err)

class ClientError(Exception):
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
requests
aiohttp
6 changes: 3 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@

setup(
name='konnected',
version='0.1.5',
version='1.0.0',
packages=['konnected'],
url='https://github.com/konnected-io/konnected-py',
license=license,
description='A Python library for interacting with Konnected home automation controllers (see https://konnected.io)',
description='A async Python library for interacting with Konnected home automation controllers (see https://konnected.io)',
long_description=long_description,
author='Nate Clark, Konnected Inc',
author_email='[email protected]',
install_requires=['requests>=2.0'],
install_requires=['aiohttp>=3.6.1'],
project_urls={
'Homepage': 'https://github.com/konnected-io/konnected-py',
'Website & Online Store': 'https://konnected.io',
Expand Down

0 comments on commit 577464f

Please sign in to comment.