Skip to content
webdjoePublic

About

pyvesync is a python library to manage Etekcity & Levoit smart devices

Topics

Resources

Contributing

Stars

248 stars

Watchers

19 watching

Forks

Repository files navigation

pyvesync build status Open Source? Yes! PyPI license

pyvesync is a library to manage VeSync compatible smart home devices

Check out the new pyvesync documentation for usage and full API details.

Supported Product Types

  1. Outlets
  2. Switches
  3. Fans
  4. Air Purifiers
  5. Humidifiers
  6. Bulbs
  7. Air Fryers
  8. Thermostats

See the supported devices page for a complete list of supported devices and device types.

pyvesync v3 Features

BREAKING CHANGES - The release of pyvesync 3.0 comes with many improvements and new features, but as a result there are many breaking changes. The structure has been completely refactored, so please read through the README and thoroughly test before deploying.

The goal is to standardize the library across all devices to allow easier and consistent maintainability moving forward. The original library was created 8 years ago for supporting only a few outlets, it was not designed for supporting 20+ different devices.

Some of the changes are:

  • Asynchronous network requests with aiohttp.
  • Strong typing of all network requests and responses.
  • Created base classes for all devices for easier isinstance checks.
  • Separated the instantiated devices to a DeviceContainer class that acts as a mutable set with convenience methods.
  • Standardized the API for all device to follow a common naming convention. No more devices with different names for the same functionality.
  • Implemented custom exceptions and error (code) handling for API responses.
  • const module to hold all library constants
  • Built the DeviceMap class to hold the mapping and features of devices.

See pyvesync V3 for more information on the changes.

Asynchronous operation

Library is now asynchronous, using aiohttp as a replacement for requests. The pyvesync.VeSync class is an asynchronous context manager. A aiohttp.ClientSession can be passed or created internally.

import asyncio
import aiohttp
from pyvesync import VeSync

async def main():
    async with VeSync(
        username="user",
        password="password",
        country_code="US",  # Optional - country Code to select correct server
        session=session,  # Optional - aiohttp.ClientSession
        time_zone="America/New_York",  # Optional - Timezone, defaults to America/New_York
        redact=True  # Optional - Redact sensitive information from logs
        ) as manager:

        # Redact mode is enabled by default, set to False to disable
        manager.redact = False

        # To print logs to file
        manager.log_to_file("pyvesync.log")

        await manager.login()
        if not manager.enabled:
            print("Not logged in.")
            return
        await manager.get_devices() # Instantiates supported devices in device list
        await manager.update() # Updates the state of all devices

        # manager.devices is a DeviceContainer object
        # manager.devices.outlets is a list of VeSyncOutlet objects
        # manager.devices.switches is a list of VeSyncSwitch objects
        # manager.devices.fans is a list of VeSyncFanBase objects
        # manager.devices.bulbs is a list of VeSyncBulb objects
        # manager.devices.humidifiers is a list of VeSyncHumidifier objects
        # manager.devices.air_purifiers is a list of VeSyncPurifier objects
        # manager.devices.air_fryers is a list of VeSyncFryer objects
        # manager.devices.thermostats is a list of VeSyncThermostat objects

        for outlet in manager.devices.outlets:
            # The outlet object contain all action methods and static device attributes
            await outlet.update()
            await outlet.turn_off()
            outlet.display() # Print static device information, name, type, CID, etc.

            # State of object held in `device.state` attribute
            print(outlet.state)
            state_json = outlet.to_json(state=True)  # Returns JSON string of device state
            state_bytes = outlet.to_jsonb(state=True)  # Returns JSON bytes of device state

            # to view the response information of the last API call
            print(outlet.last_response)
            # Prints a ResponseInfo object containing error code,
            # and other response information


# Or use your own session
session = aiohttp.ClientSession()

async def main():
    async with VeSync("user", "password", session=session) as manager:
        await manager.login()
        await manager.update()



if __name__ == "__main__":
    asyncio.run(main())

If using async with is not ideal, the __aenter__() and __aexit__() methods need to be called manually:

manager = VeSync("user", "password")

await manager.__aenter__()

...

await manager.__aexit__(None, None, None)

pyvesync will close the ClientSession that was created by the library on __aexit__. If a session is passed in as an argument, the library does not close it. If a session is passed in and not closed, aiohttp will generate an error on exit:

2025-02-16 14:41:07 - ERROR - asyncio - Unclosed client session
2025-02-16 14:41:07 - ERROR - asyncio - Unclosed connector

VeSync Class Signature

The VeSync signature is:

VeSync(
    username: str,
    password: str,
    country_code: str = DEFAULT_REGION,  # "US"
    session: ClientSession | None = None,
    time_zone: str = DEFAULT_TZ,  # "America/New_York"
    redact: bool = True,
    )

Product Types

There is a new nomenclature for product types that defines the device class. The device.product_type attribute defines the product type based on the VeSync API. The product type is used to determine the device class and module. The currently supported product types are:

  1. outlet - Outlet devices
  2. switch - Wall switches
  3. fan - Fans (not air purifiers or humidifiers)
  4. purifier - Air purifiers (not humidifiers)
  5. humidifier - Humidifiers (not air purifiers)
  6. bulb - Light bulbs (not dimmers or switches)
  7. air fryer - Air fryers
  8. thermostat - Thermostats

See Supported Devices for a complete list of supported devices and models.

Custom Exceptions

Exceptions are no longer caught by the library and must be handled by the user. Exceptions are raised by server errors and aiohttp connection errors.

Errors that occur at the aiohttp level are raised automatically and propagated to the user. That means exceptions raised by aiohttp that inherit from aiohttp.ClientError are propagated.

When the connection to the VeSync API succeeds but returns an error code that prevents the library from functioning a custom exception inherited from pyvesync.utils.errors.VeSyncError is raised.

Custom Exceptions raised by all API calls:

  • pyvesync.utils.errors.VeSyncServerError - The API connected and returned a code indicated there is a server-side error.
  • pyvesync.utils.errors.VeSyncRateLimitError - The API's rate limit has been exceeded.
  • pyvesync.utils.errors.VeSyncAPIStatusCodeError - The API returned a non-200 status code.
  • pyvesync.utils.errors.VeSyncAPIResponseError - The response from the API was not in an expected format.

Login API Exceptions

  • pyvesync.utils.errors.VeSyncLoginError - The username or password is incorrect.

See the errors documentation for a complete list of error codes and exceptions.

The raise_api_errors() function is called for every API call and checks for general response errors. It can raise the following exceptions:

  • VeSyncServerError - The API connected and returned a code indicated there is a server-side error.
  • VeSyncRateLimitError - The API's rate limit has been exceeded.
  • VeSyncAPIStatusCodeError - The API returned a non-200 status code.
  • VeSyncTokenError - The API returned a token error and requires login() to be called again.
  • VeSyncLoginError - The username or password is incorrect.

Installation

Install the latest version from pip:

pip install pyvesync

Supported Devices

Etekcity Outlets

  1. Voltson Smart WiFi Outlet - Round (7A model ESW01-USA)
  2. Voltson Smart WiFi Outlet - Round (10A model ESW01-EU)
  3. Voltson Smart WiFi Outlet - Round (10A model ESW03-USA)
  4. Voltson Smart WiFi Outlet - Round (10A model ESW10-USA)
  5. Voltson Smart WiFi Outlet - Rectangle (15A model ESW15-USA)
  6. Two Plug Outdoor Outlet (ESO15-TB) (Each plug is a separate VeSyncOutlet object, energy readings are for both plugs combined)
  7. BSDOG / Greensun Smart Outlet Series (BSDOG01, BSDOG02, WYSMTOD16A, WM-PLUG and more)
  8. WHOGPLUG / Greensun Smart Plug
  9. WYLDR Smart Plug (WYLDR16A1081) (Supports energy monitoring but not energy history)

Wall Switches

  1. Etekcity Smart WiFi Light Switch (model ESWL01)
  2. Etekcity WiFi 3-Way Switch (model ESWL03)
  3. Etekcity WiFi Dimmer Switch (model ESWD16)

Levoit Air Purifiers

  1. LV-PUR131S
  2. LV-RH131S
  3. Core 200S
  4. Core 300S
  5. Core 400S
  6. Core 600S
  7. Vital 100S / 200S
  8. Everest Air
  9. Sprout Air Purifier

Etekcity / Valceno Bulbs

  1. Soft White Dimmable Smart Bulb (ESL100)
  2. Cool to Soft White Tunable Dimmable Bulb (ESL100CW)
  3. Multicolor Dimmable Bulb (ESL100MC)
  4. Valceno Multicolor Bulb (XYD0001)

Levoit Humidifiers

  1. Classic 200S
  2. Dual 200S
  3. Classic 300S
  4. LV600S / LV603S
  5. OasisMist 450S / 600S
  6. OasisMist 1000S
  7. Superior 6000S
  8. Sprout Humidifier

Levoit Fans

  1. 42 in. Tower Fan (LTF-F422S Series)
  2. Pedestal Fan (LPF-R432S Series)

Cosori Air Fryers

  1. Cosori 3.7 Quart Air Fryer (CS137-AF)
  2. Cosori 5.8 Quart Air Fryer (CS158-AF)
  3. Cosori TurboBlaze 6 Quart Air Fryer (CAF-DC601S)
  4. Cosori Dual Blaze 6.8 Quart Air Fryer (CAF-P583S)
  5. Cosori Dual Air Fryer (CAF-TF101S)
  6. Cosori Turbo Tower Pro Smart Air Fryer (CAF-DC111S-AEU)

Thermostats

  1. Aura Thermostat (LTM-A401S-WUS)

Usage

import asyncio
from pyvesync import VeSync

async def main():
    async with VeSync("user", "password") as manager:
        await manager.login()
        await manager.update()

        # Acts as a set of device instances
        device_container = manager.devices

        outlets = device_container.outlets  # List of outlet instances
        outlet = outlets[0]
        await outlet.update()
        await outlet.turn_off()
        outlet.display()

        # Iterate over entire device list
        for device in device_container:
            device.display()


if __name__ == "__main__":
    asyncio.run(main())

If you want to reuse your token and account_id between runs. The VeSync.auth object holds the credentials and helper methods to save and load credentials. See the Authentication Documentation for more details.

import asyncio
from pyvesync import VeSync

async def main():
    async with VeSync("user", "password") as manager:

        # If credentials are stored in a file, it can be loaded
        # with no path, .vesync_auth is read from the current directory,
        # then from the home directory
        await manager.load_credentials_from_file()
        # or the file path can be passed
        await manager.load_credentials_from_file("/path/to/token_file")

        # Or credentials can be passed directly
        manager.set_credentials(
            token="your_token",
            account_id="your_account_id",
            country_code="US",
            region="US",
        )

        # No login needed if token is valid
        # await manager.login()

        # To store credentials to a file after login
        await manager.save_credentials("/path/to/token_file")

        # Output credentials as JSON string
        print(manager.output_credentials_json())
        # Output credentials as dictionary
        print(manager.output_credentials_dict())

        await manager.update()

        # Acts as a set of device instances
        device_container = manager.devices

        outlets = device_container.outlets  # List of outlet instances
        outlet = outlets[0]
        await outlet.update()
        await outlet.turn_off()
        outlet.display()

        # Iterate over entire device list
        for device in device_container:
            device.display()


if __name__ == "__main__":
    asyncio.run(main())

Devices are stored in the VeSync.devices attribute, which is a DeviceContainer instance that acts as a mutable set. The DeviceContainer has properties for each product type that return lists of device instances:

await manager.login()  # Asynchronous
await manager.update()  # Asynchronous


# Acts as set with properties that return product type lists
manager.devices = DeviceContainer instance

manager.devices.outlets = [VeSyncOutletInstances]
manager.devices.switches = [VeSyncSwitchInstances]
manager.devices.fans = [VeSyncFanInstances]
manager.devices.bulbs = [VeSyncBulbInstances]
manager.devices.air_purifiers = [VeSyncPurifierInstances]
manager.devices.humidifiers = [VeSyncHumidifierInstances]
manager.devices.air_fryers = [VeSyncAirFryerInstances]
manager.devices.thermostats = [VeSyncThermostatInstances]

# Get device by device name
dev_name = "My Device"
for device in manager.devices:
  if device.device_name == dev_name:
    my_device = device
    device.display()

# Turn on switch by switch name
switch_name = "My Switch"
for switch in manager.devices.switches:
  if switch.device_name == switch_name:
    await switch.turn_on()   # Asynchronous

See the device documentation for more information on the device classes and their methods/states.

Debug mode and redact

There are three independent knobs that control logging output:

  • Debug logging - set the pyvesync logger level to DEBUG. The read-only manager.debug property reflects whether debug logging is currently active.
  • redact - the redact argument (default True) replaces tokens, account IDs, and other sensitive values (token, password, email, accountId, authKey, uuid, cid, authorizeCode) with ##_REDACTED_## so logs can be shared safely. It only has an effect while debug logging is enabled.
  • LibraryLogger.verbose - set this class attribute to True to additionally print the full request & response body of every API call.

Debug to the console

Setting the pyvesync logger to DEBUG sends debug output to wherever your logging is configured (the console by default). redact stays on so tokens are not exposed:

import logging
import asyncio
from pyvesync import VeSync
from pyvesync.utils.logs import LibraryLogger

logger = logging.getLogger("pyvesync")
logger.setLevel(logging.DEBUG)
logging.basicConfig()  # Send log records to the console


async def main():
    async with VeSync("user", "password") as manager:
        manager.redact = True  # True by default
        LibraryLogger.verbose = True  # Optional - print full request/response content
        await manager.login()
        await manager.update()

        outlet = manager.devices.outlets[0]
        await outlet.update()
        await outlet.turn_off()
        outlet.display()


if __name__ == "__main__":
    asyncio.run(main())

Debug to a file (recommended for sharing with issues)

The log_to_file() method is the simplest way to capture a full debug log. It sets the pyvesync logger to DEBUG and attaches a file handler in one call, so you do not need to configure logging yourself. It also prints to the console by default; pass stdout=False to log only to the file. Keep redact=True (the default) so the log is safe to attach to a GitHub issue:

import asyncio
from pyvesync import VeSync
from pyvesync.utils.logs import LibraryLogger


async def main():
    # redact=True is the default - sensitive values are scrubbed from the log
    async with VeSync("user", "password", redact=True) as manager:
        # Enables DEBUG logging and writes it to pyvesync.log
        # stdout=True (the default) also prints the log to the console
        manager.log_to_file("pyvesync.log", stdout=True)

        # Optional - include the full request & response body of every API call
        LibraryLogger.verbose = True

        await manager.login()
        await manager.update()

        outlet = manager.devices.outlets[0]
        await outlet.update()
        await outlet.turn_off()
        outlet.display()


if __name__ == "__main__":
    asyncio.run(main())

Contribution Expectations

Contributions — from humans and AI coding assistants alike — must follow three rules. These keep the library correct and maintainable. See the contributing guide for full detail.

  1. Follow the intended architecture. New devices are added through the three-tier hierarchy (base class → concrete device + API mixin → device map), with state in the device's DeviceState subclass, models in models/, and constants in pyvesync.const. API request/response shapes must come from a real packet capture — never invented.
  2. Verify on real hardware before merge. New device support and any change to device behavior must be tested on the physical device, and the pull request must state the model and firmware version tested. Testing only through Home Assistant does not count.
  3. One change per pull request. Each PR must be a single feature, fix, or edit. Large or mixed PRs that bundle unrelated changes will be asked to be broken up before review.

Using an AI assistant? Agent instructions live in AGENTS.md, which Codex and most tools read directly; CLAUDE.md imports it for Claude Code. Point your assistant at it and the contributing guide. You are responsible for the result: it must follow the architecture, must not fabricate API fields, must not be submitted without real-device testing, and must be a single focused change.

Feature Requests

Before filing an issue to request a new feature or device, please ensure that you will take the time to test the feature thoroughly. New features cannot be simply tested on Home Assistant. A separate integration must be created which is not part of this library. In order to test a new feature, clone the branch and install into a new virtual environment.

mkdir python_test && cd python_test

# Check Python version is 3.11 or higher
python3 --version # or python --version
# Create a new venv
python3 -m venv pyvesync-venv
# Activate the venv on linux
source pyvesync-venv/bin/activate
# or ....
pyvesync-venv\Scripts\activate.ps1 # on powershell
pyvesync-venv\Scripts\activate.bat # on command prompt

# Install branch to be tested into new virtual environment:
pip install git+https://github.com/webdjoe/pyvesync.git@BRANCHNAME

# Install a PR that has not been merged:
pip install git+https://github.com/webdjoe/pyvesync.git@refs/pull/PR_NUMBER/head

Test functionality with a script, please adjust methods and logging statements to the device you are testing.

See testing_scripts for a fully functioning test script for all devices.

import asyncio
import logging
from pyvesync import VeSync

vs_logger = logging.getLogger("pyvesync")
vs_logger.setLevel(logging.DEBUG)

logger = logging.getLogger('pyvesync_test')
logger.setLevel(logging.DEBUG)

USERNAME = "YOUR USERNAME"
PASSWORD = "YOUR PASSWORD"

DEVICE_NAME = "Device"  # Device to test

async def test_device():
    # Instantiate VeSync class and login
    async with VeSync(USERNAME, PASSWORD, redact=True) as manager:
        await manager.login()

        # Pull and update devices
        await manager.update()

        for dev in manager.devices:
            # Print all device info
            logger.debug(dev.device_name)
            dev.display()

            # Find correct device
            if dev.device_name.lower() != DEVICE_NAME.lower():
                logger.debug("%s is not %s, continuing", dev.device_name, DEVICE_NAME)
                continue

            logger.debug('-------------- %s -----------------', dev.device_name)
            dev.display()

            # Test device methods
            logger.debug("Device is on: %s", dev.is_on)

            logger.debug("Turning on")
            await dev.turn_on()
            logger.debug("Device is on: %s", dev.is_on)

            logger.debug("Turning off")
            await dev.turn_off()
            logger.debug("Device is on: %s", dev.is_on)

            # Display all device info as JSON
            logger.debug(dev.to_json(state=True, indent=True))
            dev_dict = dev.to_dict(state=True)

if __name__ == "__main__":
    logger.debug("Testing device")
    asyncio.run(test_device())

Device Requests

If you would like to request a new device to be added to the library, please open an issue on GitHub. Be sure to include the device model number and a link to the product page. If you are able to provide packet captures or are willing to share the device temporarily, please indicate that in the issue. See the Packet Capturing for New Device Support document for more details.

Contributing

All contributions are welcome.

This project is licensed under MIT.

Contributors

This is an open source project and cannot exist without the contributions of its community. Thank you to all the contributors who have helped make this project better!

A special thanks for helping with V3 go live:


cdninja

sapuseven

sdrapha

And to all of those that contributed to the project:

Made with contrib.rocks.

About

pyvesync is a python library to manage Etekcity & Levoit smart devices

Topics

Resources

Contributing

Stars

248 stars

Watchers

19 watching

Forks

Releases

Packages

Used by

Contributors

Languages