Bulbs

Supported features

  • Turning on and off

  • Setting brightness, color temperature, and color (in HSV)

  • Querying emeter information

  • Transitions

  • Presets

Currently unsupported

  • Setting the default transitions

  • Timers

Note

Feel free to open a pull request to add support for more features!

Transitions

All commands changing the bulb state can be accompanied with a transition, e.g., to slowly fade the light off. The transition time is in milliseconds, 0 means immediate change. If no transition value is given, the default setting as configured for the bulb will be used.

Note

Accepted values are command (and potentially bulb) specific, feel free to improve the documentation on accepted values.

Example: While KL130 allows at least up to 15 second transitions for smooth turning off transitions, turning it on will not be so smooth.

Command-line usage

All command-line commands can be used with transition period for smooth changes.

Example: Turn the bulb off over a 15 second time period.

$ kasa --type bulb --host <host> off --transition 15000

Example: Change the bulb to red with 20% brightness over 15 seconds:

$ kasa --type bulb --host <host> hsv 0 100 20 --transition 15000

API documentation

class kasa.SmartBulb(host: str, *, config: Optional[DeviceConfig] = None, protocol: Optional[BaseProtocol] = None)[source]

Representation of a TP-Link Smart Bulb.

To initialize, you have to await update() at least once. This will allow accessing the properties using the exposed properties.

All changes to the device are done using awaitable methods, which will not change the cached values, so you must await update() to fetch updates values from the device.

Errors reported by the device are raised as SmartDeviceExceptions, and should be handled by the user of the library.

Examples:
>>> import asyncio
>>> bulb = SmartBulb("127.0.0.1")
>>> asyncio.run(bulb.update())
>>> print(bulb.alias)
Bulb2

Bulbs, like any other supported devices, can be turned on and off:

>>> asyncio.run(bulb.turn_off())
>>> asyncio.run(bulb.turn_on())
>>> asyncio.run(bulb.update())
>>> print(bulb.is_on)
True

You can use the is_-prefixed properties to check for supported features:

>>> bulb.is_dimmable
True
>>> bulb.is_color
True
>>> bulb.is_variable_color_temp
True

All known bulbs support changing the brightness:

>>> bulb.brightness
30
>>> asyncio.run(bulb.set_brightness(50))
>>> asyncio.run(bulb.update())
>>> bulb.brightness
50

Bulbs supporting color temperature can be queried for the supported range:

>>> bulb.valid_temperature_range
ColorTempRange(min=2500, max=9000)
>>> asyncio.run(bulb.set_color_temp(3000))
>>> asyncio.run(bulb.update())
>>> bulb.color_temp
3000

Color bulbs can be adjusted by passing hue, saturation and value:

>>> asyncio.run(bulb.set_hsv(180, 100, 80))
>>> asyncio.run(bulb.update())
>>> bulb.hsv
HSV(hue=180, saturation=100, value=80)

If you don’t want to use the default transitions, you can pass transition in milliseconds. All methods changing the state of the device support this parameter:

Light strips (e.g., KL420L5) do not support this feature, but silently ignore the parameter. The following changes the brightness over a period of 10 seconds:

>>> asyncio.run(bulb.set_brightness(100, transition=10_000))

Bulb configuration presets can be accessed using the presets() property:

>>> bulb.presets
[SmartBulbPreset(index=0, brightness=50, hue=0, saturation=0, color_temp=2700, custom=None, id=None, mode=None), SmartBulbPreset(index=1, brightness=100, hue=0, saturation=75, color_temp=0, custom=None, id=None, mode=None), SmartBulbPreset(index=2, brightness=100, hue=120, saturation=75, color_temp=0, custom=None, id=None, mode=None), SmartBulbPreset(index=3, brightness=100, hue=240, saturation=75, color_temp=0, custom=None, id=None, mode=None)]

To modify an existing preset, pass SmartBulbPreset instance to save_preset() method:

>>> preset = bulb.presets[0]
>>> preset.brightness
50
>>> preset.brightness = 100
>>> asyncio.run(bulb.save_preset(preset))
>>> bulb.presets[0].brightness
100
LIGHT_SERVICE = 'smartlife.iot.smartbulb.lightingservice'
SET_LIGHT_METHOD = 'transition_light_state'
add_module(name: str, module: Module)

Register a module.

property alias: Optional[str]

Return device name (alias).

property brightness: int

Return the current brightness in percentage.

property color_temp: int

Return color temperature of the device in kelvin.

property config: DeviceConfig

Return the device configuration.

async static connect(*, host: Optional[str] = None, config: Optional[DeviceConfig] = None) SmartDevice

Connect to a single device by the given hostname or device configuration.

This method avoids the UDP based discovery process and will connect directly to the device.

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

Parameters:
  • host – Hostname of device to query

  • config – Connection parameters to ensure the correct protocol and connection options are used.

Return type:

SmartDevice

Returns:

Object for querying/controlling found device.

property credentials: Optional[Credentials]

The device credentials.

property credentials_hash: Optional[str]

The protocol specific hash of the credentials the device is using.

async current_consumption() float

Get the current power consumption in Watt.

property device_id: str

Return unique ID for the device.

If not overridden, this is the MAC address of the device. Individual sockets on strips will override this.

property device_type: DeviceType

Return the device type.

async disconnect()

Disconnect and close any underlying connection resources.

property emeter_realtime: EmeterStatus

Return current energy readings.

property emeter_this_month: Optional[float]

Return this month’s energy consumption in kWh.

property emeter_today: Optional[float]

Return today’s energy consumption in kWh.

emeter_type = 'smartlife.iot.common.emeter'
async erase_emeter_stats() Dict

Erase energy meter statistics.

property features: Set[str]

Return a set of features that the device supports.

async get_emeter_daily(year: Optional[int] = None, month: Optional[int] = None, kwh: bool = True) Dict

Retrieve daily statistics for a given month.

Parameters:
  • year – year for which to retrieve statistics (default: this year)

  • month – month for which to retrieve statistics (default: this month)

  • kwh – return usage in kWh (default: True)

Returns:

mapping of day of month to value

async get_emeter_monthly(year: Optional[int] = None, kwh: bool = True) Dict

Retrieve monthly statistics for a given year.

Parameters:
  • year – year for which to retrieve statistics (default: this year)

  • kwh – return usage in kWh (default: True)

Returns:

dict: mapping of month to value

async get_emeter_realtime() EmeterStatus

Retrieve current energy readings.

async get_light_details() Dict[str, int][source]

Return light details.

Example:

{'lamp_beam_angle': 290, 'min_voltage': 220, 'max_voltage': 240,
 'wattage': 5, 'incandescent_equivalent': 40, 'max_lumens': 450,
  'color_rendering_index': 80}
async get_light_state() Dict[str, Dict][source]

Query the light state.

get_plug_by_index(index: int) SmartDevice

Return child device for the given index.

get_plug_by_name(name: str) SmartDevice

Return child device for the given name.

async get_sys_info() Dict[str, Any]

Retrieve system information.

async get_time() Optional[datetime]

Return current time from the device, if available.

async get_timezone() Dict

Return timezone information.

async get_turn_on_behavior() TurnOnBehaviors[source]

Return the behavior for turning the bulb on.

property has_children: bool

Return true if the device has children devices.

property has_effects: bool

Return True if the device supports effects.

property has_emeter: bool

Return that the bulb has an emeter.

property host: str

The device host.

property hsv: HSV

Return the current HSV state of the bulb.

Returns:

hue, saturation and value (degrees, %, %)

property hw_info: Dict

Return hardware information.

This returns just a selection of sysinfo keys that are related to hardware.

property internal_state: Any

Return the internal state of the instance.

The returned object contains the raw results from the last update call. This should only be used for debugging purposes.

property is_bulb: bool

Return True if the device is a bulb.

property is_color: bool

Whether the bulb supports color changes.

property is_dimmable: bool

Whether the bulb supports brightness changes.

property is_dimmer: bool

Return True if the device is a dimmer.

property is_light_strip: bool

Return True if the device is a led strip.

property is_off: bool

Return True if device is off.

property is_on: bool

Return whether the device is on.

property is_plug: bool

Return True if the device is a plug.

property is_strip: bool

Return True if the device is a strip.

property is_strip_socket: bool

Return True if the device is a strip socket.

property is_variable_color_temp: bool

Whether the bulb supports color temperature changes.

property light_state: Dict[str, str]

Query the light state.

property location: Dict

Return geographical location.

property mac: str

Return mac address.

Returns:

mac address in hexadecimal with colons, e.g. 01:23:45:67:89:ab

property max_device_response_size: int

Returns the maximum response size the device can safely construct.

property model: str

Return device model.

property on_since: Optional[datetime]

Return pretty-printed on-time, or None if not available.

property port: int

The device port.

property presets: List[SmartBulbPreset]

Return a list of available bulb setting presets.

async reboot(delay: int = 1) None

Reboot the device.

Note that giving a delay of zero causes this to block, as the device reboots immediately without responding to the call.

property rssi: Optional[int]

Return WiFi signal strength (rssi).

async save_preset(preset: SmartBulbPreset)[source]

Save a setting preset.

You can either construct a preset object manually, or pass an existing one obtained using presets().

async set_alias(alias: str) None[source]

Set the device name (alias).

Overridden to use a different module name.

async set_brightness(brightness: int, *, transition: Optional[int] = None) Dict[source]

Set the brightness in percentage.

Parameters:
  • brightness (int) – brightness in percent

  • transition (int) – transition in milliseconds.

async set_color_temp(temp: int, *, brightness=None, transition: Optional[int] = None) Dict[source]

Set the color temperature of the device in kelvin.

Parameters:
  • temp (int) – The new color temperature, in Kelvin

  • transition (int) – transition in milliseconds.

async set_hsv(hue: int, saturation: int, value: Optional[int] = None, *, transition: Optional[int] = None) Dict[source]

Set new HSV.

Parameters:
  • hue (int) – hue in degrees

  • saturation (int) – saturation in percentage [0,100]

  • value (int) – value in percentage [0, 100]

  • transition (int) – transition in milliseconds.

async set_light_state(state: Dict, *, transition: Optional[int] = None) Dict[source]

Set the light state.

async set_mac(mac)

Set the mac address.

Parameters:

mac (str) – mac in hexadecimal with colons, e.g. 01:23:45:67:89:ab

async set_turn_on_behavior(behavior: TurnOnBehaviors)[source]

Set the behavior for turning the bulb on.

If you do not want to manually construct the behavior object, you should use get_turn_on_behavior() to get the current settings.

property state_information: Dict[str, Any]

Return bulb-specific state information.

property supported_modules: List[str]

Return a set of modules supported by the device.

property sys_info: Dict[str, Any]

Return system information.

Do not call this function from within the SmartDevice class itself as @requires_update will be affected for other properties.

property time: datetime

Return current time from the device.

property timezone: Dict

Return the current timezone.

async turn_off(*, transition: Optional[int] = None, **kwargs) Dict[source]

Turn the bulb off.

Parameters:

transition (int) – transition in milliseconds.

async turn_on(*, transition: Optional[int] = None, **kwargs) Dict[source]

Turn the bulb on.

Parameters:

transition (int) – transition in milliseconds.

async update(update_children: bool = True)

Query the device to update the data.

Needed for properties that are decorated with requires_update.

update_from_discover_info(info: Dict[str, Any]) None

Update state from info from the discover call.

property valid_temperature_range: ColorTempRange

Return the device-specific white temperature range (in Kelvin).

Returns:

White temperature range in Kelvin (minimum, maximum)

async wifi_join(ssid: str, password: str, keytype: str = '3')

Join the given wifi network.

If joining the network fails, the device will return to AP mode after a while.

async wifi_scan() List[WifiNetwork]

Scan for available wifi networks.

class kasa.SmartBulbPreset(*, index: int, brightness: int, hue: Optional[int] = None, saturation: Optional[int] = None, color_temp: Optional[int] = None, custom: Optional[int] = None, id: Optional[str] = None, mode: Optional[int] = None)[source]

Bulb configuration preset.

brightness: int
color_temp: Optional[int]
custom: Optional[int]
hue: Optional[int]
id: Optional[str]
index: int
mode: Optional[int]
saturation: Optional[int]
class kasa.smartbulb.BehaviorMode(value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Enum to present type of turn on behavior.

Last = 'last_status'

Return to the last state known state.

Preset = 'customize_preset'

Use chosen preset.

class kasa.TurnOnBehaviors(*, soft_on: TurnOnBehavior, hard_on: TurnOnBehavior)[source]

Model to contain turn on behaviors.

hard: TurnOnBehavior

The behavior when the bulb has been off from mains power.

soft: TurnOnBehavior

The behavior when the bulb is turned on programmatically.

class kasa.TurnOnBehavior(*, index: Optional[int] = None, mode: BehaviorMode)[source]

Model to present a single turn on behavior.

Parameters:
  • preset (int) – the index number of wanted preset.

  • mode (BehaviorMode) – last status or preset mode. If you are changing existing settings, you should not set this manually.

To change the behavior, it is only necessary to change the preset field to contain either the preset index, or None for the last known state.

class Config[source]

Configuration to make the validator run when changing the values.

validate_assignment = True
mode: BehaviorMode

Wanted behavior

preset: Optional[int]

Index of preset to use, or None for the last known state.