mirror of
https://github.com/python-kasa/python-kasa.git
synced 2024-12-23 03:33:35 +00:00
2d60467bea
* 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
144 lines
4.8 KiB
Python
Executable File
144 lines
4.8 KiB
Python
Executable File
import socket
|
|
import logging
|
|
import json
|
|
from typing import Dict, Type, Optional
|
|
|
|
from pyHS100 import (
|
|
TPLinkSmartHomeProtocol,
|
|
SmartDevice,
|
|
SmartPlug,
|
|
SmartBulb,
|
|
SmartStrip,
|
|
SmartDeviceException,
|
|
)
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
class Discover:
|
|
"""Discover TPLink Smart Home devices.
|
|
|
|
The main entry point for this library is Discover.discover(),
|
|
which returns a dictionary of the found devices. The key is the IP address
|
|
of the device and the value contains ready-to-use, SmartDevice-derived
|
|
device object.
|
|
|
|
discover_single() can be used to initialize a single device given its
|
|
IP address. If the type of the device and its IP address is already known,
|
|
you can initialize the corresponding device class directly without this.
|
|
|
|
The protocol uses UDP broadcast datagrams on port 9999 for discovery.
|
|
|
|
|
|
"""
|
|
|
|
DISCOVERY_QUERY = {
|
|
"system": {"get_sysinfo": None},
|
|
"emeter": {"get_realtime": None},
|
|
"smartlife.iot.dimmer": {"get_dimmer_parameters": None},
|
|
"smartlife.iot.common.emeter": {"get_realtime": None},
|
|
"smartlife.iot.smartbulb.lightingservice": {"get_light_state": None},
|
|
}
|
|
|
|
@staticmethod
|
|
def discover(
|
|
protocol: TPLinkSmartHomeProtocol = None,
|
|
port: int = 9999,
|
|
timeout: int = 3,
|
|
discovery_packets=3,
|
|
return_raw=False,
|
|
) -> Dict[str, SmartDevice]:
|
|
|
|
"""
|
|
Sends discovery message to 255.255.255.255:9999 in order
|
|
to detect available supported devices in the local network,
|
|
and waits for given timeout for answers from devices.
|
|
|
|
:param protocol: Protocol implementation to use
|
|
:param timeout: How long to wait for responses, defaults to 3
|
|
:param port: port to send broadcast messages, defaults to 9999.
|
|
:rtype: dict
|
|
:return: Array of json objects {"ip", "port", "sys_info"}
|
|
"""
|
|
if protocol is None:
|
|
protocol = TPLinkSmartHomeProtocol()
|
|
|
|
target = "255.255.255.255"
|
|
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
sock.settimeout(timeout)
|
|
|
|
req = json.dumps(Discover.DISCOVERY_QUERY)
|
|
_LOGGER.debug("Sending discovery to %s:%s", target, port)
|
|
|
|
encrypted_req = protocol.encrypt(req)
|
|
for i in range(discovery_packets):
|
|
sock.sendto(encrypted_req[4:], (target, port))
|
|
|
|
devices = {}
|
|
_LOGGER.debug("Waiting %s seconds for responses...", timeout)
|
|
|
|
try:
|
|
while True:
|
|
data, addr = sock.recvfrom(4096)
|
|
ip, port = addr
|
|
info = json.loads(protocol.decrypt(data))
|
|
device_class = Discover._get_device_class(info)
|
|
if return_raw:
|
|
devices[ip] = info
|
|
elif device_class is not None:
|
|
devices[ip] = device_class(ip)
|
|
except socket.timeout:
|
|
_LOGGER.debug("Got socket timeout, which is okay.")
|
|
except Exception as ex:
|
|
_LOGGER.error("Got exception %s", ex, exc_info=True)
|
|
_LOGGER.debug("Found %s devices: %s", len(devices), devices)
|
|
return devices
|
|
|
|
@staticmethod
|
|
def discover_single(
|
|
host: str, protocol: TPLinkSmartHomeProtocol = None
|
|
) -> Optional[SmartDevice]:
|
|
"""Discover a single device by the given IP address.
|
|
|
|
:param host: Hostname of device to query
|
|
:param protocol: Protocol implementation to use
|
|
:rtype: SmartDevice
|
|
:return: Object for querying/controlling found device.
|
|
"""
|
|
if protocol is None:
|
|
protocol = TPLinkSmartHomeProtocol()
|
|
|
|
info = protocol.query(host, Discover.DISCOVERY_QUERY)
|
|
|
|
device_class = Discover._get_device_class(info)
|
|
if device_class is not None:
|
|
return device_class(host)
|
|
|
|
return None
|
|
|
|
@staticmethod
|
|
def _get_device_class(info: dict) -> Optional[Type[SmartDevice]]:
|
|
"""Find SmartDevice subclass for device described by passed data."""
|
|
if "system" in info and "get_sysinfo" in info["system"]:
|
|
sysinfo = info["system"]["get_sysinfo"]
|
|
if "type" in sysinfo:
|
|
type_ = sysinfo["type"]
|
|
elif "mic_type" in sysinfo:
|
|
type_ = sysinfo["mic_type"]
|
|
else:
|
|
raise SmartDeviceException("Unable to find the device type field!")
|
|
else:
|
|
raise SmartDeviceException("No 'system' nor 'get_sysinfo' in response")
|
|
|
|
if "smartplug" in type_.lower() and "children" in sysinfo:
|
|
return SmartStrip
|
|
elif "smartplug" in type_.lower():
|
|
return SmartPlug
|
|
elif "smartbulb" in type_.lower():
|
|
return SmartBulb
|
|
|
|
return None
|