🏠🤖 Python API for TP-Link smarthome products
Go to file
Teemu R 2d60467bea
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 17:05:00 -04:00
pyHS100 API and tests cleanup (#151) 2019-06-16 17:05:00 -04:00
.flake8 API and tests cleanup (#151) 2019-06-16 17:05:00 -04:00
.gitchangelog.rc Add changelog & add .gitchangelog.rc (#28) 2017-03-17 14:38:58 +01:00
.gitignore Local test clean (#96) 2017-10-07 17:44:45 +02:00
.hound.yml API and tests cleanup (#151) 2019-06-16 17:05:00 -04:00
.pre-commit-config.yaml API and tests cleanup (#151) 2019-06-16 17:05:00 -04:00
.travis.yml API and tests cleanup (#151) 2019-06-16 17:05:00 -04:00
CHANGELOG Prepare 0.3.5 (#170) 2019-04-13 01:12:37 -04:00
Dockerfile created a docker file to aid dev setup (#99) 2017-10-13 23:27:05 +02:00
HOWTO_RELEASE Release 0.2.4 preparations (#43) 2017-03-25 23:04:32 +01:00
LICENSE Update LICENSE 2016-10-18 09:40:42 +08:00
README.md Add LB230 2019-01-22 13:23:27 +01:00
requirements.txt API and tests cleanup (#151) 2019-06-16 17:05:00 -04:00
setup.py API and tests cleanup (#151) 2019-06-16 17:05:00 -04:00
tox.ini API and tests cleanup (#151) 2019-06-16 17:05:00 -04:00

pyHS100

PyPI version Build Status Coverage Status Reviewed by Hound

Python Library to control TPLink smart plugs/switches and smart bulbs.

Supported devices

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

Usage

The package is shipped with a console tool named pyhs100, please refer to pyhs100 --help for detailed usage. The device to which the commands are sent is chosen by PYHS100_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. pyhs100 emeter --help or pyhs100 hsv --help.

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

Discovering devices

The devices can be discovered either by using pyhs100 discover or by calling pyhs100 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.

$ pyhs100
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 which is used by e.g. state, useful for debugging and when adding support for new device types

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.

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

Plug-specific commands

At the moment only switching the state of the LED is implemented. Feel free to submit patches as pull requests for further features!

Controlling the LED

led command can be used to control whether the LED light on front of the plug is on or off.

$ pyhs100 --plug led
LED state: False
$ pyhs100 --plug led 1
Turning led to True

Bulb-specific commands

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

Feel free to submit patches as pull requests to add more functionality (e.g. scenes)!

Library usage

The public API is well documented, but here are some examples to get you started. For all available API functions run help(SmartPlug) or help(SmartBulb).

Discovering devices

Discover class' discover() can be used to discover supported devices, which returns a dictionary keyed with the IP address whose value hold a ready-to-use instance of the detected device type.

Example:

from pyHS100 import Discover

for dev in Discover.discover().values():
    print(dev)
$ python3 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

Please note that most property getters do I/O (e.g. fetching the system information) on each call. If you want to avoid unnecessary communication with the device please use get_sysinfo and handle parsing of information by yourself.

from pyHS100 import SmartPlug, SmartBulb
from pprint import pformat as pf

plug = SmartPlug("192.168.XXX.XXX")
print("Hardware: %s" % pf(plug.hw_info))
print("Full sysinfo: %s" % pf(plug.get_sysinfo())) # this prints lots of information about the device

State & switching

Devices can be turned on and off by either calling appropriate methods on the device object, or by assigning a new state to state property.

print("Current state: %s" % plug.state)
plug.turn_off()
plug.turn_on()
plug.state = "ON"
plug.state = "OFF"

Time information

print("Current time: %s" % plug.time)
print("Timezone: %s" % plug.timezone)

Getting and setting the name

print("Alias: %s" % plug.alias)
plug.alias = "My New Smartplug"

Getting emeter status (if applicable)

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

Plug-specific

Switching the led (plugs only)

print("Current LED state: %s" % plug.led)
plug.led = False # turn off led
print("New LED state: %s" % plug.led)

Bulb-specific API

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

The brightness property works in percentages.

print(bulb.brightness)
if bulb.is_dimmable:
    bulb.brightness = 100

Setting the color temperature

print(bulb.color_temp)
if bulb.is_variable_color_temp:
    bulb.color_temp = 3000

Setting the color

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

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

Development Setup

Docker

The following assumes you have a working installation of Docker.

Set up the environment and run the tests on demand.

docker build . -t pyhs100 && docker run -v $(PWD)/pyHS100/tests:/opt/pyHS100/pyHS100/tests  pyhs100 pytest