Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
exclude = .git,.tox,__pycache__,kasa/tests/newfakes.py,kasa/tests/test_fixtures.py
max-line-length = 88
per-file-ignores =
kasa/tests/*.py:D100,D101,D102,D103,D104
kasa/tests/*.py:D100,D101,D102,D103,D104,F401
docs/source/conf.py:D100,D103
ignore = D105, D107, E203, E501, W503
max-complexity = 18
127 changes: 1 addition & 126 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,30 +37,10 @@ This project is a maintainer-made fork of [pyHS100](https://github.com/GadgetRea
**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
Expand Down Expand Up @@ -108,112 +88,7 @@ The commands are straightforward, so feel free to check `--help` for instruction

# 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:
```python
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

```python
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.

```python
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:

```python
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

```python
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
```python
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.

```python
if bulb.is_color:
await bulb.set_hsv(180, 100, 100) # set to cyan
await bulb.update()
print(bulb.hsv)
```
You can find several code examples in [the API documentation](broken link).

## Contributing

Expand Down
20 changes: 20 additions & 0 deletions docs/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build

# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
35 changes: 35 additions & 0 deletions docs/make.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
@ECHO OFF

pushd %~dp0

REM Command file for Sphinx documentation

if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build

if "%1" == "" goto help

%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)

%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end

:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%

:end
popd
65 changes: 65 additions & 0 deletions docs/source/_static/copybutton.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright 2014 PSF. Licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
// File originates from the cpython source found in Doc/tools/sphinxext/static/copybutton.js

$(document).ready(function() {
/* Add a [>>>] button on the top-right corner of code samples to hide
* the >>> and ... prompts and the output and thus make the code
* copyable. */
var div = $('.highlight-python .highlight,' +
'.highlight-default .highlight,' +
'.highlight-python3 .highlight')
var pre = div.find('pre');

// get the styles from the current theme
pre.parent().parent().css('position', 'relative');
var hide_text = 'Hide the prompts and output';
var show_text = 'Show the prompts and output';
var border_width = pre.css('border-top-width');
var border_style = pre.css('border-top-style');
var border_color = pre.css('border-top-color');
var button_styles = {
'cursor':'pointer', 'position': 'absolute', 'top': '0', 'right': '0',
'border-color': border_color, 'border-style': border_style,
'border-width': border_width, 'color': border_color, 'text-size': '75%',
'font-family': 'monospace', 'padding-left': '0.2em', 'padding-right': '0.2em',
'border-radius': '0 3px 0 0'
}

// create and add the button to all the code blocks that contain >>>
div.each(function(index) {
var jthis = $(this);
if (jthis.find('.gp').length > 0) {
var button = $('<span class="copybutton">&gt;&gt;&gt;</span>');
button.css(button_styles)
button.attr('title', hide_text);
button.data('hidden', 'false');
jthis.prepend(button);
}
// tracebacks (.gt) contain bare text elements that need to be
// wrapped in a span to work with .nextUntil() (see later)
jthis.find('pre:has(.gt)').contents().filter(function() {
return ((this.nodeType == 3) && (this.data.trim().length > 0));
}).wrap('<span>');
});

// define the behavior of the button when it's clicked
$('.copybutton').click(function(e){
e.preventDefault();
var button = $(this);
if (button.data('hidden') === 'false') {
// hide the code output
button.parent().find('.go, .gp, .gt').hide();
button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'hidden');
button.css('text-decoration', 'line-through');
button.attr('title', show_text);
button.data('hidden', 'true');
} else {
// show the code output
button.parent().find('.go, .gp, .gt').show();
button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'visible');
button.css('text-decoration', 'none');
button.attr('title', hide_text);
button.data('hidden', 'false');
}
});
});
28 changes: 28 additions & 0 deletions docs/source/cli.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
Command-line 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.

Provisioning
~~~~~~~~~~~~

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.

``kasa --help``
~~~~~~~~~~~~~~~

.. program-output:: kasa --help
70 changes: 70 additions & 0 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))


# -- Project information -----------------------------------------------------

project = "python-kasa"
copyright = "2020, python-kasa developers"
author = "python-kasa developers"


# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.coverage",
"sphinx.ext.viewcode",
"sphinxcontrib.programoutput",
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = [] # type: ignore


# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "sphinx_rtd_theme"

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]


def setup(app):
# add copybutton to hide the >>> prompts, see https://github.com/readthedocs/sphinx_rtd_theme/issues/167
app.add_js_file("copybutton.js")

# see https://github.com/readthedocs/recommonmark/issues/191#issuecomment-622369992
from m2r import MdInclude

app.add_config_value("no_underscore_emphasis", False, "env")
app.add_config_value("m2r_parse_relative_links", False, "env")
app.add_config_value("m2r_anonymous_references", False, "env")
app.add_config_value("m2r_disable_inline_math", False, "env")
app.add_directive("mdinclude", MdInclude)
17 changes: 17 additions & 0 deletions docs/source/discover.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
Discovering devices
===================

.. code-block::

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}")


.. autoclass:: kasa.Discover
:members:
:undoc-members:
Loading