python-kasa/README.md
Teemu R 836f1701b9
Optimize I/O access (#59)
* Optimize I/O access

A single update() will now fetch information from all interesting modules,
including the current device state and the emeter information.

In practice, this will allow dropping the number of I/O reqs per homeassistant update cycle to 1,
which is paramount at least for bulbs which are very picky about sequential accesses.
This can be further extend to other modules/methods, if needed.

Currently fetched data:
* sysinfo
* realtime, today's and this months emeter stats

New properties:
* emeter_realtime: return the most recent emeter information, update()-version of get_emeter_realtime()
* emeter_today: returning today's energy consumption
* emeter_this_month: same for this month

Other changes:
* Accessing @requires_update properties will cause SmartDeviceException if the device has not ever been update()d
* Fix __repr__ for devices that haven't been updated
* Smartbulb uses now the state data from get_sysinfo instead of separately querying the bulb service
* SmartStrip's state_information no longer lists onsince for separate plugs
* The above mentioned properties are now printed out by cli
* Simplify is_on handling for bulbs

* remove implicit updates, return device responses for actions, update README.md instructions. fixes #61
2020-05-24 17:57:54 +02:00

8.0 KiB

python-kasa

PyPI version Build Status Coverage Status

python-kasa is a Python library to control TPLink smart home devices (plugs, wall switches, power strips, and bulbs) using asyncio. This project is a maintainer-made fork of pyHS100 project.

Supported devices

  • Plugs
    • HS100
    • HS103
    • HS105
    • HS107
    • HS110
  • Power Strips
    • HS300
    • KP303
  • Wall switches
    • HS200
    • HS210
    • HS220
  • Bulbs
    • LB100
    • LB110
    • LB120
    • LB130
    • LB230
    • KL60
    • KL110
    • KL120
    • KL130

Contributions (be it adding missing features, fixing bugs or improving documentation) are more than welcome, feel free to submit pull requests! See below for instructions for setting up a development environment.

Usage

The package is shipped with a console tool named kasa, please refer to kasa --help for detailed usage. The device to which the commands are sent is chosen by KASA_HOST environment variable or passing --host <address> as an option. To see what is being sent to and received from the device, specify option --debug.

To avoid discovering the devices when executing commands its type can be passed by specifying either --plug or --bulb, if no type is given its type will be discovered automatically with a small delay. Some commands (such as reading energy meter values and setting color of bulbs) additional parameters are required, which you can find by adding --help after the command, e.g. kasa emeter --help or kasa hsv --help.

If no command is given, the state command will be executed to query the device state.

Initial Setup

You can provision your device without any extra apps by using the kasa wifi command:

  1. If the device is unprovisioned, connect to its open network
  2. Use kasa discover (or check the routes) to locate the IP address of the device (likely 192.168.0.1)
  3. Scan for available networks using kasa wifi scan
  4. Join/change the network using kasa wifi join command, see --help for details.

Discovering devices

The devices can be discovered either by using kasa discover or by calling kasa without any parameters. In both cases supported devices are discovered from the same broadcast domain, and their current state will be queried and printed out.

$ kasa
No --bulb nor --plug given, discovering..
Discovering devices for 3 seconds
== My Smart Plug - HS110(EU) ==
Device state: ON
IP address: 192.168.x.x
LED state: False
On since: 2017-03-26 18:29:17.242219
== Generic information ==
Time:         1970-06-22 02:39:41
Hardware:     1.0
Software:     1.0.8 Build 151101 Rel.24452
MAC (rssi):   50:C7:BF:XX:XX:XX (-77)
Location:     {'latitude': XXXX, 'longitude': XXXX}
== Emeter ==
Current state: {'total': 133.082, 'power': 100.418681, 'current': 0.510967, 'voltage': 225.600477}

Basic controls

All devices support a variety of common commands, including:

  • state which returns state information
  • on and off for turning the device on or off
  • emeter (where applicable) to return energy consumption information
  • sysinfo to return raw system information

Energy meter

Passing no options to emeter command will return the current consumption. Possible options include --year and --month for retrieving historical state, and reseting the counters is done with --erase.

$ kasa emeter
== Emeter ==
Current state: {'total': 133.105, 'power': 108.223577, 'current': 0.54463, 'voltage': 225.296283}

Bulb-specific commands

At the moment setting brightness, color temperature and color (in HSV) are supported depending on the device. The commands are straightforward, so feel free to check --help for instructions how to use them.

Library usage

The property accesses use the data obtained before by awaiting update(). The values are cached until the next update call. In practice this means that property accesses do no I/O and are dependent, while I/O producing methods need to be awaited.

Methods changing the state of the device do not invalidate the cache (i.e., there is no implicit update()). You can assume that the operation has succeeded if no exception is raised. These methods will return the device response, which can be useful for some use cases.

Errors are raised as SmartDeviceException instances for the library user to handle.

Discovering devices

Discover.discover() can be used to discover supported devices in the local network. The return value is a dictionary keyed with the IP address and the value holds a ready-to-use instance of the detected device type.

Example:

import asyncio
from kasa import Discover

devices = asyncio.run(Discover.discover())
for addr, dev in devices.items():
    asyncio.run(dev.update())
    print(f"{addr} >> {dev}")
$ python example.py
<SmartPlug at 192.168.XXX.XXX (My Smart Plug), is_on: True - dev specific: {'LED state': True, 'On since': datetime.datetime(2017, 3, 26, 18, 29, 17, 52073)}>

Querying basic information

import asyncio
from kasa import SmartPlug
from pprint import pformat as pf

plug = SmartPlug("192.168.XXX.XXX")
asyncio.run(plug.update())
print("Hardware: %s" % pf(plug.hw_info))
print("Full sysinfo: %s" % pf(plug.sys_info))

The rest of the examples assume that you have initialized an instance.

State & switching

Devices can be turned on and off by either calling appropriate methods on the device object.

print("Current state: %s" % plug.is_on)
await plug.turn_off()
await plug.turn_on()

Getting emeter status (if applicable)

The update() call will automatically fetch the following emeter information:

  • Current consumption (accessed through emeter_realtime property)
  • Today's consumption (emeter_today)
  • This month's consumption (emeter_this_month)

You can also request this information separately:

print("Current consumption: %s" % await plug.get_emeter_realtime())
print("Per day: %s" % await plug.get_emeter_daily(year=2016, month=12))
print("Per month: %s" % await plug.get_emeter_monthly(year=2016))

Bulb and dimmer-specific APIs

The bulb API is likewise straightforward, so please refer to its API documentation. Information about supported features can be queried by using properties prefixed with is_, e.g. is_dimmable.

Setting the brightness

import asyncio
from kasa import SmartBulb

bulb = SmartBulb("192.168.1.123")
asyncio.run(bulb.update())

if bulb.is_dimmable:
    asyncio.run(bulb.set_brightness(100))
    asyncio.run(bulb.update())
    print(bulb.brightness)

Setting the color temperature

if bulb.is_variable_color_temp:
    await bulb.set_color_temp(3000)
    await bulb.update()
    print(bulb.color_temp)

Setting the color

Hue is given in degrees (0-360) and saturation and value in percentage.

if bulb.is_color:
    await bulb.set_hsv(180, 100, 100) # set to cyan
    await bulb.update()
    print(bulb.hsv)

Contributing

Contributions are very welcome! To simplify the process, we are leveraging automated checks and tests for contributions.

Resources

Setting up development environment

poetry install
pre-commit install

Code-style checks

We use several tools to automatically check all contributions, which are run automatically when you commit your code.

If you want to manually execute the checks, you can run tox -e lint to do the linting checks or tox to also execute the tests.