2019-11-11 21:14:34 +00:00
|
|
|
"""Implementation of the TP-Link Smart Home Protocol.
|
|
|
|
|
|
|
|
Encryption/Decryption methods based on the works of
|
|
|
|
Lubomir Stroetmann and Tobias Esser
|
|
|
|
|
|
|
|
https://www.softscheck.com/en/reverse-engineering-tp-link-hs110/
|
|
|
|
https://github.com/softScheck/tplink-smartplug/
|
|
|
|
|
|
|
|
which are licensed under the Apache License, Version 2.0
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
"""
|
2019-11-11 15:52:13 +00:00
|
|
|
import asyncio
|
2021-09-24 21:25:43 +00:00
|
|
|
import contextlib
|
2022-04-24 17:38:42 +00:00
|
|
|
import errno
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
import logging
|
2019-11-11 18:39:43 +00:00
|
|
|
import struct
|
2023-11-20 13:17:10 +00:00
|
|
|
from abc import ABC, abstractmethod
|
async++, small powerstrip improvements (#46)
* async++, small powerstrip improvements
* use asyncclick instead of click, allows defining the commands with async def to avoid manual eventloop/asyncio.run handling
* improve powerstrip support:
* new powerstrip api: turn_{on,off}_by_{name,index} methods
* cli: fix on/off for powerstrip using the new apis
* add missing update()s for cli's hsv, led, temperature (fixes #43)
* prettyprint the received payloads when debug mode in use
* cli: debug mode can be activated now with '-d'
* update requirements_test.txt
* remove outdated click-datetime, replace click with asyncclick
* debug is a flag
* make smartstripplug to inherit the sysinfo from its parent, allows for simple access of general plug properties
* proper bound checking for index accesses, allow controlling the plug at index 0
* remove the mess of turn_{on,off}_by_{name,index}, get_plug_by_{name,index} are enough.
* adapt cli to use that
* allow changing the alias per index
* use f-strings consistently everywhere in the cli
* add tests for get_plug_by_{index,name}
2020-04-21 18:46:13 +00:00
|
|
|
from pprint import pformat as pf
|
2022-01-14 22:08:25 +00:00
|
|
|
from typing import Dict, Generator, Optional, Union
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
|
2023-07-21 09:50:54 +00:00
|
|
|
# When support for cpython older than 3.11 is dropped
|
|
|
|
# async_timeout can be replaced with asyncio.timeout
|
|
|
|
from async_timeout import timeout as asyncio_timeout
|
|
|
|
|
2023-11-20 13:17:10 +00:00
|
|
|
from .credentials import Credentials
|
2020-05-27 17:02:09 +00:00
|
|
|
from .exceptions import SmartDeviceException
|
2023-06-17 23:03:04 +00:00
|
|
|
from .json import dumps as json_dumps
|
|
|
|
from .json import loads as json_loads
|
2020-05-27 17:02:09 +00:00
|
|
|
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
2022-04-24 17:38:42 +00:00
|
|
|
_NO_RETRY_ERRORS = {errno.EHOSTDOWN, errno.EHOSTUNREACH, errno.ECONNREFUSED}
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
|
|
|
|
|
2023-11-20 13:17:10 +00:00
|
|
|
class TPLinkProtocol(ABC):
|
|
|
|
"""Base class for all TP-Link Smart Home communication."""
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
host: str,
|
|
|
|
*,
|
|
|
|
port: Optional[int] = None,
|
|
|
|
credentials: Optional[Credentials] = None,
|
|
|
|
) -> None:
|
|
|
|
"""Create a protocol object."""
|
|
|
|
self.host = host
|
|
|
|
self.port = port
|
|
|
|
self.credentials = credentials
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
async def query(self, request: Union[str, Dict], retry_count: int = 3) -> Dict:
|
|
|
|
"""Query the device for the protocol. Abstract method to be overriden."""
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
async def close(self) -> None:
|
|
|
|
"""Close the protocol. Abstract method to be overriden."""
|
|
|
|
|
|
|
|
|
|
|
|
class TPLinkSmartHomeProtocol(TPLinkProtocol):
|
2019-11-11 21:14:34 +00:00
|
|
|
"""Implementation of the TP-Link Smart Home protocol."""
|
API and tests cleanup (#151)
* Add new cli commands: raw_command and dump_discover
- raw_command can be used to execute raw commands with given parameters
* Useful for testing new calls before implementing them properly
- dump_discover can be used to dump the device discovery information (into a file)
* The discovery is extended to request more modules and methods from devices
* smartlife.iot.dimmer get_dimmer_parameters
* smartlife.iot.common.emeter get_realtime
* smartlife.iot.smartbulb.lightingservice get_light_state
* This is used to dump more information for proper tests, and will also allow better discovery in the future
This commit contains also some documentation updates and dropping click_datetime in favor of click's built-in datetime
* Docstring fixes
* Major API cleanup
Properties shall no more change the state of the device, this work in still in progress, the main goal being making the API more user-friendly and to make implementing new features simpler.
The newly deprecated functionality will remain working and will simply warn the user about deprecation.
Previously deprecated 'features' property and 'identify' method are now finally removed.
Deprecate and replace the following property setters:
* state with turn_on() and turn_off()
* hsv with set_hsv()
* color_temp with set_color_temp()
* brightness with set_brightness()
* led with set_led()
* alias with set_alias()
* mac with set_mac()
And getters:
* state with is_on and is_off
The {BULB,PLUG}_STATE_{ON,OFF} is simplified to STATE_ON and STATE_OFF, UNKNOWN state is removed.
These are now deprecated and will be removed in the future.
* is_on and is_off can be used to check for the state
* turn_on() and turn_off() for changing the device state.
Trying to use functionality not supported by the device will cause SmartDeviceExceptions instead of failing silently and/or returning None.
This includes, e.g., trying to set a color temperature on non-supported bulb.
ValueErrors are raised instead of SmartDeviceExceptions where appropriate (e.g. when trying to set an invalid hsv or brightness).
New enum type DeviceType is added to allow detecting device types without resorting to isinstance() calling. SmartDevice class' device_type property can be used to query the type. is_plug and is_bulb helpers are added.
* Cleanup tests and improve test coverage
* Make writing tests easier by sharing code for common implementations
* Instead of storing test data inside python files, dump-discover based information is used
* This will simplify adding new tests and remove code duplication
* fixtures are based on https://github.com/plasticrake/tplink-smarthome-simulator
* run black on newfakes
* Add HS300 tests and update SmartStrip API according to earlier changes, still WIP
* run black and avoid wildcard imports
* Black on conftest
* bump minimum required version to 3.5
* Rename fixture_tests to test_fixtures for autocollect
* fix typoed type to _type, black
* run black on several files with -79 to fix hound issues
* Fix broken merge on hue
* Fix tests (hue update, pass context to smartdevice), add is_strip property, disable emeter tests for HS300 until a solution for API is found.
* Fix old tests
* Run black on changed files
* Add real HS220 discovery, thanks to @poiyo
* add is_dimmable and is_variable_color_temp to smartdevice class, simplifies interfacing with homeassistant
* add KL120(US) fixture
* Add a simple query cache
This commit adds a simple query cache to speed up the process for users
requesting lots of different properties from the device, as done by the
cli tool as well as homeassistant.
The logic for caching is very simple:
1. A timestamp for last fetch for each module+command is stored alongside the response.
2. If the issued command starts with `get_` and the TTL has not expired, the cache result is returned.
3. Otherwise the cache for the whole corresponding module gets invalidated, the device will be queried and the result will be stored in the cache.
* add deprecation to tox.ini
* make tests pass again
* remove old tests, add flake8 to tox reqs
* run black against pyhs100 module, add it to precommit hooks, fix flake8 configuration to conform to black standards (https://ljvmiranda921.github.io/notebook/2018/06/21/precommits-using-black-and-flake8/)
* fix syntax
* cleanup conftest
2019-06-16 21:05:00 +00:00
|
|
|
|
2017-01-07 22:44:57 +00:00
|
|
|
INITIALIZATION_VECTOR = 171
|
|
|
|
DEFAULT_PORT = 9999
|
|
|
|
DEFAULT_TIMEOUT = 5
|
2021-09-24 21:25:43 +00:00
|
|
|
BLOCK_SIZE = 4
|
|
|
|
|
2023-10-07 18:58:00 +00:00
|
|
|
def __init__(
|
2023-11-20 13:17:10 +00:00
|
|
|
self,
|
|
|
|
host: str,
|
|
|
|
*,
|
|
|
|
port: Optional[int] = None,
|
|
|
|
timeout: Optional[int] = None,
|
|
|
|
credentials: Optional[Credentials] = None,
|
2023-10-07 18:58:00 +00:00
|
|
|
) -> None:
|
2021-09-24 21:25:43 +00:00
|
|
|
"""Create a protocol object."""
|
2023-11-20 13:17:10 +00:00
|
|
|
super().__init__(
|
|
|
|
host=host, port=port or self.DEFAULT_PORT, credentials=credentials
|
|
|
|
)
|
|
|
|
|
2021-09-24 21:25:43 +00:00
|
|
|
self.reader: Optional[asyncio.StreamReader] = None
|
|
|
|
self.writer: Optional[asyncio.StreamWriter] = None
|
2023-10-07 22:36:51 +00:00
|
|
|
self.query_lock = asyncio.Lock()
|
2021-09-24 21:25:43 +00:00
|
|
|
self.loop: Optional[asyncio.AbstractEventLoop] = None
|
2023-10-07 18:58:00 +00:00
|
|
|
self.timeout = timeout or TPLinkSmartHomeProtocol.DEFAULT_TIMEOUT
|
2021-09-24 21:25:43 +00:00
|
|
|
|
|
|
|
async def query(self, request: Union[str, Dict], retry_count: int = 3) -> Dict:
|
API and tests cleanup (#151)
* Add new cli commands: raw_command and dump_discover
- raw_command can be used to execute raw commands with given parameters
* Useful for testing new calls before implementing them properly
- dump_discover can be used to dump the device discovery information (into a file)
* The discovery is extended to request more modules and methods from devices
* smartlife.iot.dimmer get_dimmer_parameters
* smartlife.iot.common.emeter get_realtime
* smartlife.iot.smartbulb.lightingservice get_light_state
* This is used to dump more information for proper tests, and will also allow better discovery in the future
This commit contains also some documentation updates and dropping click_datetime in favor of click's built-in datetime
* Docstring fixes
* Major API cleanup
Properties shall no more change the state of the device, this work in still in progress, the main goal being making the API more user-friendly and to make implementing new features simpler.
The newly deprecated functionality will remain working and will simply warn the user about deprecation.
Previously deprecated 'features' property and 'identify' method are now finally removed.
Deprecate and replace the following property setters:
* state with turn_on() and turn_off()
* hsv with set_hsv()
* color_temp with set_color_temp()
* brightness with set_brightness()
* led with set_led()
* alias with set_alias()
* mac with set_mac()
And getters:
* state with is_on and is_off
The {BULB,PLUG}_STATE_{ON,OFF} is simplified to STATE_ON and STATE_OFF, UNKNOWN state is removed.
These are now deprecated and will be removed in the future.
* is_on and is_off can be used to check for the state
* turn_on() and turn_off() for changing the device state.
Trying to use functionality not supported by the device will cause SmartDeviceExceptions instead of failing silently and/or returning None.
This includes, e.g., trying to set a color temperature on non-supported bulb.
ValueErrors are raised instead of SmartDeviceExceptions where appropriate (e.g. when trying to set an invalid hsv or brightness).
New enum type DeviceType is added to allow detecting device types without resorting to isinstance() calling. SmartDevice class' device_type property can be used to query the type. is_plug and is_bulb helpers are added.
* Cleanup tests and improve test coverage
* Make writing tests easier by sharing code for common implementations
* Instead of storing test data inside python files, dump-discover based information is used
* This will simplify adding new tests and remove code duplication
* fixtures are based on https://github.com/plasticrake/tplink-smarthome-simulator
* run black on newfakes
* Add HS300 tests and update SmartStrip API according to earlier changes, still WIP
* run black and avoid wildcard imports
* Black on conftest
* bump minimum required version to 3.5
* Rename fixture_tests to test_fixtures for autocollect
* fix typoed type to _type, black
* run black on several files with -79 to fix hound issues
* Fix broken merge on hue
* Fix tests (hue update, pass context to smartdevice), add is_strip property, disable emeter tests for HS300 until a solution for API is found.
* Fix old tests
* Run black on changed files
* Add real HS220 discovery, thanks to @poiyo
* add is_dimmable and is_variable_color_temp to smartdevice class, simplifies interfacing with homeassistant
* add KL120(US) fixture
* Add a simple query cache
This commit adds a simple query cache to speed up the process for users
requesting lots of different properties from the device, as done by the
cli tool as well as homeassistant.
The logic for caching is very simple:
1. A timestamp for last fetch for each module+command is stored alongside the response.
2. If the issued command starts with `get_` and the TTL has not expired, the cache result is returned.
3. Otherwise the cache for the whole corresponding module gets invalidated, the device will be queried and the result will be stored in the cache.
* add deprecation to tox.ini
* make tests pass again
* remove old tests, add flake8 to tox reqs
* run black against pyhs100 module, add it to precommit hooks, fix flake8 configuration to conform to black standards (https://ljvmiranda921.github.io/notebook/2018/06/21/precommits-using-black-and-flake8/)
* fix syntax
* cleanup conftest
2019-06-16 21:05:00 +00:00
|
|
|
"""Request information from a TP-Link SmartHome Device.
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
|
2018-01-17 21:03:19 +00:00
|
|
|
:param str host: host name or ip address of the device
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
:param request: command to send to the device (can be either dict or
|
|
|
|
json string)
|
2020-05-27 17:02:09 +00:00
|
|
|
:param retry_count: how many retries to do in case of failure
|
API and tests cleanup (#151)
* Add new cli commands: raw_command and dump_discover
- raw_command can be used to execute raw commands with given parameters
* Useful for testing new calls before implementing them properly
- dump_discover can be used to dump the device discovery information (into a file)
* The discovery is extended to request more modules and methods from devices
* smartlife.iot.dimmer get_dimmer_parameters
* smartlife.iot.common.emeter get_realtime
* smartlife.iot.smartbulb.lightingservice get_light_state
* This is used to dump more information for proper tests, and will also allow better discovery in the future
This commit contains also some documentation updates and dropping click_datetime in favor of click's built-in datetime
* Docstring fixes
* Major API cleanup
Properties shall no more change the state of the device, this work in still in progress, the main goal being making the API more user-friendly and to make implementing new features simpler.
The newly deprecated functionality will remain working and will simply warn the user about deprecation.
Previously deprecated 'features' property and 'identify' method are now finally removed.
Deprecate and replace the following property setters:
* state with turn_on() and turn_off()
* hsv with set_hsv()
* color_temp with set_color_temp()
* brightness with set_brightness()
* led with set_led()
* alias with set_alias()
* mac with set_mac()
And getters:
* state with is_on and is_off
The {BULB,PLUG}_STATE_{ON,OFF} is simplified to STATE_ON and STATE_OFF, UNKNOWN state is removed.
These are now deprecated and will be removed in the future.
* is_on and is_off can be used to check for the state
* turn_on() and turn_off() for changing the device state.
Trying to use functionality not supported by the device will cause SmartDeviceExceptions instead of failing silently and/or returning None.
This includes, e.g., trying to set a color temperature on non-supported bulb.
ValueErrors are raised instead of SmartDeviceExceptions where appropriate (e.g. when trying to set an invalid hsv or brightness).
New enum type DeviceType is added to allow detecting device types without resorting to isinstance() calling. SmartDevice class' device_type property can be used to query the type. is_plug and is_bulb helpers are added.
* Cleanup tests and improve test coverage
* Make writing tests easier by sharing code for common implementations
* Instead of storing test data inside python files, dump-discover based information is used
* This will simplify adding new tests and remove code duplication
* fixtures are based on https://github.com/plasticrake/tplink-smarthome-simulator
* run black on newfakes
* Add HS300 tests and update SmartStrip API according to earlier changes, still WIP
* run black and avoid wildcard imports
* Black on conftest
* bump minimum required version to 3.5
* Rename fixture_tests to test_fixtures for autocollect
* fix typoed type to _type, black
* run black on several files with -79 to fix hound issues
* Fix broken merge on hue
* Fix tests (hue update, pass context to smartdevice), add is_strip property, disable emeter tests for HS300 until a solution for API is found.
* Fix old tests
* Run black on changed files
* Add real HS220 discovery, thanks to @poiyo
* add is_dimmable and is_variable_color_temp to smartdevice class, simplifies interfacing with homeassistant
* add KL120(US) fixture
* Add a simple query cache
This commit adds a simple query cache to speed up the process for users
requesting lots of different properties from the device, as done by the
cli tool as well as homeassistant.
The logic for caching is very simple:
1. A timestamp for last fetch for each module+command is stored alongside the response.
2. If the issued command starts with `get_` and the TTL has not expired, the cache result is returned.
3. Otherwise the cache for the whole corresponding module gets invalidated, the device will be queried and the result will be stored in the cache.
* add deprecation to tox.ini
* make tests pass again
* remove old tests, add flake8 to tox reqs
* run black against pyhs100 module, add it to precommit hooks, fix flake8 configuration to conform to black standards (https://ljvmiranda921.github.io/notebook/2018/06/21/precommits-using-black-and-flake8/)
* fix syntax
* cleanup conftest
2019-06-16 21:05:00 +00:00
|
|
|
:return: response dict
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
"""
|
|
|
|
if isinstance(request, dict):
|
2023-06-17 23:03:04 +00:00
|
|
|
request = json_dumps(request)
|
2023-10-29 22:15:42 +00:00
|
|
|
assert isinstance(request, str) # noqa: S101
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
|
2021-09-24 21:25:43 +00:00
|
|
|
async with self.query_lock:
|
2023-10-07 18:58:00 +00:00
|
|
|
return await self._query(request, retry_count, self.timeout)
|
2021-09-24 21:25:43 +00:00
|
|
|
|
2022-04-05 16:16:36 +00:00
|
|
|
async def _connect(self, timeout: int) -> None:
|
2021-09-24 21:25:43 +00:00
|
|
|
"""Try to connect or reconnect to the device."""
|
|
|
|
if self.writer:
|
2022-04-05 16:16:36 +00:00
|
|
|
return
|
|
|
|
self.reader = self.writer = None
|
2023-07-21 09:50:54 +00:00
|
|
|
|
2023-07-09 23:55:27 +00:00
|
|
|
task = asyncio.open_connection(self.host, self.port)
|
2023-07-21 09:50:54 +00:00
|
|
|
async with asyncio_timeout(timeout):
|
|
|
|
self.reader, self.writer = await task
|
2021-09-24 21:25:43 +00:00
|
|
|
|
|
|
|
async def _execute_query(self, request: str) -> Dict:
|
|
|
|
"""Execute a query on the device and wait for the response."""
|
2023-10-29 22:15:42 +00:00
|
|
|
assert self.writer is not None # noqa: S101
|
|
|
|
assert self.reader is not None # noqa: S101
|
2021-09-26 14:50:58 +00:00
|
|
|
debug_log = _LOGGER.isEnabledFor(logging.DEBUG)
|
2021-09-24 21:25:43 +00:00
|
|
|
|
2021-09-26 14:50:58 +00:00
|
|
|
if debug_log:
|
2021-09-26 17:16:12 +00:00
|
|
|
_LOGGER.debug("%s >> %s", self.host, request)
|
2021-09-24 21:25:43 +00:00
|
|
|
self.writer.write(TPLinkSmartHomeProtocol.encrypt(request))
|
|
|
|
await self.writer.drain()
|
|
|
|
|
|
|
|
packed_block_size = await self.reader.readexactly(self.BLOCK_SIZE)
|
|
|
|
length = struct.unpack(">I", packed_block_size)[0]
|
|
|
|
|
|
|
|
buffer = await self.reader.readexactly(length)
|
|
|
|
response = TPLinkSmartHomeProtocol.decrypt(buffer)
|
2023-06-17 23:03:04 +00:00
|
|
|
json_payload = json_loads(response)
|
2021-09-26 14:50:58 +00:00
|
|
|
if debug_log:
|
2021-09-26 17:16:12 +00:00
|
|
|
_LOGGER.debug("%s << %s", self.host, pf(json_payload))
|
|
|
|
|
2021-09-24 21:25:43 +00:00
|
|
|
return json_payload
|
|
|
|
|
2022-01-14 22:08:25 +00:00
|
|
|
async def close(self) -> None:
|
2021-09-24 21:25:43 +00:00
|
|
|
"""Close the connection."""
|
|
|
|
writer = self.writer
|
2021-09-26 17:38:33 +00:00
|
|
|
self.reader = self.writer = None
|
2021-09-24 21:25:43 +00:00
|
|
|
if writer:
|
|
|
|
writer.close()
|
|
|
|
with contextlib.suppress(Exception):
|
|
|
|
await writer.wait_closed()
|
|
|
|
|
2022-01-14 22:08:25 +00:00
|
|
|
def _reset(self) -> None:
|
2021-09-24 21:25:43 +00:00
|
|
|
"""Clear any varibles that should not survive between loops."""
|
2023-10-07 22:36:51 +00:00
|
|
|
self.reader = self.writer = None
|
2021-09-24 21:25:43 +00:00
|
|
|
|
|
|
|
async def _query(self, request: str, retry_count: int, timeout: int) -> Dict:
|
|
|
|
"""Try to query a device."""
|
2022-04-24 17:38:42 +00:00
|
|
|
#
|
|
|
|
# Most of the time we will already be connected if the device is online
|
|
|
|
# and the connect call will do nothing and return right away
|
|
|
|
#
|
2023-10-29 22:15:42 +00:00
|
|
|
# However, if we get an unrecoverable error (_NO_RETRY_ERRORS and
|
|
|
|
# ConnectionRefusedError) we do not want to keep trying since many
|
|
|
|
# connection open/close operations in the same time frame can block
|
|
|
|
# the event loop.
|
|
|
|
# This is especially import when there are multiple tplink devices being polled.
|
2020-05-27 17:02:09 +00:00
|
|
|
for retry in range(retry_count + 1):
|
2022-04-05 16:16:36 +00:00
|
|
|
try:
|
|
|
|
await self._connect(timeout)
|
2022-04-24 17:38:42 +00:00
|
|
|
except ConnectionRefusedError as ex:
|
|
|
|
await self.close()
|
|
|
|
raise SmartDeviceException(
|
2023-07-09 23:55:27 +00:00
|
|
|
f"Unable to connect to the device: {self.host}:{self.port}: {ex}"
|
2023-10-29 22:15:42 +00:00
|
|
|
) from ex
|
2022-04-24 17:38:42 +00:00
|
|
|
except OSError as ex:
|
|
|
|
await self.close()
|
|
|
|
if ex.errno in _NO_RETRY_ERRORS or retry >= retry_count:
|
|
|
|
raise SmartDeviceException(
|
2023-10-29 22:15:42 +00:00
|
|
|
f"Unable to connect to the device:"
|
|
|
|
f" {self.host}:{self.port}: {ex}"
|
|
|
|
) from ex
|
2022-04-24 17:38:42 +00:00
|
|
|
continue
|
2022-04-05 16:16:36 +00:00
|
|
|
except Exception as ex:
|
2021-09-24 21:25:43 +00:00
|
|
|
await self.close()
|
|
|
|
if retry >= retry_count:
|
2021-09-26 17:16:12 +00:00
|
|
|
_LOGGER.debug("Giving up on %s after %s retries", self.host, retry)
|
2021-09-24 21:25:43 +00:00
|
|
|
raise SmartDeviceException(
|
2023-10-29 22:15:42 +00:00
|
|
|
f"Unable to connect to the device:"
|
|
|
|
f" {self.host}:{self.port}: {ex}"
|
|
|
|
) from ex
|
2021-09-24 21:25:43 +00:00
|
|
|
continue
|
|
|
|
|
2020-05-27 17:02:09 +00:00
|
|
|
try:
|
2023-10-29 22:15:42 +00:00
|
|
|
assert self.reader is not None # noqa: S101
|
|
|
|
assert self.writer is not None # noqa: S101
|
2023-07-21 09:50:54 +00:00
|
|
|
async with asyncio_timeout(timeout):
|
|
|
|
return await self._execute_query(request)
|
2020-05-27 17:02:09 +00:00
|
|
|
except Exception as ex:
|
2021-09-24 21:25:43 +00:00
|
|
|
await self.close()
|
2020-05-27 17:02:09 +00:00
|
|
|
if retry >= retry_count:
|
2021-09-26 17:16:12 +00:00
|
|
|
_LOGGER.debug("Giving up on %s after %s retries", self.host, retry)
|
2020-05-27 17:02:09 +00:00
|
|
|
raise SmartDeviceException(
|
2023-07-09 23:55:27 +00:00
|
|
|
f"Unable to query the device {self.host}:{self.port}: {ex}"
|
2020-05-27 17:02:09 +00:00
|
|
|
) from ex
|
|
|
|
|
2021-09-26 17:16:12 +00:00
|
|
|
_LOGGER.debug(
|
|
|
|
"Unable to query the device %s, retrying: %s", self.host, ex
|
|
|
|
)
|
2020-05-27 17:02:09 +00:00
|
|
|
|
|
|
|
# make mypy happy, this should never be reached..
|
2021-09-24 21:25:43 +00:00
|
|
|
await self.close()
|
2020-05-27 17:02:09 +00:00
|
|
|
raise SmartDeviceException("Query reached somehow to unreachable")
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
|
2022-01-14 22:08:25 +00:00
|
|
|
def __del__(self) -> None:
|
2021-09-24 21:25:43 +00:00
|
|
|
if self.writer and self.loop and self.loop.is_running():
|
Fix unsafe __del__ in TPLinkSmartHomeProtocol (#300)
* Fix unsafe __del__ in TPLinkSmartHomeProtocol
Fixes
```
Exception ignored in: <function TPLinkSmartHomeProtocol.__del__ at 0x1096d0670>
Traceback (most recent call last):
File "/Users/bdraco/home-assistant/venv/lib/python3.9/site-packages/kasa/protocol.py", line 159, in __del__
self.writer.close()
File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/streams.py", line 353, in close
return self._transport.close()
File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/selector_events.py", line 700, in close
self._loop.call_soon(self._call_connection_lost, None)
File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 748, in call_soon
self._check_thread()
File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 785, in _check_thread
raise RuntimeError(
RuntimeError: Non-thread-safe operation invoked on an event loop other than the current one
```
* comment
* comment
* comment
2022-01-30 22:00:00 +00:00
|
|
|
# Since __del__ will be called when python does
|
|
|
|
# garbage collection is can happen in the event loop thread
|
|
|
|
# or in another thread so we need to make sure the call to
|
|
|
|
# close is called safely with call_soon_threadsafe
|
|
|
|
self.loop.call_soon_threadsafe(self.writer.close)
|
2021-09-24 21:25:43 +00:00
|
|
|
self._reset()
|
|
|
|
|
2021-09-23 16:11:16 +00:00
|
|
|
@staticmethod
|
2022-01-14 22:08:25 +00:00
|
|
|
def _xor_payload(unencrypted: bytes) -> Generator[int, None, None]:
|
2021-09-23 16:11:16 +00:00
|
|
|
key = TPLinkSmartHomeProtocol.INITIALIZATION_VECTOR
|
|
|
|
for unencryptedbyte in unencrypted:
|
|
|
|
key = key ^ unencryptedbyte
|
|
|
|
yield key
|
|
|
|
|
2017-01-07 22:44:57 +00:00
|
|
|
@staticmethod
|
2019-11-11 21:14:34 +00:00
|
|
|
def encrypt(request: str) -> bytes:
|
2020-05-27 14:55:18 +00:00
|
|
|
"""Encrypt a request for a TP-Link Smart Home Device.
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
|
|
|
|
:param request: plaintext request data
|
2020-05-27 14:55:18 +00:00
|
|
|
:return: ciphertext to be send over wire, in bytes
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
"""
|
2018-08-08 14:52:03 +00:00
|
|
|
plainbytes = request.encode()
|
2021-09-23 16:11:16 +00:00
|
|
|
return struct.pack(">I", len(plainbytes)) + bytes(
|
|
|
|
TPLinkSmartHomeProtocol._xor_payload(plainbytes)
|
|
|
|
)
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
|
2021-09-23 16:11:16 +00:00
|
|
|
@staticmethod
|
2022-01-14 22:08:25 +00:00
|
|
|
def _xor_encrypted_payload(ciphertext: bytes) -> Generator[int, None, None]:
|
2021-09-23 16:11:16 +00:00
|
|
|
key = TPLinkSmartHomeProtocol.INITIALIZATION_VECTOR
|
|
|
|
for cipherbyte in ciphertext:
|
|
|
|
plainbyte = key ^ cipherbyte
|
2018-08-08 14:52:03 +00:00
|
|
|
key = cipherbyte
|
2021-09-23 16:11:16 +00:00
|
|
|
yield plainbyte
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2017-09-18 16:13:06 +00:00
|
|
|
def decrypt(ciphertext: bytes) -> str:
|
2020-05-27 14:55:18 +00:00
|
|
|
"""Decrypt a response of a TP-Link Smart Home Device.
|
Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35 (#17)
* Refactor & add unittests for almost all functionality, add tox for running tests on py27 and py35
This commit adds unit tests for current api functionality.
- currently no mocking, all tests are run on the device.
- the library is now compatible with python 2.7 and python 3.5, use tox for tests
- schema checks are done with voluptuous
refactoring:
- protocol is separated into its own file, smartplug adapted to receive protocol worker as parameter.
- cleaned up the initialization routine, initialization is done on use, not on creation of smartplug
- added model and features properties, identity kept for backwards compatibility
- no more storing of local variables outside _sys_info, paves a way to handle state changes sanely (without complete reinitialization)
* Fix CI warnings, remove unused leftover code
* Rename _initialize to _fetch_sysinfo, as that's what it does.
* examples.cli: fix identify call, prettyprint sysinfo, update readme which had false format for led setting
* Add tox-travis for automated testing.
2016-12-16 22:51:56 +00:00
|
|
|
|
|
|
|
:param ciphertext: encrypted response data
|
|
|
|
:return: plaintext response
|
|
|
|
"""
|
2021-09-23 16:11:16 +00:00
|
|
|
return bytes(
|
|
|
|
TPLinkSmartHomeProtocol._xor_encrypted_payload(ciphertext)
|
|
|
|
).decode()
|
2023-06-30 00:43:01 +00:00
|
|
|
|
|
|
|
|
|
|
|
# Try to load the kasa_crypt module and if it is available
|
|
|
|
try:
|
|
|
|
from kasa_crypt import decrypt, encrypt
|
|
|
|
|
|
|
|
TPLinkSmartHomeProtocol.decrypt = decrypt # type: ignore[method-assign]
|
|
|
|
TPLinkSmartHomeProtocol.encrypt = encrypt # type: ignore[method-assign]
|
|
|
|
except ImportError:
|
|
|
|
pass
|