Skip to content

Commit

Permalink
Fix unclosed resources
Browse files Browse the repository at this point in the history
  • Loading branch information
lafriks committed May 7, 2023
1 parent d74c007 commit 466ceee
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 15 deletions.
11 changes: 10 additions & 1 deletion karcher/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ def cli(ctx: click.Context, debug: int, output: str, country: str):

logging.basicConfig(level=level)

ctx.obj = GlobalContextObject(debug=debug, output=output, country=country.upper())
ctx.obj = GlobalContextObject(
debug=debug, output=output, country=country.upper())


def safe_cli():
Expand All @@ -99,6 +100,7 @@ async def urls(ctx: click.Context):

kh = await KarcherHome.create(country=ctx.obj.country)
d = await kh.get_urls()
await kh.close()

ctx.obj.print(d)

Expand All @@ -112,8 +114,11 @@ async def login(ctx: click.Context, username: str, password: str):
"""Get user session tokens."""

kh = await KarcherHome.create(country=ctx.obj.country)

ctx.obj.print(kh.login(username, password))

await kh.close()


@cli.command()
@click.option('--username', '-u', default=None, help='Username to login with.')
Expand All @@ -139,6 +144,8 @@ async def devices(ctx: click.Context, username: str, password: str, auth_token:
if auth_token is None:
await kh.logout()

await kh.close()

ctx.obj.print(devices)


Expand Down Expand Up @@ -183,4 +190,6 @@ async def device_properties(
if auth_token is None:
await kh.logout()

await kh.close()

ctx.obj.print(props)
47 changes: 35 additions & 12 deletions karcher/karcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,18 @@ class KarcherHome:
"""Main class to access Karcher Home Robots API"""

@classmethod
async def create(cls, country: str = 'GB', language: Language = Language.EN):
async def create(cls, country: str = 'GB', language: Language = Language.EN, session: aiohttp.ClientSession = None):
"""Create Karcher Home Robots API instance"""

self = KarcherHome()
self._country = country.upper()
self._base_url = REGION_URLS[get_region_by_country(self._country)]
self._language = language

if session is not None:
self._http_external = True
self._http = session

d = await self.get_urls()
# Update base URLs
if d.app_api != '':
Expand All @@ -62,11 +66,27 @@ def __init__(self):
self._device_props = {}
self._wait_events = {}

def __del__(self):
"""Destructor"""

self.close()

async def close(self):
"""Close underlying connections"""

if self._mqtt is not None:
self._mqtt.disconnect()
self._mqtt = None

if self._http is not None:
if self._http_external:
self._http.close()
self._http = None

async def _request(self, method: str, url: str, **kwargs) -> aiohttp.ClientResponse:
session = aiohttp.ClientSession()
# TODO: Fix SSL
# requests.packages.urllib3.disable_warnings()
# session.skip = False
if self._http is None:
self._http_external = False
self._http = aiohttp.ClientSession()

headers = {}
if kwargs.get('headers') is not None:
Expand Down Expand Up @@ -113,27 +133,32 @@ async def _request(self, method: str, url: str, **kwargs) -> aiohttp.ClientRespo
headers['nonce'] = nonce

kwargs['headers'] = headers
# TODO: Fix SSL
kwargs['verify_ssl'] = False
return await session.request(method, self._base_url + url, **kwargs)
return await self._http.request(method, self._base_url + url, **kwargs)

async def _download(self, url) -> bytes:
session = aiohttp.ClientSession()
headers = {
'User-Agent': 'Android_' + TENANT_ID,
}

resp = await session.get(url, headers=headers)
resp = await self._http.get(url, headers=headers)
if resp.status != 200:
raise KarcherHomeException(-1,
'HTTP error: ' + str(resp.status_code))

return await resp.content.read(-1)
data = await resp.content.read(-1)
resp.close()

return data

async def _process_response(self, resp: aiohttp.ClientResponse, prop=None) -> Any:
if resp.status != 200:
raise KarcherHomeException(-1,
'HTTP error: ' + str(resp.status))
data = await resp.json()
resp.close()

# Check for error response
if data['code'] != 0:
handle_error_code(data['code'], data['msg'])
Expand Down Expand Up @@ -252,9 +277,7 @@ async def logout(self):
'POST', '/user-center/auth/logout'))
self._session = None

if self._mqtt is not None:
self._mqtt.disconnect()
self._mqtt = None
await self.close()

async def get_devices(self) -> List[Device]:
"""Get all user devices."""
Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@
name='karcher-home',
packages=['karcher'],
include_package_data=True,
version='0.4.1',
version='0.4.2',
license='MIT',
description='Kärcher Home Robots client',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
author='Lauris BH',
author_email='[email protected]',
url='https://github.com/lafriks/python-karcher',
download_url='https://github.com/lafriks/python-karcher/releases/download/v0.4.1/karcher-home-0.4.1.tar.gz',
download_url='https://github.com/lafriks/python-karcher/releases/download/v0.4.2/karcher-home-0.4.2.tar.gz',
platforms='any',
install_requires=[
'click',
Expand Down

0 comments on commit 466ceee

Please sign in to comment.