Discovering devices

Discovery

Discovery works by sending broadcast UDP packets to two known TP-link discovery ports, 9999 and 20002. Port 9999 is used for legacy devices that do not use strong encryption and 20002 is for newer devices that use different levels of encryption. If a device uses port 20002 for discovery you will obtain some basic information from the device via discovery, but you will need to await SmartDevice.update() to get full device information. Credentials will most likely be required for port 20002 devices although if the device has never been connected to the tplink cloud it may work without credentials.

To query or update the device requires authentication via Credentials and if this is invalid or not provided it will raise an AuthenticationException.

If discovery encounters an unsupported device when calling via Discover.discover_single() it will raise a UnsupportedDeviceException. If discovery encounters a device when calling Discover.discover(), you can provide a callback to the on_unsupported parameter to handle these.

Example:

import asyncio
from kasa import Discover, Credentials

async def main():
    device = await Discover.discover_single(
        "127.0.0.1",
        credentials=Credentials("myusername", "mypassword"),
        discovery_timeout=10
    )

    await device.update()  # Request the update
    print(device.alias)  # Print out the alias

    devices = await Discover.discover(
        credentials=Credentials("myusername", "mypassword"),
        discovery_timeout=10
    )
    for ip, device in devices.items():
        await device.update()
        print(device.alias)

if __name__ == "__main__":
    asyncio.run(main())

API documentation

class kasa.Discover[source]

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 DeviceConfig of the device is already known, you can initialize the corresponding device class directly without discovery.

The protocol uses UDP broadcast datagrams on port 9999 and 20002 for discovery. Legacy devices support discovery on port 9999 and newer devices on 20002.

Newer devices that respond on port 20002 will most likely require TP-Link cloud credentials to be passed if queries or updates are to be performed on the returned devices.

Examples:

Discovery returns a list of discovered devices:

>>> import asyncio
>>> found_devices = asyncio.run(Discover.discover())
>>> [dev.alias for dev in found_devices]
['TP-LINK_Power Strip_CF69']

Discovery can also be targeted to a specific broadcast address instead of the default 255.255.255.255:

>>> asyncio.run(Discover.discover(target="192.168.8.255"))

It is also possible to pass a coroutine to be executed for each found device:

>>> async def print_alias(dev):
>>>    print(f"Discovered {dev.alias}")
>>> devices = asyncio.run(Discover.discover(on_discovered=print_alias))
DISCOVERY_PORT = 9999
DISCOVERY_PORT_2 = 20002
DISCOVERY_QUERY = {'system': {'get_sysinfo': None}}
DISCOVERY_QUERY_2 = b'\x02\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00F<\xb5\xd3'
async static discover(*, target='255.255.255.255', on_discovered=None, discovery_timeout=5, discovery_packets=3, interface=None, on_unsupported=None, credentials=None, port=None, timeout=None) Dict[str, Device][source]

Discover supported devices.

Sends discovery message to 255.255.255.255:9999 and 255.255.255.255:20002 in order to detect available supported devices in the local network, and waits for given timeout for answers from devices. If you have multiple interfaces, you can use target parameter to specify the network for discovery.

If given, on_discovered coroutine will get awaited with a SmartDevice-derived object as parameter.

The results of the discovery are returned as a dict of SmartDevice-derived objects keyed with IP addresses. The devices are already initialized and all but emeter-related properties can be accessed directly.

Parameters:
  • target – The target address where to send the broadcast discovery queries if multi-homing (e.g. 192.168.xxx.255).

  • on_discovered – coroutine to execute on discovery

  • discovery_timeout – Seconds to wait for responses, defaults to 5

  • discovery_packets – Number of discovery packets to broadcast

  • interface – Bind to specific interface

  • on_unsupported – Optional callback when unsupported devices are discovered

  • credentials – Credentials for devices requiring authentication

  • port – Override the discovery port for devices listening on 9999

  • timeout – Query timeout in seconds for devices returned by discovery

Returns:

dictionary with discovered devices

async static discover_single(host: str, *, discovery_timeout: int = 5, port: Optional[int] = None, timeout: Optional[int] = None, credentials: Optional[Credentials] = None) Device[source]

Discover a single device by the given IP address.

It is generally preferred to avoid discover_single() and use SmartDevice.connect() instead as it should perform better when the WiFi network is congested or the device is not responding to discovery requests.

Parameters:
  • host – Hostname of device to query

  • discovery_timeout – Timeout in seconds for discovery

  • port – Optionally set a different port for legacy devices using port 9999

  • timeout – Timeout in seconds device for devices queries

  • credentials – Credentials for devices that require authentication

Return type:

SmartDevice

Returns:

Object for querying/controlling found device.