Skip to main content

switchbot-client

PyPI - Python Version PyPI - Library Version PyPI - Downloads License Code style: black

An unofficial Python client implementation of the SwitchBot API.

About this version

switchbot-client-0.x.x is the implementation for SwitchBot API version 1.0. The implementation for API version 1.1 or later will proceed with switchbot-client-1.x.x. Please select the library version according to the API version you use. Development of switchbot-client-0.x.x will likely cease with the SwitchBot API version update, and we recommend moving to 1.x.x.

Table of Contents

Authentication

Before you start using this client, you need to get an open token. Please follow the instructions in the official documentation below.

https://github.com/OpenWonderLabs/SwitchBotAPI#authentication

Once you have the token, use one of the following methods to pass the information to the client.

Environment variables

If the environment variable SWITCHBOT_OPEN_TOKEN is present, this client will automatically use this value.

export SWITCHBOT_OPEN_TOKEN=your_switchbot_open_token
python your_script.py
# your_script.py
from switchbot_client import SwitchBotClient

client = SwitchBotClient()
print(client.devices())

Constructor Arguments

It is also possible to initialize the client by passing a token directly as an argument.

from switchbot_client import SwitchBotClient

your_token = "your_switchbot_open_token"
client = SwitchBotClient(token=your_token)
print(client.devices())

Config file

If ~/.config/switchbot-client/config.yml exists and has a token entry, this client will automatically use the value.

mkdir -p ~/.config/switchbot-client
echo "token: your_switchbot_open_token" >>  ~/.config/switchbot-client/config.yml
python your_script.py
# your_script.py
from switchbot_client import SwitchBotClient

client = SwitchBotClient()
print(client.devices())

Usage

Get Device List

from switchbot_client import SwitchBotClient

client = SwitchBotClient()
result = client.devices()
print(result)
[Meter({'device_id': 'ABCDEFG', 'device_type': 'Meter', 'device_name': 'Meter 0A', 'hub_device_id': 'ABCDE', 'is_virtual_infrared': False}), HubMini({'device_id': 'ABCDEFG', 'device_type': 'Hub Mini', 'device_name': 'Hub Mini 0', 'hub_device_id': None, 'is_virtual_infrared': False}), Light({'device_id': '12345', 'device_type': 'Light', 'device_name': 'My Light', 'hub_device_id': 'ABCDE', 'is_virtual_infrared': True}), AirConditioner({'device_id': '12345', 'device_type': 'Air Conditioner', 'device_name': 'My Air Conditioner', 'hub_device_id': 'ABCDE', 'is_virtual_infrared': True})]

If you run the above code, you will get a list of all the devices associated with your SwitchBot account. You can perform operations on the acquired device_id, such as manipulating it or getting its status.

Get Device Status

from switchbot_client import SwitchBotClient

client = SwitchBotClient()
device_id = "YOUR_DEVICE_ID"
print(client.device(device_id).status())
DeviceStatus(device_id='ABCDE', device_type='Meter', device_name='Meter 0', hub_device_id='ABCDE', data={'deviceId': 'ABCDE', 'deviceType': 'Meter', 'hubDeviceId': 'ABCDE', 'humidity': 50, 'temperature': 25.0})

This function allows you to get the status of a device. Note that only the physical device returns accurate results, while the virtual infrared remote device is inaccurate, storing the results of the most recent operation.

Please refer to the following official document to know what kind of information can be obtained from each device.

https://github.com/OpenWonderLabs/SwitchBotAPI#get-device-status

Control Device

from switchbot_client import SwitchBotClient
from switchbot_client.devices import Light

client = SwitchBotClient()
device_id = "12345"  # My Light(virtual infrared remote devices)
device = Light.create_by_id(client, device_id)
print(device.turn_on())
SwitchBotCommandResult(status_code=100, message='success', response_body={})

It allows you to control the specified device. The following documents define the commands that can be executed.

https://github.com/OpenWonderLabs/SwitchBotAPI#send-device-control-commands

Get Scene List

from switchbot_client import SwitchBotClient

client = SwitchBotClient()
print(client.scenes())
[SwitchBotScene({'scene_id': '12345', 'scene_name': 'My Scene1'}), SwitchBotScene({'scene_id': '23456', 'scene_name': 'My Scene2'})]

You can get a list of all the scenes associated with your SwitchBot account. Note that only manual scenes are returned from this api.

Execute Scene

from switchbot_client import SwitchBotClient

client = SwitchBotClient()
print(client.scene("12345").execute())
SwitchBotCommandResult(status_code=100, message='success', response_body={})

The specified scene can be executed immediately.

Webhooks

from switchbot_client import SwitchBotClient

client = SwitchBotClient()
client.set_webhook(url="https://example.com/foo", enable=True)
print(client.webhooks())
[SwitchBotWebhook(url='https://example.com/foo', enable=True, device_list='ALL', create_time=datetime.datetime(2022, 1, 1, 12, 0, 0, 123456), last_update_time=datetime.datetime(2022, 1, 1, 12, 0, 0, 123456))]

You can handle webhook configurations via SwitchBotClient.

Raw API interface

Devices and scenes also can be manipulated via the low-level raw API client. The SwitchBotAPIClient class has methods for each endpoints of SwitchBot API.

For example the /v1.0/devices endpoint is implemented as SwitchBotAPIClient.devices(), the /v1.0/devices/{device_id}/status" endpoint is implemented as SwitchBotAPIClient.devices_status(device_id: str).

Examples

from switchbot_client import devices
from switchbot_client import SwitchBotClient


def call_this_function_when_i_go_out():
    client = SwitchBotClient()
    print("turn off all lights and air conditioners...")
    for d in client.devices():
        if isinstance(d, devices.Light):
            d.turn_off()

        if isinstance(d, devices.ColorBulb):
            d.turn_off()

        if isinstance(d, devices.AirConditioner):
            d.turn_off()
    print("done")


def control_devices_by_temperature():
    client = SwitchBotClient()
    all_devices = client.devices()

    temperatures = [d.temperature() for d in all_devices if isinstance(d, devices.Meter)]
    temperature = min(temperatures)

    color_bulbs = [d for d in all_devices if isinstance(d, devices.ColorBulb)]
    air_conditioners = [d for d in all_devices if isinstance(d, devices.AirConditioner)]

    if temperature > 25.0:
        print("hot!")
        for d in color_bulbs:
            d.set_color("#FF0000")

        for d in air_conditioners:
            d.set_all(
                temperature=20.0,
                mode=devices.AirConditioner.Parameters.MODE_COOL,
                fan_speed=devices.AirConditioner.Parameters.FAN_SPEED_HIGH,
                power=devices.AirConditioner.Parameters.POWER_ON
            )

    elif temperature < 15.0:
        print("cold!")
        for d in color_bulbs:
            d.set_color("#0000FF")

        for d in air_conditioners:
            d.set_all(
                temperature=20.0,
                mode=devices.AirConditioner.Parameters.MODE_HEAT,
                fan_speed=devices.AirConditioner.Parameters.FAN_SPEED_HIGH,
                power=devices.AirConditioner.Parameters.POWER_ON
            )

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Release files for switchbot-client 0.4.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for switchbot-client 0.4.1
File Size Uploaded
switchbot-client-0.4.1.tar.gz 23.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for switchbot-client 0.4.1
File Interpreter ABI Platform
switchbot_client-0.4.1-py3-none-any.whl Python 3 none any Details

Total release size: 42.8 kB

Release files / switchbot-client-0.4.1.tar.gz

Download URL switchbot-client-0.4.1.tar.gz
Size 23.4 kB
Tags Source
SHA-256 checksum
How to use checksums
536556cea70a337697521fa7e1888ae91f678e3d3667b00526d171447263b488
BLAKE2b-256 checksum
How to use checksums
7c0a6a173624f8fc9b264e8cefdc58948d72126206402ae4be6d95f89be84294
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.2.1 CPython/3.10.4 Darwin/21.3.0

Release files / switchbot_client-0.4.1-py3-none-any.whl

Download URL switchbot_client-0.4.1-py3-none-any.whl
Size 19.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c45018293c87d77f03b6d1e9282de482cd0ce677af74e147ec241d0403e03324
BLAKE2b-256 checksum
How to use checksums
b8bccdbdd07a4cacae5ea626b7ceec61ede975ac98fbb6c5d88db826deaa189f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.2.1 CPython/3.10.4 Darwin/21.3.0

Release history Release notifications | RSS feed

This release

0.4.1 This release

2 release files

0.4.0

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page