Commit Graph

634 Commits

Author SHA1 Message Date
Steven B
67b5d7de83
Update cli to use common modules and remove iot specific cli testing (#913) 2024-05-14 08:38:21 +01:00
Steven B
ef49f44eac
Deprecate is_something attributes (#912)
Deprecates the is_something attributes like is_bulb and is_dimmable in favour of the modular approach.
2024-05-13 18:52:08 +01:00
Steven B
33d839866e
Make Light and Fan a common module interface (#911) 2024-05-13 17:34:44 +01:00
Steven B
d7b00336f4
Rename bulb interface to light and move fan and light interface to interfaces (#910)
Also rename BulbPreset to LightPreset.
2024-05-11 19:40:08 +01:00
Steven B
f259a8f162
Make module names consistent and remove redundant module casting (#909)
Address the inconsistent naming of smart modules by removing all "Module" suffixes and aligning filenames with class names. Removes the casting of modules to the correct module type now that is is redundant. Update the adding of iot modules to use the ModuleName class rather than a free string.
2024-05-11 19:28:18 +01:00
Steven B
9473d97ad2
Create common interfaces for remaining device types (#895)
Introduce common module interfaces across smart and iot devices and provide better typing implementation for getting modules to support this.
2024-05-10 19:29:28 +01:00
Teemu R
7d4dc4c710
Improve smartdevice update module (#791)
* Expose current and latest firmware as features
* Provide API to get information about available firmware updates (e.g., changelog, release date etc.)
* Implement updating the firmware
2024-05-09 01:43:07 +02:00
Teemu R
353e84438c
Add support for contact sensor (T110) (#877)
Initial support for T110 contact sensor & T110 fixture by courtesy of @ngaertner.
2024-05-07 20:58:18 +02:00
Teemu R
7f98acd477
Add 'battery_percentage' only when it's available (#906)
At least some firmware versions of T110 are known not to report this.
2024-05-07 20:56:24 +02:00
Teemu R
b66a337f40
Add H100 1.5.10 and KE100 2.4.0 fixtures (#905) 2024-05-07 20:56:03 +02:00
Teemu R
55653d0346
Improve categorization of features (#904)
This updates the categorization of features and makes the id mandatory for features
2024-05-07 10:13:35 +01:00
Teemu R
50b5107f75
Add missing alarm volume 'normal' (#899)
Also logs a warning in feature repr if value not in choices and fixes the returned string to be consistent with valid values.
2024-05-07 09:38:09 +01:00
Steven B
f063c83378
Add child devices from hubs to generated list of supported devices (#898)
Updates generate_supported hook to include child devices of hubs in the list of supported devices.
2024-05-07 07:48:47 +01:00
Steven B
c5d65b624b
Make get_module return typed module (#892)
Passing in a string still works and returns either `IotModule` or
`SmartModule` type when called on `IotDevice` or `SmartDevice`
respectively. When calling on `Device` will return `Module` type.

Passing in a module type is then typed to that module, i.e.:
```py
smartdev.get_module(FanModule)  # type is FanModule
smartdev.get_module("FanModule")  # type is SmartModule
```
Only thing this doesn't do is check that you can't pass an `IotModule`
to a `SmartDevice.get_module()`. However there is a runtime check which
will return null if the passed `ModuleType` is not a subclass of
`SmartModule`.

Many thanks to @cdce8p for helping with this.
2024-05-03 17:01:21 +02:00
Teemu R
530fb841b0
Add fixture for waterleak sensor T300 (#897)
Fixture by courtesy of @ngaertner
(https://github.com/python-kasa/python-kasa/issues/875#issuecomment-2091484438)
2024-05-03 15:24:34 +02:00
Steven B
5b486074e2
Add LightEffectModule for dynamic light effects on SMART bulbs (#887)
Support the `light_effect` module which allows setting the effect to Off
or Party or Relax. Uses the new `Feature.Type.Choice`. Does not
currently allow editing of effects.
2024-05-02 16:31:12 +02:00
Teemu R
5ef81f4669
Improve feature setter robustness (#870)
This adds a test to check that all feature.set_value() calls will cause
a query, i.e., that there are no self.call()s that are not awaited, and
fixes existing code in this context.

This also fixes an issue where it was not possible to print out the
feature if the value threw an exception.
2024-05-02 15:32:06 +02:00
Teemu R
9dcd8ec91b
Improve temperature controls (#872)
This improves the temperature control features to allow implementing
climate platform support for homeassistant.

Also adds frostprotection module, which is also used to turn
the thermostat on and off.
2024-05-02 13:05:26 +00:00
Steven B
28d41092e5
Update interfaces so they all inherit from Device (#893)
Brings consistency to the api across Smart and Iot so the interfaces can be used for their specialist methods as well as the device methods (e.g. turn_on/off).
2024-05-02 13:55:08 +01:00
Steven B
b2194a1c62
Update ks240 fixture with child device query info (#890)
The fixture now includes the queries returned directly from the child devices which is stored under child_devices along with valid device ids.

Also fixes a bug in the test_cli.py::test_wifi_scan which fails with more than 9 networks.
2024-05-01 16:05:37 +01:00
Steven B
3fc131dfd2
Fix wifi scan re-querying error (#891) 2024-05-01 15:56:43 +01:00
Teemu R
46338ee21d
Use pydantic.v1 namespace on all pydantic versions (#883)
With https://github.com/pydantic/pydantic/pull/9042 being shipped with
[1.10.15](https://docs.pydantic.dev/latest/changelog/#v11015-2024-04-03),
we can clean up the imports a bit until we make decisions how to move
onward with or without pydantic.

---------

Co-authored-by: Steven B. <51370195+sdb9696@users.noreply.github.com>
2024-05-01 15:59:35 +02:00
Steven B
16f17a7729
Add Fan interface for SMART devices (#873)
Enables the Fan interface for devices supporting that component.
Currently the only device with a fan is the ks240 which implements it as
a child device. This PR adds a method `get_module` to search the child
device for modules if it is a WallSwitch device type.
2024-04-30 17:42:53 +01:00
Teemu R
7db989e2ec
Fix --help on subcommands (#886)
Pass a dummy object as context object as it will not be used by --help
anyway.

Also, allow defining --help anywhere in the argv, not just in the last
place.
2024-04-30 18:30:03 +02:00
Teemu R
5599756d28
Add support for waterleak sensor (T300) (#876) 2024-04-30 17:31:47 +02:00
Teemu R
300d823895
Implement choice feature type (#880)
Implement the choice feature type allowing to provide a list of choices that can be set.

Co-authored-by: sdb9696
2024-04-30 07:56:09 +01:00
Steven B
d3544b4989
Move SmartBulb into SmartDevice (#874) 2024-04-29 18:19:44 +01:00
Steven B
cb11b36511
Put modules back on children for wall switches (#881)
Puts modules back on the children for `WallSwitches` (i.e. ks240) and
makes them accessible from the `modules` property on the parent.
2024-04-29 18:34:20 +02:00
Steven B
e7553a7af4
Fix smartprotocol response list handler to handle null reponses (#884) 2024-04-29 14:24:30 +01:00
Teemu R
d7a36fe071
Add precision_hint to feature (#871)
This can be used to hint how the sensor value should be rounded when
displaying it to users.

The values are adapted from the values used by homeassistant.
2024-04-29 13:31:42 +02:00
Teemu R
1ff3162112
Expose IOT emeter info as features (#844)
Exposes IOT emeter information using features, bases on #843 to allow
defining the units.


---------

Co-authored-by: Steven B <51370195+sdb9696@users.noreply.github.com>
2024-04-25 14:59:17 +02:00
Teemu R
10629f2db9
Be more lax on unknown SMART devices (#863) 2024-04-25 07:36:30 +01:00
Steven B
53b84b7683
Handle paging of partial responses of lists like child_device_info (#862)
When devices have lists greater than 10 for child devices only the first
10 are returned. This retrieves the rest of the items (currently with
single requests rather than multiple requests)
2024-04-24 20:32:30 +02:00
Steven B
eff8db450d
Support for new ks240 fan/light wall switch (#839)
In order to support the ks240 which has children for the fan and light
components, this PR adds those modules at the parent level and hides the
children so it looks like a single device to consumers. It also decides
which modules not to take from the child because the child does not
support them even though it say it does. It does this for now via a
fixed list, e.g. `Time`, `Firmware` etc.

Also adds fixtures from two versions and corresponding tests.
2024-04-24 20:17:49 +02:00
Teemu R
65874c0365
Embed FeatureType inside Feature (#860)
Moves `FeatureType` into `Feature` to make it easier to use the API.
This also enforces that no invalid types are accepted (i.e.,
`Category.Config` cannot be a `Sensor`)
If `--verbose` is used with the cli tool, some extra information is
displayed for features when in the state command.
2024-04-24 18:38:52 +02:00
Steven B
e410e4f3f3
Fix incorrect state updates in FakeTestProtocols (#861) 2024-04-24 12:25:16 +01:00
Teemu R
6e5cae1f47
Implement action feature (#849)
Adds `FeatureType.Action` making it possible to expose features like
"reboot", "test alarm", "pair" etc.

The `attribute_getter` is no longer mandatory, but it will raise an
exception if not defined for other types than actions.
Trying to read returns a static string `<Action>`.
This overloads the `set_value` to call the given callable on any value.

This also fixes the `play` and `stop` coroutines of the alarm module to
await the call.
2024-04-23 19:49:04 +02:00
Teemu R
b860c32d5f
Implement feature categories (#846)
Initial implementation for feature categories to help downstreams and
our cli tool to categorize the data for more user-friendly manner. As
more and more information is being exposed through the generic features
interface, it is necessary to give some hints to downstreams about how
might want to present the information to users.

This is not a 1:1 mapping to the homeassistant's mental model, and it
will be necessary to fine-tune homeassistant-specific parameters by
other means to polish the presentation.
2024-04-23 19:20:12 +02:00
Steven B
aa969ef020
Better firmware module support for devices not connected to the internet (#854)
Devices not connected to the internet will either error when querying
firmware queries (e.g. P300) or return misleading information (e.g.
P100). This PR adds the cloud connect query to the initial queries and
bypasses the firmware module if not connected.
2024-04-23 13:56:32 +02:00
Adrian Dörr
0ab7436eef
Add support for KH100 hub (#847)
Add SMART.KASAHUB to the map of supported devices.
This also adds fixture files for KH100, KE100, and T310, and adapts affected modules and their tests accordingly.

---------

Co-authored-by: Steven B <51370195+sdb9696@users.noreply.github.com>
2024-04-22 16:24:15 +02:00
Teemu R
72db5c6447
Add temperature control module for smart (#848) 2024-04-22 12:39:07 +01:00
Teemu R
890900daf3
Add support for feature units (#843)
Co-authored-by: Steven B <51370195+sdb9696@users.noreply.github.com>
2024-04-22 10:25:30 +01:00
Teemu R
651ad96144
Use brightness module for smartbulb (#853)
Moves one more feature out from the smartbulb class
2024-04-20 20:29:07 +02:00
Teemu R
29b28966e0
Remove mock fixtures (#845) 2024-04-20 16:37:24 +01:00
Steven B
214b26a1ea
Re-query missing responses after multi request errors (#850)
When smart devices encounter an error during a multipleRequest they
return the previous successes and the current error and stop processing
subsequent requests. This checks the responses returned and
re-queries individually for any missing responses so that individual
errors do not break other components.
2024-04-20 17:24:49 +02:00
Steven B
aeb2c923c6
Add ColorModule for smart devices (#840)
Adds support L530 hw_version 1.0
2024-04-20 17:18:35 +02:00
Teemu R
4573260ac8
Ignore system environment variables for tests (#851) 2024-04-20 16:14:53 +01:00
Steven B
203bd79253
Enable and convert to future annotations (#838) 2024-04-17 15:39:24 +02:00
Teemu R
82d92aeea5
smartbulb: Limit brightness range to 1-100 (#829)
The allowed brightness for tested light devices (L530, L900) is [1-100]
instead of [0-100] like it was for some kasa devices.
2024-04-17 13:33:10 +02:00
Teemu R
700643d3cf
Add fan module (#764)
Co-authored-by: Steven B <51370195+sdb9696@users.noreply.github.com>
2024-04-17 11:07:16 +01:00
Steven B
da441bc697
Update poetry locks and pre-commit hooks (#837)
Also updates CI pypy versions to be 3.9 and 3.10 which are the currently
[supported
versions](https://www.pypy.org/posts/2024/01/pypy-v7315-release.html).
Otherwise latest cryptography doesn't ship with pypy3.8 wheels and is
unable to build on windows.

Also updates the `codecov-action` to v4 which fixed some intermittent
uploading errors.
2024-04-16 20:21:20 +02:00
Steven B
0f3b29183d
Fix non python 3.8 compliant test (#832) 2024-03-28 11:38:58 +00:00
Teemu R
c08b58cd8b
Add colortemp feature for iot devices (#827)
Make color temperature feature available for iot bulbs.
2024-03-26 18:33:10 +00:00
Teemu R
35dbda7049
Change state_information to return feature values (#804)
This changes `state_information` to return the names and values of
all defined features.
It was originally a "temporary" hack to show some extra, device-specific
information in the cli tool, but now that we have device-defined
features we can leverage them.
2024-03-26 19:28:39 +01:00
Teemu R
d63f43a230
Add colortemp module (#814)
Allow controlling the color temperature via features interface:
```
$ kasa --host 192.168.xx.xx feature color_temperature                                                                                                                             
Color temperature (color_temperature): 0

$ kasa --host 192.168.xx.xx feature color_temperature 2000
Setting color_temperature to 2000
Raised error: Temperature should be between 2500 and 6500, was 2000
Run with --debug enabled to see stacktrace

$ kasa --host 192.168.xx.xx feature color_temperature 3000
Setting color_temperature to 3000

$ kasa --host 192.168.xx.xx feature color_temperature                                                                                                                             
Color temperature (color_temperature): 3000
```
2024-03-15 17:36:07 +01:00
Teemu R
270614aa02
Revise device initialization and subsequent updates (#807)
This improves the initial update cycle to fetch the information as early
as possible and avoid requesting unnecessary information (like the child
component listing) in every subsequent call of `update()`.

The initial update performs the following steps:
1. `component_nego` (for components) and `get_device_info` (for common
device info) are requested as first, and their results are stored in the
internal state to allow individual modules (like colortemp) to access
the data during the initialization later on.
2. If `child_device` component is available, the child device list and
their components is requested separately to initialize the children.
3. The modules are initialized based on component lists, making the
queries available for the regular `update()`.
4. Finally, a query requesting all module-defined queries is executed,
including also those that we already did above, like the device info.

All subsequent updates will only involve queries that are defined by the
supported modules. This also means that we do not currently support
adding & removing child devices on the fly.

The internal state contains now only the responses for the most recent
update (i.e., no component information is directly available anymore,
but needs to be accessed separately if needed). If component information
is wanted from homeassistant users via diagnostics reports, the
diagnostic platform needs to be adapted to acquire this separately.
2024-03-15 17:18:13 +01:00
Teemu R
48ac39e6d8
Refactor split smartdevice tests to test_{iot,smart}device (#822) 2024-03-15 15:55:48 +00:00
Steven B
063518b7db
Add support for firmware module v1 (#821)
The v1 of firmware does not support changing the auto update setting,
this makes it so that it isn't requested in that case.
2024-03-12 18:18:08 +01:00
Steven B
33be568897
Add P100 fw 1.4.0 fixture (#820) 2024-03-12 17:28:50 +01:00
Steven B
7507837734
Fix slow aestransport and cli tests (#816) 2024-03-11 10:17:12 +00:00
Teemu R
3495bd83df
Add T315 fixture, tests for humidity&temperature modules (#802) 2024-03-06 18:04:09 +00:00
Steven B
adce92a761
Add iot brightness feature (#808) 2024-03-06 16:45:08 +00:00
Steven B
42080bd954
Update test framework for dynamic parametrization (#810) 2024-03-06 16:18:52 +00:00
Steven B
ced879498b
Put child fixtures in subfolder (#809)
This should prevent child fixtures from hubs breaking tests due to
missing discovery info. To get these devices in `filter_fixtures`
include protocol string of `SMART.CHILD`.
2024-03-06 15:54:55 +01:00
Teemu R
0d5a3c8439
Add brightness module (#806)
Add module for controlling the brightness.
2024-03-05 15:41:40 +01:00
Teemu R
eb4c048b57
Simplify device __repr__ (#805)
Previously:
```
>>> dev
<DeviceType.Hub model H100 at 192.168.xx.xx (Smart Hub), is_on: False - dev specific: {'overheated': False, 'signal_level': 2, 'SSID': 'xx'}>
>>> dev.children[0]
<ChildDevice Temperature Humidity Sensor of <DeviceType.Hub model H100 at 192.168.xx.xx (Smart Hub), is_on: False - dev specific: {'overheated': False, 'signal_level': 2, 'SSID': 'xx'}>>
```

Now:
```
>>> dev
Device: <DeviceType.Hub at 192.168.xx.xx - Smart Hub (H100)>
>>> dev.children[0]
<DeviceType.Sensor Temperature Humidity Sensor (T315) of <DeviceType.Hub at 192.168.xx.xx - Smart Hub (H100)>>
```
2024-03-05 13:35:19 +01:00
Steven B
fcad0d2344
Add WallSwitch device type and autogenerate supported devices docs (#758) 2024-03-01 18:32:45 +00:00
Steven B
0306e05fb9
Fix energy module calling get_current_power (#798) 2024-02-28 17:57:02 +00:00
Teemu R
75c60eb97c
Add fixture for P110 sw 1.0.7 (#801)
By courtesy of @pplucky (#797)
2024-02-27 20:06:13 +01:00
Steven B
97680bdcee
Refactor test framework (#794)
This is in preparation for tests based on supporting features amongst
other tweaks:

- Consolidates the filtering logic that was split across `filter_model`
and `filter_fixture`
- Allows filtering `dev` fixture by `component`
- Consolidates fixtures missing method warnings into one warning
- Does not raise exceptions from `FakeSmartTransport` for missing
methods (required for KS240)
2024-02-27 18:39:04 +01:00
Steven B
d82747d73f
Support multiple child requests (#795) 2024-02-26 17:13:46 +01:00
Teemu R
cbf82c9498
Support for on_off_gradually v2+ (#793)
Previously, only v1 of on_off_gradually is supported, and the newer versions are not backwards compatible.
This PR adds support for the newer versions of the component, and implements `number` type for `Feature` to expose the transition time selection.
This also adds a new `supported_version` property to the main module API.
2024-02-24 02:16:43 +01:00
Teemu R
a73e2a9ede
Add H100 fixtures (#737)
One direct out of the box, another with upgraded fw & t315
2024-02-24 00:12:19 +01:00
Teemu R
c3aa34425d
Add temperature_unit feature to t315 (#788) 2024-02-24 00:05:06 +01:00
Teemu R
c61f2e931c
Add --child option to feature command (#789)
This allows listing and changing child device features that were previously not accessible using the cli tool.
2024-02-23 23:32:17 +01:00
Teemu R
7884436679
Add updated L530 fixture 1.1.6 (#792) 2024-02-23 17:13:11 +01:00
Teemu R
bc65f96f85
Add initial support for H100 and T315 (#776)
Adds initial support for H100 and its alarmmodule.

Also implements the following modules for T315:
* reportmodule (reporting interval)
* battery
* humidity
* temperature
2024-02-22 23:09:38 +01:00
Teemu R
951d41a628
Fix auto update switch (#786)
Set the attribute_setter. Also, (at least some) devices expect the full payload data so send it with.
2024-02-22 20:57:42 +01:00
Teemu R
2b0721aea9
Generalize smartdevice child support (#775)
* Initialize children's modules (and features) using the child component negotiation results
* Set device_type based on the device response
* Print out child features in cli 'state'
* Add --child option to cli 'command' to allow targeting child devices
* Guard "generic" features like rssi, ssid, etc. only to devices which have this information

Note, we do not currently perform queries on child modules so some data may not be available. At the moment, a stop-gap solution to use parent's data is used but this is not always correct; even if the device shares the same clock and cloud connectivity, it may have its own firmware updates.
2024-02-22 20:46:19 +01:00
Benjamin Ness
f965b14021
Add feature for ambient light sensor (#787) 2024-02-22 19:11:30 +01:00
Steven B
a87fc3b766
Retry query on 403 after succesful handshake (#785)
If a handshake session becomes invalid the device returns 403 on send and an `AuthenticationError` is raised which prevents a retry, however a retry would be successful.  In HA this causes devices to go into reauth flow which is not necessary.
2024-02-22 18:02:03 +01:00
Teemu R
d9d2f1a430
Remove SmartPlug in favor of SmartDevice (#781)
With the move towards autodetecting available features, there is no reason to keep SmartPlug around.

kasa.smart.SmartPlug is removed in favor of kasa.smart.SmartDevice which offers the same functionality.
Information about auto_off can be accessed using Features of the AutoOffModule on supported devices.

Co-authored-by: Steven B. <51370195+sdb9696@users.noreply.github.com>
2024-02-22 14:34:55 +01:00
Steven B
8c39e81a40
Rename and deprecate exception classes (#739)
# Public #
SmartDeviceException -> KasaException
UnsupportedDeviceException(SmartDeviceException) -> UnsupportedDeviceError(KasaException)
TimeoutException(SmartDeviceException, asyncio.TimeoutError) -> TimeoutError(KasaException, asyncio.TimeoutError)

Add new exception for error codes -> DeviceError(KasaException)
AuthenticationException(SmartDeviceException) -> AuthenticationError(DeviceError)

# Internal #
RetryableException(SmartDeviceException) -> _RetryableError(DeviceError)
ConnectionException(SmartDeviceException) -> _ConnectionError(KasaException)
2024-02-21 16:52:55 +01:00
Steven B
4beff228c9
Enable shell extra for installing ptpython and rich (#782)
Co-authored-by: Teemu R. <tpr@iki.fi>
2024-02-20 18:40:28 +00:00
Steven B
5ba3676422
Raise CLI errors in debug mode (#771) 2024-02-20 11:21:04 +00:00
Teemu R
29e6b92b1e
Add missing firmware module import (#774)
#766 was merged too hastily to fail the tests as the module was never imported.
2024-02-20 01:00:26 +01:00
Teemu R
3de04f320a
Add firmware module for smartdevice (#766)
Initial firmware module implementation.

New switch: `Auto update enabled (auto_update_enabled): False`
New binary sensor: `Update available (update_available): False`
2024-02-19 21:29:09 +01:00
Teemu R
efb4a0f31f
Auto auto-off module for smartdevice (#760)
Adds auto-off implementation. The feature stays enabled after the timer runs out, and it will start the countdown if the device is turned on again without explicitly disabling it.

New features:
* Switch to select if enabled: `Auto off enabled (auto_off_enabled): False`
* Setting to change the delay: `Auto off minutes (auto_off_minutes): 222`
* If timer is active, datetime object when the device gets turned off: `Auto off at (auto_off_at): None`
2024-02-19 21:11:11 +01:00
Teemu R
44b59efbb2
Add smartdevice module for led controls (#761)
Allows controlling LED on devices that support it.
2024-02-19 20:59:09 +01:00
Teemu R
f5175c5632
Add cloud module for smartdevice (#767)
Add initial support for the cloud module.

Adds a new binary sensor: `Cloud connection (cloud_connection): False`
2024-02-19 20:48:46 +01:00
Teemu R
520b6bbae3
Add smartdevice module for smooth transitions (#759)
* Add smart module for smooth transitions

* Fix tests

* Fix linting
2024-02-19 20:39:20 +01:00
Teemu R
11719991c0
Initial implementation for modularized smartdevice (#757)
The initial steps to modularize the smartdevice. Modules are initialized based on the component negotiation, and each module can indicate which features it supports and which queries should be run during the update cycle.
2024-02-19 18:01:31 +01:00
Steven B
9ab9420ad6
Let caller handle SMART errors on multi-requests (#754)
* Fix for missing get_device_usage

* Fix coverage and add methods to exceptions

* Remove unused caplog fixture
2024-02-15 18:10:34 +00:00
Teemu R
64da736717
Add generic interface for accessing device features (#741)
This adds a generic interface for all device classes to introspect available device features,
that is necessary to make it easier to support a wide variety of supported devices with different set of features.
This will allow constructing generic interfaces (e.g., in homeassistant) that fetch and change these features without hard-coding the API calls.

`Device.features()` now returns a mapping of `<identifier, Feature>` where the `Feature` contains all necessary information (like the name, the icon, a way to get and change the setting) to present and change the defined feature through its interface.
2024-02-15 16:25:08 +01:00
Steven B
57835276e3
Fix devtools for P100 and add fixture (#753) 2024-02-14 19:43:10 +00:00
Steven B
13d8d94bd5
Fix for P100 on fw 1.1.3 login_version none (#751)
* Fix for P100 on fw 1.1.3 login_version none

* Fix coverage

* Add delay before trying default login

* Move devtools and fixture out

* Change logging string

Co-authored-by: Teemu R. <tpr@iki.fi>

* Fix test

---------

Co-authored-by: Teemu R. <tpr@iki.fi>
2024-02-14 19:13:28 +00:00
Steven B
45f251e57e
Ensure connections are closed when cli is finished (#752)
* Ensure connections are closed when cli is finished

* Test for close calls on error and success
2024-02-14 17:03:50 +00:00
Steven B
5d81e9f94c
Pass timeout parameters to discover_single (#744)
* Pass timeout parameters to discover_single

* Fix tests
2024-02-08 20:03:06 +01:00
Teemu R
458949157a
Add 'shell' command to cli (#738)
* Add 'shell' command to cli

* Add test

* Add ptpython as optional dep
2024-02-06 14:48:19 +01:00
Steven B
6ab17d823c
Reduce AuthenticationExceptions raising from transports (#740)
* Reduce AuthenticationExceptions raising from transports

* Make auth failed test ids easier to read

* Test invalid klap response length
2024-02-05 21:49:26 +01:00
Steven B
215b8d4e4f
Fix discovery cli to print devices not printed during discovery timeout (#670)
* Fix discovery cli to print devices not printed during discovery

* Fix tests

* Fix print exceptions not being propagated

* Fix tests

* Reduce test discover_send time

* Simplify wait logic

* Add tests

* Remove sleep loop and make auth failed a list
2024-02-05 17:53:09 +00:00
Steven B
0d119e63d0
Refactor devices into subpackages and deprecate old names (#716)
* Refactor devices into subpackages and deprecate old names

* Tweak and add tests

* Fix linting

* Remove duplicate implementations affecting project coverage

* Update post review

* Add device base class attributes and rename subclasses

* Rename Module to BaseModule

* Remove has_emeter_history

* Fix missing _time in init

* Update post review

* Fix test_readmeexamples

* Fix erroneously duped files

* Clean up iot and smart imports

* Update post latest review

* Tweak Device docstring
2024-02-04 16:20:08 +01:00
Teemu R
6afd05be59
Do not crash cli on missing discovery info (#735) 2024-02-03 15:28:51 +01:00
Teemu R
fae071f0df
Fix port-override for aes&klap transports (#734)
* Fix port-override for aes&klap transports

* Add tests for port override
2024-02-03 15:28:20 +01:00
Teemu R
1f15bcda7c
Avoid crashing on childdevice property accesses (#732)
* Avoid crashing on childdevice property accesses

* Push updates from parent to child
2024-02-02 17:29:14 +01:00
J. Nick Koston
1f62aee7b6
Add TP25 fixtures (#729)
* Add TP25 fixtures

* redump fixture
2024-02-01 19:52:57 +01:00
Teemu R
1acf4e86da
Retain last two chars for children device_id (#733) 2024-02-01 19:27:01 +01:00
J. Nick Koston
8657959ace
Add TP15 fixture (#730) 2024-01-31 18:30:19 +01:00
Teemu R
55525fc58b
Unignore F401 for tests (#724)
* Unignore F401 for tests

* Fix linting
2024-01-30 00:15:58 +01:00
Teemu R
9e6896a08f
Various test code cleanups (#725)
* Separate fake protocols for iot and smart

* Move control_child impl into its own method

* Organize schemas into correct places

* Add test_childdevice

* Add missing return for _handle_control_child
2024-01-29 20:26:39 +01:00
Steven B
bc1503c40e
Fix TapoBulb state information for non-dimmable SMARTSWITCH (#726) 2024-01-29 19:52:22 +01:00
Teemu R
f8e273981c
Add P300 fixture (#717)
* Add P300 fixture

* fixture after update

* Add tests for p300
2024-01-29 18:14:30 +01:00
Teemu R
1ad2a05b65
Initial support for tapos with child devices (#720)
* Add ChildDevice and ChildProtocolWrapper

* Initialize & update children

* Fix circular imports

* Add dummy_protocol fixture and tests for unwrapping responseData

* Use dummy_protocol for existing smartprotocol tests

* Move _ChildProtocolWrapper to smartprotocol.py

* Use dummy_protocol for test multiple requests

* Use device_id instead of position for selecting the child

* Fix wrapping for regular requests

* Remove unused imports

* tweak

* rename child_device to childdevice

* Fix import
2024-01-29 17:11:29 +01:00
J. Nick Koston
b479b6d84d
Avoid rebuilding urls for every request (#715)
* Avoid rebuilding urls for every request

* more fixes

* more fixes

* make mypy happy

* reduce

* tweak

* fix tests

* fix tests

* tweak

* tweak

* lint

* fix type
2024-01-29 15:26:00 +00:00
Teemu R
69dcc0d8bb
Implement alias set for tapodevice (#721) 2024-01-29 11:57:32 +01:00
Steven B
9c0a831027
Enable batching of multiple requests (#662)
* Enable batching of multiple requests

* Test for debug enabled outside of loop

* tweaks

* tweaks

* tweaks

* Update kasa/smartprotocol.py

Co-authored-by: Teemu R. <tpr@iki.fi>

* revert

* Update pyproject.toml

* Add batch test and make batch_size configurable

---------

Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: Teemu R. <tpr@iki.fi>
2024-01-29 11:55:54 +01:00
Steven B
cedffc5c9f
Update L510E(US) fixture with mac prefix (#722) 2024-01-29 09:25:36 +00:00
J. Nick Koston
7e2be35e4b
Reduce the number of times creating the cipher in klap (#712) 2024-01-26 07:44:41 -10:00
J. Nick Koston
dd38225f51
Use hashlib in place of hashes.Hash (#714) 2024-01-26 06:57:56 -10:00
J. Nick Koston
fcd4883645
Use hashlib for klap since its faster (#711) 2024-01-26 09:33:18 +00:00
Steven B
0d0f56414c
Switch from TPLinkSmartHomeProtocol to IotProtocol/XorTransport (#710)
* Switch from TPLinkSmartHomeProtocol to IotProtocol/XorTransport

* Add test

* Update docs

* Fix ruff deleting deprecated import
2024-01-26 09:11:31 +00:00
Steven B
c318303255
Add concrete XorTransport class with full implementation (#646)
* Add concrete XorTransport class

* Update xortransport reset() docstring
2024-01-25 17:37:19 +00:00
J. Nick Koston
716b1f82d9
Add support for the S500 (#705)
* Add support for the S500D

* tweak

* Add S505
2024-01-25 09:07:01 +01:00
J. Nick Koston
cba073ebde
Add support for tapo wall switches (S500D) (#704)
* Add support for the S500D

* tweak

* Update README.md
2024-01-25 08:54:56 +01:00
J. Nick Koston
fa94548723
Add additional L900-10 fixture (#707) 2024-01-25 08:53:43 +01:00
J. Nick Koston
fa6bc59b29
Replace rich formatting stripper (#706)
* Revert "Fix overly greedy _strip_rich_formatting (#703)"

This reverts commit ae6a31463e.

* Improve rich formatter stripper

reverts and replaces #703
2024-01-25 08:49:26 +01:00
J. Nick Koston
8947ffbc94
Add L930-5 fixture (#694)
* Add L930-5 fixture

* Mark L930-5 as variable temp

* Update readme

* Fix overly greedy _strip_rich_formatting

---------

Co-authored-by: Teemu Rytilahti <tpr@iki.fi>
2024-01-24 22:31:01 +00:00
J. Nick Koston
3235ba620d
Add updated L920 fixture (#680)
* Add updated L920 fixture

* Fix overly greedy _strip_rich_formatting

---------

Co-authored-by: Teemu R <tpr@iki.fi>
2024-01-24 22:29:55 +00:00
J. Nick Koston
ae6a31463e
Fix overly greedy _strip_rich_formatting (#703) 2024-01-24 11:53:28 -10:00
J. Nick Koston
3df837cc82
Ensure login token is only sent if aes state is ESTABLISHED (#702) 2024-01-24 09:43:42 -10:00
Teemu R
aecf0ecd8a
Do not crash on missing geolocation (#701)
If 'has_set_location_info' is false, the geolocation is missing.
2024-01-24 12:21:37 +00:00
J. Nick Koston
bab40d43e6
Renew the handshake session 20 minutes before we think it will expire (#697)
* Renew the KLAP handshake session 20 minutes before we think it will expire

Currently we assumed the clocks were perfectly aligned and the handshake
session lasted 20 hours.  We now add a 20 minute buffer

* use timeout cookie when available
2024-01-24 10:11:27 +01:00
J. Nick Koston
24c645746e
Refactor aestransport to use a state enum (#691) 2024-01-23 22:50:25 -10:00
Steven B
eb217a748c
Fix test_klapprotocol test duration (#698) 2024-01-23 22:20:44 -10:00
Teemu R
8b566757c3
Add new cli command 'command' to execute arbitrary commands (#692)
* Add new cli command 'command' to execute arbitrary commands

This deprecates 'raw-command', which requires positional argument for module,
in favor of new 'command' that accepts '--module' option for IOT devices.

* Pull block list to the module level
2024-01-24 09:10:55 +01:00
J. Nick Koston
5907dc763a
Add fixtures for L510E (#693)
* Add fixtures for L510E

* mac
2024-01-24 06:59:39 +00:00
Teemu R
52c3fb4d52
Add 1003 (TRANSPORT_UNKNOWN_CREDENTIALS_ERROR) (#667) 2024-01-24 00:12:01 +01:00
Steven B
1788c50146
Update transport close/reset behaviour (#689)
Co-authored-by: J. Nick Koston <nick@koston.org>
2024-01-23 12:15:18 -10:00
Teemu R
e576fcdb46
Allow raw-command and wifi without update (#688)
* Allow raw-command and wifi without update

* Call update always but on wifi&raw-command

* Add tests

* Skip update also if device_family was defined, as device factory performs an update
2024-01-23 22:58:57 +01:00
Steven B
f045696ebe
Fix P100 error getting conn closed when trying default login after login failure (#690) 2024-01-23 11:51:07 -10:00
Steven B
e233e377ad
Generate AES KeyPair lazily (#687)
* Generate AES KeyPair lazily

* Fix coverage

* Update post-review

* Fix pragma

* Make json dumps consistent between python and orjson

* Add comment

* Add comments re json parameter in HttpClient
2024-01-23 15:29:27 +00:00
Steven B
718983c401
Try default tapo credentials for klap and aes (#685)
* Try default tapo credentials for klap and aes

* Add tests
2024-01-23 14:44:32 +00:00
Teemu R
c8ac3a29c7
Add reboot and factory_reset to tapodevice (#686)
* Add reboot and factory_reset to tapodevice

* Add test for reboot command

* Fix mocking as different protocols use different methods for comms..
2024-01-23 14:26:47 +01:00
Teemu R
cfbdf7c64a
Show discovery data for state with verbose (#678)
* Show discovery data for state with verbose

* Remove duplicate discovery printout on discovery, add a newline for readability
2024-01-23 13:24:17 +01:00
J. Nick Koston
d5fdf05ed2
Add P100 test fixture (#683) 2024-01-23 10:12:24 +00:00
J. Nick Koston
abd3ee0768
Add P135 fixture (#673)
* Add P135 fixture

This device is a dimmer but we currently treat it as a on/off

* add to conftest
2024-01-23 08:31:19 +01:00
J. Nick Koston
65c47a9373
Update fixtures from test devices (#679)
* Update fixtures from test devices

* move l920 to another pr
2024-01-23 08:12:54 +01:00
J. Nick Koston
37f522c763
Add L530E(US) fixture (#674) 2024-01-23 06:24:08 +01:00
Steven B
ee487ad837
Sleep between discovery packets (#656)
* Sleep between discovery packets

* Add tests
2024-01-22 18:25:23 +01:00
Steven B
6b0a72d5a7
Add protocol and transport documentation (#663)
* Add protocol and transport documentation

* Update post review
2024-01-22 17:45:19 +01:00
Steven B
14acc8550e
Rename base TPLinkProtocol to BaseProtocol (#669) 2024-01-22 16:28:30 +01:00
Teemu R
df59791829
Add l900-5 1.1.0 fixture (#664)
* Adds new localSmart module
* Changed from AES to klap
* Doesn't reboot itself when receiving a RST for the cloud connectivity requests
2024-01-21 01:41:13 +01:00
Teemu R
f77e87dc5d
dump_devinfo improvements (#657)
* dump_devinfo improvements

* Scrub only the last three bytes for mac addresses
* Add --target to allow creating fixtures based on discovery
* Save fixtures directly to correct location, add --basedir to allow defining the location of repository root
* Add --autosave to disable prompting for saving

* Update fixtures for devices I have

* Add fixture for HS110 hw 4.0 fw 1.0.4

* Improve help strings

* Fix tests

* Update devtools README

* Default to discovery if no host/target given
2024-01-20 14:20:08 +01:00
Steven B
49cfef087c
Make close behaviour consistent across new protocols and transports (#660) 2024-01-20 13:35:05 +01:00
Steven B
e94cd118a4
Add fixtures with new MAC mask (#661) 2024-01-20 13:22:54 +01:00
J. Nick Koston
8523800b23
Fix minor typos in docstrings (#659) 2024-01-20 02:40:21 +01:00
J. Nick Koston
d62b5a55cc
Improve and document close behavior (#654)
* Close connection on smartprotocol timeout

* tweaks
2024-01-19 21:30:01 +01:00
Steven B
38159140fb
Fix httpclient exceptions on read and improve error info (#655) 2024-01-19 21:06:50 +01:00
Steven B
bedf05ce3b
Remove time logging in debug message (#645) 2024-01-18 08:32:58 -10:00
Steven B
c3329155c8
Raise SmartDeviceException on invalid config dicts (#640)
Co-authored-by: J. Nick Koston <nick@koston.org>
2024-01-18 07:51:50 -10:00
Steven B
642e9a1f5b
Migrate http client to use aiohttp instead of httpx (#643) 2024-01-18 07:32:26 -10:00
Steven B
3b1b0a3c21
Encapsulate http client dependency (#642)
* Encapsulate http client dependency

* Store cookie dict as variable

* Update post-review
2024-01-18 10:57:33 +01:00
J. Nick Koston
eadf1203fc
Add fixture for L920 (#638) 2024-01-14 23:49:31 +01:00
J. Nick Koston
aed67dad16
Fix connection indeterminate state on cancellation (#636)
* Fix connection indeterminate state on cancellation

If the task the query is running in it cancelled, we do
know the state of the connection so we must close. Previously
we would not close on BaseException which could result
in reading the previous response if the previous query was
cancelled after the request had been sent

* add test for cancellation
2024-01-13 18:37:24 +01:00
Steven B
fbce755544
Raise TimeoutException on discover_single timeout (#632) 2024-01-11 16:13:44 +01:00
Steven B
5b8280a8d9
Return alias as None for new discovery devices before update (#627)
* Trim the length of the unavailable device alias

* Update to use short mac as auth required alias

* Update to return alias as none
2024-01-11 16:12:02 +01:00
Steven B
fd2170c82c
Update config to_dict to exclude credentials if the hash is empty string (#626)
* Update config to_dict to exclude credentials if the hash is empty string

* Add test
2024-01-10 20:47:30 +01:00
Steven B
d5a6fd8e73
Improve test coverage (#625) 2024-01-10 20:37:43 +01:00
Steven B
3e0cd07b7c
Update docs for newer devices and DeviceConfig (#614)
* Update docs for newer devices and DeviceConfig

* Tweak docs post review

* Move sentence to newline

* Update post review

* Update following review
2024-01-10 20:13:14 +01:00
Steven B
897db674c2
Add L900-10 fixture and it's additional component requests (#629) 2024-01-10 19:40:36 +01:00
J. Nick Koston
460054ced7
Avoid recreating struct each request in legacy protocol (#628) 2024-01-09 13:51:04 -10:00
Nathan Wreggit
cfe694e5de
Get child emeters with CLI (#623)
* Get child emeters with CLI

* Avoid extra IO when not que querying the child emeter
2024-01-05 02:25:24 +01:00
Teemu R
2d8a8d9511
Add update-credentials command (#620)
* Add change credentials command

* Rename command and add prompts for credential update
2024-01-05 02:25:15 +01:00
J. Nick Koston
554fe0a96e
Avoid linear search for emeter realtime and emeter_today (#622)
* Avoid linear search for emeter realtime and emeter_today

Most of the time the data we want is at the end of the
list so we now search backwards to avoid having to
scale all the data and throw most of it away

* more tweaks

* coverage

* coverage

* preen

* coverage

* branch cover
2024-01-05 02:01:00 +01:00
J. Nick Koston
efd67b9261
Add P125M and update EP25 fixtures (#621)
* Add P125M and update EP25 fixtures

* fix: adjust tests
2024-01-05 00:01:34 +01:00
Teemu R
17d96064c2
Mark L900-5 as supported (#617)
* Add fixture for L900-5

* Update readme
2024-01-04 19:52:11 +01:00
Teemu R
7a3eedeee9
Check the ct range for color temp support (#619) 2024-01-04 19:28:48 +01:00
sdb9696
b156defc3c
Fix cli discover bug with None username/password (#615) 2024-01-04 19:17:48 +01:00
sdb9696
e9bf9f58ee
Allow serializing and passing of credentials_hashes in DeviceConfig (#607)
* Allow passing of credentials_hashes in DeviceConfig

* Update following review
2024-01-03 22:46:08 +01:00
Teemu R
3692e4812f
Implement wifi interface for tapodevice (#606)
* Implement wifi interface for tapodevice

* Implement wifi_join

Tested to work on P110

* Fix linting
2024-01-03 22:45:16 +01:00
gimpy88
c810298b04
Add support for KS205 and KS225 wall switches (#594)
* KS205 Fixture

* KS225 Fixture

* Added Smart.KasaSwitch device type

* Added KS225 to test

* Added variable color temp check

* Added supported devices to readme

* Removed parenthesis

* Updated fixtures

* Fixed for ruff
2024-01-03 19:31:42 +01:00
Teemu R
30c4e6a6a3
Cleanup credentials handling (#605)
* credentials: don't allow none to simplify checks

* Implement __bool__ for credentials

* Cleanup klaptransport cred usage

* Cleanup deviceconfig and tapodevice

* fix linting

* Pass dummy credentials for tests

* Remove __bool__ dunder and add docs to credentials

* Check for cred noneness in tapodevice.update()
2024-01-03 19:26:52 +01:00
Teemu R
10fc2c3c54
Pull up emeter handling to tapodevice base class (#601)
* Pull has_emeter property up to tapodevice base class

This will also use the existence of energy_monitoring in the component_nego query to decide if the device has the service.

* Move emeter related functions to tapodevice

* Remove supported_modules override for now

This should be done in a separate PR, if we want to expose the available components to cli and downstreams

* Dedent extra reqs

* Move extra_reqs initialization

* Fix tests
2024-01-03 19:04:34 +01:00
Teemu R
864ea92ece
Update P110(EU) fixture (#604) 2024-01-02 19:34:39 +01:00
Teemu R
9a2b513e6a
Update L530 aes fixture (#603) 2024-01-02 18:49:52 +01:00
Teemu R
5dafc1d1ed
Cleanup custom exception kwarg handling (#602)
* Cleanup custom exceptions

* Read custom keyword arguments from kwargs
* Pass all input args to the super

Earlier behavior:
Got error: AuthenticationException((('Error logging in: 192.168.xx.xx: LOGIN_ERROR(-1501)',), <SmartErrorCode.LOGIN_ERROR: -1501>))

New behavior:
Got error: AuthenticationException('Error logging in: 192.168.xx.xx: LOGIN_ERROR(-1501)')

* Pass UnsupportedDeviceException kwargs to parent, too
2024-01-02 16:24:09 +01:00
sdb9696
7646bc4542
Update P110(UK) fixture (#596) 2023-12-31 15:36:15 +01:00
sdb9696
fd9b3cd04c
Add L530(EU) klap fixture (#598) 2023-12-31 15:35:43 +01:00
sdb9696
1b7914277d
Fix dump_devinfo for unauthenticated (#593) 2023-12-29 20:42:02 +01:00
sdb9696
f6fd898faf
Add DeviceConfig to allow specifying configuration parameters (#569)
* Add DeviceConfig handling

* Update post review

* Further update post latest review

* Update following latest review

* Update docstrings and docs
2023-12-29 20:17:15 +01:00
Teemu R
1d5a9c35f4
Elevate --verbose to top-level option (#590)
* Elevate --verbose to be usable for all commands

* Fix tests
2023-12-29 16:04:41 +01:00
sdb9696
b66347116f
Add optional error code to exceptions (#585) 2023-12-20 20:16:23 +01:00
sdb9696
6819c746d7
Enable multiple requests in smartprotocol (#584)
* Enable multiple requests in smartprotocol

* Update following review

* Remove error_code parameter in exceptions
2023-12-20 18:08:04 +01:00
sdb9696
20ea6700a5
Do login entirely within AesTransport (#580)
* Do login entirely within AesTransport

* Remove login and handshake attributes from BaseTransport

* Add AesTransport tests

* Synchronise transport and protocol __init__ signatures and rename internal variables

* Update after review
2023-12-19 15:11:59 +01:00
sdb9696
209391c422
Improve CLI Discovery output (#583)
- Show discovery results for unsupported devices and devices that fail to authenticate.
- Rename `--show-unsupported` to `--verbose`.
- Remove separate `--timeout` parameter from cli discovery so it's not confused with `--timeout` now added to cli command.
- Add tests.
2023-12-19 13:50:33 +01:00
sdb9696
2e6c41d039
Improve smartprotocol error handling and retries (#578)
* Improve smartprotocol error handling and retries

* Update after review

* Enum to IntEnum and SLEEP_SECONDS_AFTER_TIMEOUT
2023-12-10 16:41:53 +01:00
Teemu R
a77af5fb3b
Request component_nego only once for tapodevice (#576)
Optimizes the update cycle a bit, as it's doubtful the components change over time
2023-12-10 00:32:30 +01:00
Teemu R
35a452168a
Log smartprotocol requests (#575)
* Log smartprotocol requests

Also, comment out encrypted secure_passthrough response for the time being

* Fix linting
2023-12-08 15:22:58 +01:00
Teemu R
1e2241ee95
Fix hsv setting for tapobulb (#573)
This fixes changing the color for L530:
* If color temp is set on the device, it overrides any hue/sat settings. We override it to zero which seems to work.
* L530 does not allow None/null for brightness, so we avoid passing it on to the device.
2023-12-08 15:16:45 +01:00
sdb9696
16ba87378d
Add EP25 smart fixture and improve test framework for SMART devices (#572) 2023-12-08 14:55:14 +01:00
sdb9696
b27a31a8a9
Add new methods to dump_devinfo and mask aliases (#574) 2023-12-08 14:29:07 +01:00
Steven Bytnar
be289a5751
Add KP125M fixture and allow passing credentials for tests (#567)
* Add KP125M fixture. Enable tapo auth in pytest.

* authentication is not just for tapo

* Use "##MASKEDNAME##" base64 for nickname and ssid.

---------

Co-authored-by: Teemu R. <tpr@iki.fi>
2023-12-08 00:04:50 +01:00
Teemu R
8cdd4f59f8
Use consistent naming for cli envvars (#570)
* Use consistent naming for cli envvars

* Fix linting
2023-12-05 23:20:29 +01:00
Teemu R
f9b5003da2
Add support for tapo bulbs (#558)
* Add support for tapo light bulbs

* Use TapoDevice for on/off

* Add tapobulbs to discovery

* Add partial support for effects

Activating the effect does not work as I thought it would,
but this implements rest of the interface from SmartLightStrip.

* Add missing __init__ for tapo package

* Make mypy happy

* Add docstrings to make ruff happy

* Implement state_information and has_emeter

* Import tapoplug from kasa.tapo package

* Add tapo L530 fixture

* Enable tests for L530 fixture

* Make ruff happy

* Update fixture filename

* Raise exceptions on invalid parameters

* Return results in a wrapped dict

* Implement set_*

* Reorganize bulbs to iot&smart, fix tests for smarts

* Fix linting

* Fix BULBS_LIGHT_STRIP back to LIGHT_STRIPS
2023-12-05 20:07:10 +01:00
Teemu R
5febd300ca
Add P110 fixture (#562)
* Add P110 fixture

* Move the fixture file to smart subdir

* Update fixture to have the region info

* Rename the fixture file to follow the convention
2023-12-05 16:58:25 +01:00
sdb9696
5e2fcd2cca
Re-add regional suffix to TAPO/SMART fixtures (#566) 2023-12-05 16:45:09 +01:00
sdb9696
01f3827d73
Fix transport retries after close (#568) 2023-12-05 15:56:29 +01:00
sdb9696
4a00199506
Add klap support for TAPO protocol by splitting out Transports and Protocols (#557)
* Add support for TAPO/SMART KLAP and seperate transports from protocols

* Add tests and some review changes

* Update following review

* Updates following review
2023-12-04 19:50:05 +01:00
Teemu R
347cbfe3bd
Make timeout configurable for cli (#564) 2023-12-04 16:44:27 +01:00
Steven Bytnar
bfd1d6ae0a
Kasa KP125M basic emeter support (#560)
* Add KP125M basic emeter support.

* Reduce diff.

* PR Comments
2023-12-03 15:41:46 +01:00
sdb9696
a6b7d73d79
Update dump_devinfo to produce new TAPO/SMART fixtures (#561) 2023-12-02 17:33:35 +01:00
sdb9696
63d64ad920
Add support for the protocol used by TAPO devices and some newer KASA devices. (#552)
* Add Tapo protocol support

* Update get_device_instance and test_unsupported following review
2023-11-30 13:10:49 +01:00
sdb9696
9de3f69033
Update dump_devinfo to include 20002 discovery results (#556)
* Fix dump_devinfo and add discovery_result to json

* Update following review.  Do not serialize aliases.

* Delete kasa/tests/fixtures/HS100(UK)_1.0_1.2.6.json
2023-11-29 20:01:20 +01:00
sdb9696
9728866afb
Re-add protocol_class parameter to connect (#551)
Co-authored-by: J. Nick Koston <nick@koston.org>
2023-11-28 20:13:15 +01:00
J. Nick Koston
d3c2861e4a
Set TCP_NODELAY to avoid needless buffering (#554) 2023-11-27 09:25:49 -06:00
J. Nick Koston
e98252ff17
Move connect_single to SmartDevice.connect (#538)
This refactors `Discover.connect_single` by moving device instance construction into a separate device factory module.
New `SmartDevice.connect(host, *, port, timeout, credentials, device_type)` class method replaces the functionality of `connect_single`,
and also now allows constructing device instances without relying on UDP discovery for type discovery if `device_type` parameter is set.

---------

Co-authored-by: Teemu R. <tpr@iki.fi>
2023-11-21 23:48:53 +01:00
sdb9696
27c4799adc
Do not do update() in discover_single (#542) 2023-11-21 21:58:41 +01:00
sdb9696
30f217b8ab
Add klap protocol (#509)
* Add support for the new encryption protocol

This adds support for the new TP-Link discovery and encryption
protocols. It is currently incomplete - only devices without
username and password are current supported, and single device
discovery is not implemented.

Discovery should find both old and new devices. When accessing
a device by IP the --klap option can be specified on the command
line to active the new connection protocol.

sdb9696 - This commit also contains 16 later commits from Simon Wilkinson
squashed into the original

* Update klap changes 2023 to fix encryption, deal with kasa credential switching and work with new discovery changes

* Move from aiohttp to httpx

* Changes following review comments

---------

Co-authored-by: Simon Wilkinson <simon@sxw.org.uk>
2023-11-20 14:17:10 +01:00
sdb9696
26502982a0
Update discover single to handle hostnames (#539) 2023-11-07 02:15:41 +01:00
Teemu R
c431dbb832
Use ruff and ruff format (#534)
Replaces the previously used linting and code formatting tools with ruff.
2023-10-29 23:15:42 +01:00
Teemu R
af37e83db1
Fix on_since for smartstrip sockets (#529) 2023-10-16 19:37:55 +02:00
J. Nick Koston
85c8410c3d
Add a connect_single method to Discover to avoid the need for UDP (#528)
This should equate to a significant reliability improvement for networks with poor wifi (edge of range)/udp.
2023-10-08 02:29:22 +02:00
J. Nick Koston
528f5e9e07
Remove code to detect event loop change (#526)
The code should always be called from the same thread that
created the object or we have a thread safety problem.
2023-10-08 00:36:51 +02:00
J. Nick Koston
9930311b54
Parse features only during updates (#527)
Every time emeter functions were called features had to be re-parsed. For power strips, thats a lot of re-parses. Only parse them when we update.
2023-10-07 21:18:47 +02:00
J. Nick Koston
0ec0826cc7
Make timeout adjustable (#494) 2023-10-07 20:58:00 +02:00
J. Nick Koston
20b3f7a771
Fix every other query tries to fetch known unsupported features (#520)
* Fix every other query tries to fetch known unsupported features

* ensure modules not being updated are preserved
2023-10-05 22:50:54 +02:00
Teemu R
84a501bcdc
Show an error if both --alias and --host are defined (#513)
Display an error if both --alias and --host are defined to avoid ambiguous target device:
```
❯ kasa --host 123 --alias 123 state
Usage: kasa [OPTIONS] COMMAND [ARGS]...
Try 'kasa --help' for help.

Error: Use either --alias or --host, not both.
```

Also, use `click.BadOptionUsage` consistently for other errors, like when only `--username` or `--password` is given.
2023-10-04 23:35:26 +02:00
cobryan05
a2444da9df
Split queries to avoid overflowing device buffers (#502)
Several KASA devices seem to have pretty strict buffer size limitations on incoming/outgoing data transfers.

Testing on KL125-US and HL103 has shown that sending a request size larger than about ~768 bytes will immediately crash the device. Additionally, a query that generates a response larger than ~4096 bytes will crash the KL125-US. I was unable to generate such a large response to test the HL103.

The KL125-US will only return such large queries when its monthly usage stats have been populated. This means that a new bulb would work fine, but after a month of data collection the bulb would break the 4K limit and start to crash.

To work around this issue, an estimated worst-case response size is calculated before sending a request by summing up all modules estimated response size. If the estimated size is greater than the device's max_response_payload_size then the query will be split into multiple queries.

This PR implements splitting queries expected to have large responses and also removes the module 'skip list' which was a previous workaround to the crash (which worked by simply reducing the number of modules queried, which prevented the overflow) since it is no longer necessary.

This PR does not attempt to address the "input buffer size limit." Thus far this limit has not been an issue.
2023-09-14 20:51:40 +02:00
sdb9696
7bb4a456a2
Add plumbing for passing credentials to devices (#507)
* Add plumbing for passing credentials as far as discovery

* Pass credentials to Smart devices

* Rename authentication exception

* Fix tests failure due to test_json_output leaving echo as nop

* Fix test_credentials test

* Do not print credentials, fix echo function bug and improve get type parameter

* Add device class constructor test

* Add comment for echo handling and move assignment
2023-09-13 15:46:38 +02:00
sdb9696
6055c29d74
Add support for alternative discovery protocol (20002/udp) (#488)
This will broadcast the new discovery message on the new port and log any responses received as unsupported devices.
2023-08-29 15:04:28 +02:00
Teemu R
53021f07fe
Add support for pydantic v2 using v1 shims (#504) 2023-08-28 17:48:49 +02:00
Norman Rasmussen
4b99351dd6
Add toggle command to cli (#498) 2023-08-26 14:21:38 +02:00
sdb9696
064e3fe560
Add discovery timeout parameter (#486)
* Add discovery timeout parameter

* Rename variable to be more pythonic
2023-08-03 14:24:46 +02:00
sdb9696
176ced9e6e
Add new HS100(UK) fixture (#489) 2023-08-03 13:20:09 +02:00
J. Nick Koston
677ef9c3ef
Add tests for KP200 (#483)
* Add tests for KP200

This one worked out of the box sans the OUI not being in the list

https://github.com/home-assistant/core/pull/97062

* it is a strip
2023-07-22 23:55:42 +02:00
J. Nick Koston
117a7ac64a
Replace asyncio.wait_for with async-timeout (#480)
asyncio.wait_for has some underlying problems that are only fixed in cpython 3.12.

Use async_timeout instead until the minimum supported version is 3.11+ and it can be replaced with asyncio.timeout

See https://github.com/python/cpython/pull/98518
2023-07-21 11:50:54 +02:00
Viktar Karpach
9b039d8374
Make device port configurable (#471) 2023-07-10 01:55:27 +02:00
xinud190
b83986bd51
Add fixture for KP405 Smart Dimmer Plug (#470)
* Add files via upload

* Add to KP405 to dimmers, update README

---------

Co-authored-by: Teemu Rytilahti <tpr@iki.fi>
2023-06-30 02:53:23 +02:00
J. Nick Koston
afd54d11d3
Add optional kasa-crypt dependency for speedups (#464)
If installed, use the optimized protocol encryption procedures implemented as a C extension by kasa-crypt (https://pypi.org/project/kasa-crypt/
2023-06-30 02:43:01 +02:00
J. Nick Koston
2d42ca301f
Use orjson when already installed or with speedups extra (#466)
* Use orjson when already installed

* Use orjson when already installed

* fix patch target

* fix patch target

* add speedups extra

* Update README.md

* Update README.md
2023-06-18 01:03:04 +02:00
Brian Davis
9550cbd2f7
Exclude querying certain modules for KL125(US) which cause crashes (#451)
* commented out modules that break

* added exclusion logic to smartdevice.py

* cleaning up a name

* removing test fixture that isn't related to this PR

* incorporating PR feedback

* fixed an if statement

* reduced exclusion list to just 'cloud'

* Tidy up the issue comment

Co-authored-by: Teemu R. <tpr@iki.fi>

* this seems to be what the linter whats

---------

Co-authored-by: Teemu R. <tpr@iki.fi>
2023-05-18 17:04:24 +02:00
Teemu R
39310f3f02
Remove importlib-metadata dependency (#457)
This is no longer needed, as python 3.8 has native importlib.metadata
2023-05-17 20:33:02 +02:00
Teemu R
ce58cc1a6a
Add methods to configure dimmer settings (#429) 2023-05-17 20:10:39 +02:00
Teemu R
18ce40b6bb
Add inactivity setting for the motion module (#453)
* Add inactivity setting for the motion module

* Fix set_cold_time payload

Co-authored-by: Matt Whitlock <whitslack@users.noreply.github.com>

* Add mention about "smart control"

---------

Co-authored-by: Matt Whitlock <whitslack@users.noreply.github.com>
2023-05-17 20:08:05 +02:00
Teemu R
ce5821a35f
Drop python 3.7 support (#455)
* Drop python 3.7 support

* CI: drop 3.7 and add 3.11

* Remove skipifs that were required for <3.8

* Use pypy-3.8 for CI, re-enable pypy for windows to see if it works now

* Bump readthedocs to use py3.8

* Remove py3.7 failure comment
2023-05-17 20:03:08 +02:00
Teemu R
233f1c9534
Cleanup fixture filenames (#448)
* Mark mocked fixtures as such

* Use consistent filenames including the swver

* Remove executable bit

* Remove duplicate KL130(US)

* Remove unnecessary mocks where we have real ones available

* Fix filenames in tests
2023-04-01 17:10:46 +02:00
Teemu R
505b63dd55
Allow effect presets seen on light strips (#440)
* Make hue, saturation and color_temp optional for smartbulbpresets

* Adjust bulb preset attributes for effect mode

* Don't send None values on save_preset

* Add tests for save_preset payloads
2023-04-01 16:15:58 +02:00
Teemu R
4d514f983b
Return result objects for cli discover and implicit 'state' (#446)
This will make --json to output relevant contents even when no command is defined (i.e., when calling 'kasa --host <host> --json' or 'kasa --target <bcast> --json'.
2023-03-30 01:53:38 +02:00
Teemu R
02c857d472
Some release preparation janitoring (#432)
* Use myst-parser for readme.md doc injection

* Relax version pins

* Define bug tracker and doc links for pypi

* Update pre-commit hooks
2023-02-18 22:09:35 +01:00
Teemu R
016f4dfd19
Add support for json output (#430)
* Add json support

* Add tests

* Check if test_json_output works on ci using py3.8+

* Add a proper note why py3.7 test for json_output are disabled
2023-02-18 21:41:08 +01:00
Teemu R
1212715dde
Minor fixes to smartbulb docs (#431) 2023-02-18 21:17:19 +01:00
Julian Davis
43ed47eca8
Return usage.get_{monthstat,daystat} in expected format (#394)
* Basic fix for issue: https://github.com/python-kasa/python-kasa/issues/373
Change usage module get_daystat and get_monthat to return dictionaries of date index: time values as spec'd instead of raw usage data. Output matches emeter module get_daystat and get_monthstat

* Fixed some formatting and lint warnings to comply with black/flake8
Use the new _convert function in emeter for all conversions rather than the one in smartdevice.py
Removed unused function _emeter_convert_emeter_data from smartdevice.py

* Added a first pass test module for testing the new usage conversion function

* Changes based on PR feedback
Tidied up some doc string comments
Added a check for explicit values from conversion function

* Rebase on top of current master, fix docstrings

---------

Co-authored-by: Teemu Rytilahti <tpr@iki.fi>
2023-02-18 20:53:02 +01:00
Teemu R
12c98eb58d
Add transition parameter to lightstrip's set_effect (#416) 2023-02-18 18:03:54 +01:00
Teemu R
92636fe82d
Pretty-print all exceptions from cli commands (#428)
Print out the repr of captured exception instead of full traceback
2023-02-18 17:32:03 +01:00
Teemu R
dd044130d4
Use rich for prettier output, if available (#403)
Use rich for prettier output, if available.

This does not add a new dependency, but rather uses rich if it's installed.
2023-02-18 17:31:06 +01:00
Teemu R
6e7a588d40
Add brightness to lightstrip's set_effect (#415)
* Add brightness parameter to lightstrip's set_effect

* Use None as default as effects have different default brightnesses
2023-01-21 00:25:59 +01:00
Teemu R
327efb6c65
Update pre-commit hooks (#401)
* Update pre-commit hooks

* Fix implicit optionals
2022-11-15 19:05:08 +01:00
Julian Davis
866c8d6db5
Fix pytest warnings about asyncio (#397)
Turn on ayncio auto mode for pytest and remove the global async marking flag
2022-11-13 23:34:47 +01:00
Teemu R
9cb2a56405
Add a note that transition is not supported by all devices (#398) 2022-11-11 21:06:54 +01:00
Aric Forrest
ec06331737
Adding cli command to delete a schedule rule (#391)
* adding cli option to delete rule

* resolving black linting issue

* simplifying command name

Co-authored-by: Teemu R. <tpr@iki.fi>

* updating rule filter

Co-authored-by: Teemu R. <tpr@iki.fi>
2022-11-03 02:11:24 +01:00
Teemu R
ef98c2aed9
Implement changing the bulb turn-on behavior (#381)
* Implement changing the bulb turn-on behavior

* Improve docstrings a bit

* Improve docs and expose TurnOnBehavior(s)

* fix typing
2022-10-27 17:40:54 +02:00
Julian Davis
1ac6c66277
Fix type hinting issue with call to click.Choice (#387)
* Fix type hinting issue with call to click.Choice which takes a Sequence not dictionary. Convert TYPE_TO_CLASS keys to a list to pass in.

* Update kasa/cli.py

Co-authored-by: Teemu R. <tpr@iki.fi>

Co-authored-by: Jules Davis <jules@focalpointvr.com>
Co-authored-by: Teemu R. <tpr@iki.fi>
2022-10-27 17:40:24 +02:00
Teemu R
f32f7f3925
Add support for bulb presets (#379)
* Add support for bulb presets

* Update docs
2022-10-23 00:15:47 +02:00
Teemu R
13052ac7a1
Fix year emeter for cli by using kwarg for year parameter (#372)
* Fix year emeter for cli by using kwarg for year parameter

* Improve tests

* Skip test_emeter on python3.7
2022-10-03 20:28:05 +02:00
Felix Yan
7aebef56ca
Correct typos in smartdevice.py (#358) 2022-07-17 19:19:09 +02:00
gritstub
57fac9a156
Add fixtures for KS200M (#356) 2022-06-28 18:53:23 +02:00
gritstub
d7295bdf6d
Add fixtures for ES20M (#353) (#354)
Co-authored-by: Teemu R <tpr@iki.fi>
2022-06-28 13:06:34 +02:00
gritstub
4c55289255
Add fixtures for KS230 (#355) 2022-06-28 12:56:36 +02:00
James Alseth
91ba1d5ac6
Add KP125 test fixture and support note. (#350)
* Add KP125 test fixture and support note.

Signed-off-by: James Alseth <james@jalseth.me>

* mark KP125 having an emeter

Co-authored-by: Teemu R <tpr@iki.fi>
2022-06-27 03:39:57 +02:00
J. Nick Koston
8e6cfd003e
Add fixtures for KP100 (#343)
* Add fixtures for KP100

* readme
2022-05-11 16:02:17 +02:00
J. Nick Koston
d908a5ab2a
Avoid retrying open_connection on unrecoverable errors (#340)
* Avoid retrying open_connection on unrecoverable errors

- We can retry so hard that we block the event loop

Fixes
```
2022-04-16 22:18:51 WARNING (MainThread) [asyncio] Executing <Task finished name=Task-3576 coro=<open_connection() done, defined at /opt/homebrew/Cellar/python@3.9/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/streams.py:25> exception=ConnectionRefusedError(61, "Connect call failed (192.168.107.200, 9999)") created at /opt/homebrew/Cellar/python@3.9/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/tasks.py:460> took 1.001 seconds
```

* comment
2022-04-24 19:38:42 +02:00
J. Nick Koston
d2581bf077
Add fixtures for kl420 (#339)
* Add fixtures for kl420

* readme
2022-04-14 02:51:15 +02:00
Teemu R
631762b50c
Drop deprecated, type-specific options in favor of --type (#336)
* Drop deprecated, type-specific options in favor of --type

* Fix tests
2022-04-06 03:39:50 +02:00
Teemu R
6e988bd9a9
Avoid discovery on --help (#335) 2022-04-06 02:25:47 +02:00
Teemu R
a39cef9a8c
Export modules & make sphinx happy (#334) 2022-04-06 01:41:08 +02:00
Teemu Rytilahti
2a0919efd5 Fix linting 2022-04-05 19:27:46 +02:00
J. Nick Koston
1e4df7ec1b Fix modularize with strips (#326)
* Fix test_deprecated_type stalling

* Fix strips with modularize

* Fix test_deprecated_type stalling (#325)
2022-04-05 19:27:46 +02:00
Teemu Rytilahti
f0d66e4195 move get_time{zone} out from smartdevice + some minor cleanups 2022-04-05 19:27:46 +02:00
Teemu Rytilahti
c8ad99abcb Use device time for on_since for smartstripplugs 2022-04-05 19:27:46 +02:00
Teemu Rytilahti
bb013e75da Raise an exception when trying to access data prior updating 2022-04-05 19:27:46 +02:00
Teemu R
3a7836cd33 Do not request unsupported modules after the initial update (#298)
* Do not request unsupported modules after the initial update

* debugify logging
2022-04-05 19:27:46 +02:00
Teemu R
8c7b1b4a68 Implement motion & ambient light sensor modules for dimmers (#278) 2022-04-05 19:27:46 +02:00
Teemu R
e3588047fc Improve usage module, consolidate API with emeter (#249)
* Consolidate API for both emeter&usage modules
* Add new cli command 'usage' to query usage
2022-04-05 19:27:46 +02:00
Teemu R
3926f3224f Add module support & query their information during update cycle (#243)
* Add module support & modularize existing query

This creates a base to expose more features on the supported devices.
At the moment, the most visible change is that each update cycle gets information from all available modules:
* Basic system info
* Cloud (new)
* Countdown (new)
* Antitheft (new)
* Schedule (new)
* Time (existing, implements the time/timezone handling)
* Emeter (existing, partially separated from smartdevice)

* Fix imports

* Fix linting

* Use device host instead of alias in module repr

* Add property to list available modules, print them in cli state report

* usage: fix the get_realtime query

* separate usage from schedule to avoid multi-inheritance

* Fix module querying

* Add is_supported property to modules
2022-04-05 19:27:46 +02:00
J. Nick Koston
766819a2a4
Ensure bulb state is restored when turning back on (#330)
* Ensure state is restored when turning back on

Fixes https://github.com/home-assistant/core/issues/69039

* Update kasa/tests/test_bulb.py

Co-authored-by: Teemu R. <tpr@iki.fi>

Co-authored-by: Teemu R. <tpr@iki.fi>
2022-04-05 18:51:36 +02:00
J. Nick Koston
2b05751aa7
Fix test_deprecated_type stalling (#325) 2022-03-24 23:59:53 +01:00
J. Nick Koston
58f6517445
Add effect support for light strips (#293)
* Add effect support for KL430

* KL400 supports effects

* Add KL400 fixture

* Comments from review

* actually commit the remove
2022-03-21 22:10:12 +01:00
Teemu R
b22f6b4eef
Don't crash on devices not reporting features (#317)
Returns an empty set if no feature information is available
2022-03-02 16:29:20 +01:00
Teemu R
db170cf1f5
Allow using environment variables for discovery target, device type and debug (#313)
* KASA_TYPE defines the device type (bulb, plug, dimmer, strip, lightstrip)
* KASA_TARGET to define discovery target
* KASA_DEBUG to enable debugging
2022-02-15 16:59:36 +01:00
Teemu R
b61c0feea9
Add 'internal_state' to return the results from the last update query (#306)
This can be useful for debugging purposes, e.g., for homeassistant diagnostics
2022-02-07 09:13:47 +01:00
Teemu R
700f3859c2
Guard emeter accesses to avoid keyerrors (#304)
Raise an exception to inform the caller that update() is needed
2022-02-02 19:31:11 +01:00
Teemu R
9ea83388ac
cli: cleanup discover, fetch update prior device access (#303)
* Use on_discovered for smoother user experience
* Remove --discover-only as unnecessary
2022-02-02 19:30:48 +01:00
J. Nick Koston
c865d3f02c
Fix unsafe __del__ in TPLinkSmartHomeProtocol (#300)
* Fix unsafe __del__ in TPLinkSmartHomeProtocol

Fixes
```
Exception ignored in: <function TPLinkSmartHomeProtocol.__del__ at 0x1096d0670>
Traceback (most recent call last):
  File "/Users/bdraco/home-assistant/venv/lib/python3.9/site-packages/kasa/protocol.py", line 159, in __del__
    self.writer.close()
  File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/streams.py", line 353, in close
    return self._transport.close()
  File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/selector_events.py", line 700, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 748, in call_soon
    self._check_thread()
  File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 785, in _check_thread
    raise RuntimeError(
RuntimeError: Non-thread-safe operation invoked on an event loop other than the current one
```

* comment

* comment

* comment
2022-01-30 23:00:00 +01:00
mrbetta
5bf6fda7ee
Added a fixture file for KS220M (#273)
* Added motion and light sensor for KS220M

* Added fixture file for ks220m

* Remove dump_devinfo and add the extra queries to devtools/dump_devinfo

* Test KS220M as a dimmer

* Add empty modules to baseproto to make the tests pass

Co-authored-by: mrbetta <bettale@gmail.com>
Co-authored-by: Teemu Rytilahti <tpr@iki.fi>
2022-01-29 18:28:14 +01:00
Teemu R
6a31de5381
Drop microsecond precision for on_since (#296) 2022-01-29 17:02:05 +01:00
Teemu R
bcb9fe18ab
Improve typing for protocol class (#289) 2022-01-14 23:08:25 +01:00
Teemu R
6ece506a3b
Relax asyncclick version requirement (#286)
* Add package_name to version_option(), breaks --version on click < 8
2022-01-14 16:32:32 +01:00
Teemu R
723fca9d08
Do not crash on discovery on WSL (#283) 2022-01-08 17:48:01 +01:00
Teemu R
a817d9cab1
Add python 3.10 to CI (#279)
* Add python 3.10 to CI

* Require pytest >=6.2.5

Required for running on python 3.10 (https://github.com/pytest-dev/pytest/pull/8540)

* Update lockfile

* Update pre-commit hooks
2021-12-17 17:48:03 +01:00
Teemu R
d2efaf5090
Add --type option to cli (#269)
* Add support for controlling dimmers
* Deprecate --bulb, --plug, --strip, --lightstrip
2021-12-13 20:17:54 +01:00