Skip to content

Commit

Permalink
Merge pull request #4 from Cyr-ius/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
cyr-ius committed Jan 23, 2022
2 parents 809658d + d0da4f7 commit 2a17610
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 36 deletions.
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,19 @@ Get started
-----------
```python
# Import the heatzypy package.
import asyncio
from heatzypy import HeatzyClient

api = HeatzyClient("username", "password")

async def async_demo():
async def main():
api = HeatzyClient("username", "password")
devices = await api.async_get_devices()
for device in devices:
name = device.get("dev_alias")
data = await api.async_get_device(device["did"])
mode = data.get("attr").get("mode")
logger.info("Heater : {} , mode : {}".format(name, mode))

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
```
Have a look at the [example.py](https://github.com/cyr-ius/heatzypy/blob/master/example.py) for a more complete overview.

Expand Down
27 changes: 16 additions & 11 deletions example.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,33 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'''
"""
This example can be run safely as it won't change anything in your box configuration
'''
"""

import asyncio
import logging

from heatzypy import HeatzyClient
from heatzypy.heatzy import HeatzyClient

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)

username = "my-login"
password = "my-password"
USERNAME = "my-login"
PASSWORD = "my-password"

api = HeatzyClient(username, password)
devices = api.async_get_devices()
for device in devices:
data = api.async_get_device_info(device["did"])
logger.info("Heater : {} , mode : {}".format(data.get("dev_alias"), data.get("attr").get("mode")))
async def main():
api = HeatzyClient(USERNAME, PASSWORD)
devices = await api.async_get_devices()
for device in devices:
name = device.get("dev_alias")
data = await api.async_get_device(device["did"])
mode = data.get("attr").get("mode")
logger.info("Heater : {} , mode : {}".format(name, mode))
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
5 changes: 4 additions & 1 deletion heatzypy.code-workspace
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@
"python.linting.pycodestyleArgs": [
"--ignore=E501,W503"
],
"python.pythonPath": "/media/datas/hass-integrations/heatzypy/.venv/bin/python"
"python.pythonPath": "/media/datas/hass-integrations/heatzypy/.venv/bin/python",
"cSpell.words": [
"aiohttp"
]
},
"launch": {
"version": "0.2.0",
Expand Down
2 changes: 1 addition & 1 deletion heatzypy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
from .heatzy import HeatzyClient

name = "heatzy"
__version__ = "2.0.0"
__version__ = "2.0.1"
__all__ = ["HeatzyClient"]
35 changes: 17 additions & 18 deletions heatzypy/heatzy.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
import logging
import time

import requests
from requests.exceptions import RequestException
from aiohttp import ClientSession, ClientError

from .const import HEATZY_API_URL, HEATZY_APPLICATION_ID
from .exception import HeatzyException, HttpRequestFailed
Expand All @@ -14,9 +13,9 @@
class HeatzyClient:
"""Heatzy Client data."""

def __init__(self, username, password):
def __init__(self, username, password, session=None):
"""Load parameters."""
self._session = requests.Session()
self._session = session if session else ClientSession()
self._username = username
self._password = password
self._authentication = None
Expand All @@ -27,9 +26,9 @@ async def async_authenticate(self):
payload = {"username": self._username, "password": self._password}

response = await self._async_make_request("/login", method="POST", payload=payload, headers=headers)
if response.status_code != 200:
raise HeatzyException("Authentication failed", response.status_code)
return response.json()
if response.status != 200:
raise HeatzyException("Authentication failed", response.status)
return await response.json()

async def async_get_token(self):
"""Get authentication token."""
Expand All @@ -49,30 +48,30 @@ async def _async_make_request(self, service, method="GET", headers=None, payload
try:
url = HEATZY_API_URL + service
_LOGGER.debug("{} {} {}".format(method, url, headers))
return self._session.request(method=method, url=url, json=payload, headers=headers)
except RequestException as error:
return await self._session.request(method=method, url=url, json=payload, headers=headers)
except ClientError as error:
raise HttpRequestFailed("Request failed") from error

async def async_get_devices(self):
"""Fetch all configured devices."""
response = await self._async_make_request("/bindings")
if response.status_code != 200:
raise HeatzyException("Devices not retrieved", response.status_code)
if response.status != 200:
raise HeatzyException("Devices not retrieved", response.status)

# API response has Content-Type=text/html, content_type=None silences parse error by forcing content type
body = response.json()
body = await response.json(content_type=None)
devices = body.get("devices")

return [await self._async_merge_with_device_data(device) for device in devices]

async def async_get_device(self, device_id):
"""Fetch device with given id."""
response = await self._async_make_request(f"/devices/{device_id}")
if response.status_code != 200:
raise HeatzyException(f"Device data for {device_id} not retrieved", response.status_code)
if response.status != 200:
raise HeatzyException(f"Device data for {device_id} not retrieved", response.status)

# API response has Content-Type=text/html, content_type=None silences parse error by forcing content type
device = response.json()
device = await response.json(content_type=None)
return await self._async_merge_with_device_data(device)

async def _async_merge_with_device_data(self, device):
Expand All @@ -83,9 +82,9 @@ async def _async_merge_with_device_data(self, device):
async def async_get_device_data(self, device_id):
"""Fetch detailled data for device with given id."""
response = await self._async_make_request(f"/devdata/{device_id}/latest")
if response.status_code != 200:
raise HeatzyException(f"Device data for {device_id} not retrieved", response.status_code)
device_data = response.json()
if response.status != 200:
raise HeatzyException(f"Device data for {device_id} not retrieved", response.status)
device_data = await response.json()
return device_data

async def async_control_device(self, device_id, payload):
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# Heatzypy
requests>=2.20.0
aiohttp>=3.8.1

0 comments on commit 2a17610

Please sign in to comment.