Skip to content

VeSync Outlets

Overview

pyvesync.base_devices.outlet_base.OutletState

Bases: DeviceState

Base state class for Outlets.

This class holds all of the state information for the outlet devices. The state instance is stored in the state attribute of the outlet device. This is only for holding state information and does not contain any methods for controlling the device or retrieving information from the API.

Parameters:

Name Type Description Default
device VeSyncOutlet

The device object.

required
details ResponseDeviceDetailsModel

The device details.

required
feature_map OutletMap

The feature map for the device.

required

Attributes:

Name Type Description
active_time int

Active time of device, defaults to None.

connection_status str

Connection status of device.

device VeSyncOutlet

Device object.

device_status str

Device status.

features dict

Features of device.

last_update_ts int

Last update timestamp of device, defaults to None.

energy float

Energy usage in kWh.

monthly_history ResponseEnergyResult

Monthly energy history.

nightlight_automode str

Nightlight automode status.

nightlight_brightness int

Nightlight brightness level.

nightlight_status str

Nightlight status.

power float

Power usage in Watts.

voltage float

Voltage in Volts.

weekly_history ResponseEnergyResult

Weekly energy history.

yearly_history ResponseEnergyResult

Yearly energy history.

Methods:

Name Description
update_ts

Update last update timestamp.

to_dict

Dump state to JSON.

to_json

Dump state to JSON string.

to_jsonb

Dump state to JSON bytes.

as_tuple

Convert state to tuple of (name, value) tuples.

Note

Not all attributes are available on all devices. Some attributes may be None or not supported depending on the device type and features. The attributes are set based on the device features and the API response.

Source code in src\pyvesync\base_devices\outlet_base.py
class OutletState(DeviceState):
    """Base state class for Outlets.

    This class holds all of the state information for the outlet devices. The state
    instance is stored in the `state` attribute of the outlet device. This is only
    for holding state information and does not contain any methods for controlling
    the device or retrieving information from the API.

    Args:
        device (VeSyncOutlet): The device object.
        details (ResponseDeviceDetailsModel): The device details.
        feature_map (OutletMap): The feature map for the device.

    Attributes:
        active_time (int): Active time of device, defaults to None.
        connection_status (str): Connection status of device.
        device (VeSyncOutlet): Device object.
        device_status (str): Device status.
        features (dict): Features of device.
        last_update_ts (int): Last update timestamp of device, defaults to None.
        energy (float): Energy usage in kWh.
        monthly_history (ResponseEnergyResult): Monthly energy history.
        nightlight_automode (str): Nightlight automode status.
        nightlight_brightness (int): Nightlight brightness level.
        nightlight_status (str): Nightlight status.
        power (float): Power usage in Watts.
        voltage (float): Voltage in Volts.
        weekly_history (ResponseEnergyResult): Weekly energy history.
        yearly_history (ResponseEnergyResult): Yearly energy history.

    Methods:
        update_ts: Update last update timestamp.
        to_dict: Dump state to JSON.
        to_json: Dump state to JSON string.
        to_jsonb: Dump state to JSON bytes.
        as_tuple: Convert state to tuple of (name, value) tuples.

    Note:
        Not all attributes are available on all devices. Some attributes may be None or
        not supported depending on the device type and features. The attributes are set
        based on the device features and the API response.
    """

    __slots__ = (
        "energy",
        "monthly_history",
        "nightlight_automode",
        "nightlight_brightness",
        "nightlight_status",
        "power",
        "voltage",
        "weekly_history",
        "yearly_history",
    )

    def __init__(
        self,
        device: VeSyncOutlet,
        details: ResponseDeviceDetailsModel,
        feature_map: OutletMap
            ) -> None:
        """Initialize VeSync Switch State."""
        super().__init__(device, details, feature_map)
        self._exclude_serialization = [
            "weakly_history",
            "monthly_history",
            "yearly_history",
        ]
        self.device: VeSyncOutlet = device
        self.features: list[str] = feature_map.features
        self.active_time: int | None = 0
        self.power: float = IntFlag.NOT_SUPPORTED
        self.energy: float = IntFlag.NOT_SUPPORTED
        self.voltage: float = IntFlag.NOT_SUPPORTED
        self.nightlight_status: str | None = StrFlag.NOT_SUPPORTED
        self.nightlight_brightness: int | None = IntFlag.NOT_SUPPORTED
        self.nightlight_automode: str | None = StrFlag.NOT_SUPPORTED
        self.weekly_history: ResponseEnergyResult | None = None
        self.monthly_history: ResponseEnergyResult | None = None
        self.yearly_history: ResponseEnergyResult | None = None

    def annual_history_to_json(self) -> None | str:
        """Dump annual history."""
        if not self.device.supports_energy:
            logger.info("Device does not support energy monitoring.")
            return None
        if self.yearly_history is None:
            logger.info("No yearly history available, run device.get_yearly_history().")
            return None
        return self.yearly_history.to_json()

    def monthly_history_to_json(self) -> None | str:
        """Dump monthly history."""
        if not self.device.supports_energy:
            logger.info("Device does not support energy monitoring.")
            return None
        if self.monthly_history is None:
            logger.info("No monthly history available, run device.get_monthly_history().")
            return None
        return self.monthly_history.to_json()

    def weekly_history_to_json(self) -> None | str:
        """Dump weekly history."""
        if not self.device.supports_energy:
            logger.info("Device does not support energy monitoring.")
            return None
        if self.weekly_history is None:
            logger.info("No weekly history available, run device.get_weekly_history().")
            return None
        return self.weekly_history.to_json()

Attributes

active_time instance-attribute

active_time: int | None = 0

Inherited From DeviceState

connection_status instance-attribute

connection_status: str = connectionStatus or UNKNOWN

Inherited From DeviceState

device instance-attribute

device: VeSyncOutlet = device

Inherited From DeviceState

device_status instance-attribute

device_status: str = deviceStatus or UNKNOWN

Inherited From DeviceState

energy instance-attribute

energy: float = NOT_SUPPORTED

features instance-attribute

features: list[str] = features

Inherited From DeviceState

last_update_ts instance-attribute

last_update_ts: int | None = None

Inherited From DeviceState

monthly_history instance-attribute

monthly_history: ResponseEnergyResult | None = None

nightlight_automode instance-attribute

nightlight_automode: str | None = NOT_SUPPORTED

nightlight_brightness instance-attribute

nightlight_brightness: int | None = NOT_SUPPORTED

nightlight_status instance-attribute

nightlight_status: str | None = NOT_SUPPORTED

power instance-attribute

power: float = NOT_SUPPORTED

timer instance-attribute

timer: Timer | None = None

Inherited From DeviceState

voltage instance-attribute

voltage: float = NOT_SUPPORTED

weekly_history instance-attribute

weekly_history: ResponseEnergyResult | None = None

yearly_history instance-attribute

yearly_history: ResponseEnergyResult | None = None

Functions

annual_history_to_json

annual_history_to_json() -> None | str

Dump annual history.

Source code in src\pyvesync\base_devices\outlet_base.py
def annual_history_to_json(self) -> None | str:
    """Dump annual history."""
    if not self.device.supports_energy:
        logger.info("Device does not support energy monitoring.")
        return None
    if self.yearly_history is None:
        logger.info("No yearly history available, run device.get_yearly_history().")
        return None
    return self.yearly_history.to_json()

as_tuple

as_tuple() -> tuple[tuple[str, Any], ...]

Inherited From DeviceState

Convert state to tuple of (name, value) tuples.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def as_tuple(self) -> tuple[tuple[str, Any], ...]:
    """Convert state to tuple of (name, value) tuples."""
    return tuple((k, v) for k, v in self._serialize().items())

display

display() -> None

Inherited From DeviceState

Print formatted state to stdout.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def display(self) -> None:
    """Print formatted state to stdout."""
    for name, val in self._serialize().items():
        print(f'{name:.<30} {val}')

monthly_history_to_json

monthly_history_to_json() -> None | str

Dump monthly history.

Source code in src\pyvesync\base_devices\outlet_base.py
def monthly_history_to_json(self) -> None | str:
    """Dump monthly history."""
    if not self.device.supports_energy:
        logger.info("Device does not support energy monitoring.")
        return None
    if self.monthly_history is None:
        logger.info("No monthly history available, run device.get_monthly_history().")
        return None
    return self.monthly_history.to_json()

to_dict

to_dict() -> dict[str, Any]

Inherited From DeviceState

Convert state to dictionary.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_dict(self) -> dict[str, Any]:
    """Convert state to dictionary."""
    return self._serialize()

to_json

to_json(indent: bool = False) -> str

Inherited From DeviceState

Dump state to JSON string.

Parameters:

Name Type Description Default
indent bool

If True, indent JSON output, defaults to False.

False

Returns:

Name Type Description
str str

JSON formatted string of device state.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_json(self, indent: bool = False) -> str:
    """Dump state to JSON string.

    Args:
        indent (bool): If True, indent JSON output, defaults to False.

    Returns:
        str: JSON formatted string of device state.
    """
    return self.to_jsonb(indent=indent).decode()

to_jsonb

to_jsonb(indent: bool = False) -> bytes

Inherited From DeviceState

Convert state to JSON bytes.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_jsonb(self, indent: bool = False) -> bytes:
    """Convert state to JSON bytes."""
    if indent:
        return orjson.dumps(
            self._serialize(), option=orjson.OPT_NON_STR_KEYS | orjson.OPT_INDENT_2
        )
    return orjson.dumps(self._serialize(), option=orjson.OPT_NON_STR_KEYS)

update_ts

update_ts() -> None

Inherited From DeviceState

Update last update timestamp.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def update_ts(self) -> None:
    """Update last update timestamp."""
    self.last_update_ts = int(dt.now(
        tz=ZoneInfo(self.device.manager.time_zone)).timestamp())

weekly_history_to_json

weekly_history_to_json() -> None | str

Dump weekly history.

Source code in src\pyvesync\base_devices\outlet_base.py
def weekly_history_to_json(self) -> None | str:
    """Dump weekly history."""
    if not self.device.supports_energy:
        logger.info("Device does not support energy monitoring.")
        return None
    if self.weekly_history is None:
        logger.info("No weekly history available, run device.get_weekly_history().")
        return None
    return self.weekly_history.to_json()

pyvesync.devices.vesyncoutlet.VeSyncOutlet7A

Bases: VeSyncOutlet

Etekcity 7A Round Outlet Class.

Parameters:

Name Type Description Default
details ResponseDeviceDetailsModel

The device details.

required
manager VeSync

The VeSync manager.

required
feature_map OutletMap

The feature map for the device.

required

Attributes:

Name Type Description
state OutletState

The state of the outlet.

last_response ResponseInfo

Last response from API call.

device_status str

Device status.

connection_status str

Connection status.

manager VeSync

Manager object for API calls.

device_name str

Name of device.

device_image str

URL for device image.

cid str

Device ID.

connection_type str

Connection type of device.

device_type str

Type of device.

type str

Type of device.

uuid str

UUID of device, not always present.

config_module str

Configuration module of device.

mac_id str

MAC ID of device.

current_firm_version str

Current firmware version of device.

device_region str

Region of device. (US, EU, etc.)

pid str

Product ID of device, pulled by some devices on update.

sub_device_no int

Sub-device number of device.

product_type str

Product type of device.

features dict

Features of device.

Source code in src\pyvesync\devices\vesyncoutlet.py
class VeSyncOutlet7A(VeSyncOutlet):
    """Etekcity 7A Round Outlet Class.

    Args:
        details (ResponseDeviceDetailsModel): The device details.
        manager (VeSync): The VeSync manager.
        feature_map (OutletMap): The feature map for the device.

    Attributes:
        state (OutletState): The state of the outlet.
        last_response (ResponseInfo): Last response from API call.
        device_status (str): Device status.
        connection_status (str): Connection status.
        manager (VeSync): Manager object for API calls.
        device_name (str): Name of device.
        device_image (str): URL for device image.
        cid (str): Device ID.
        connection_type (str): Connection type of device.
        device_type (str): Type of device.
        type (str): Type of device.
        uuid (str): UUID of device, not always present.
        config_module (str): Configuration module of device.
        mac_id (str): MAC ID of device.
        current_firm_version (str): Current firmware version of device.
        device_region (str): Region of device. (US, EU, etc.)
        pid (str): Product ID of device, pulled by some devices on update.
        sub_device_no (int): Sub-device number of device.
        product_type (str): Product type of device.
        features (dict): Features of device.
    """

    __slots__ = ()

    def __init__(self, details: ResponseDeviceDetailsModel,
                 manager: VeSync, feature_map: OutletMap) -> None:
        """Initialize Etekcity 7A round outlet class."""
        super().__init__(details, manager, feature_map)

    def _build_headers(self) -> dict:
        """Build 7A Outlet Request Headers."""
        headers = RequestHeaders.copy()
        headers.update({
            "tz": self.manager.time_zone,
            'tk': self.manager.token,
            'accountid': self.manager.account_id,
        })
        return headers

    async def get_details(self) -> None:
        r_dict, _ = await self.manager.async_call_api(
            '/v1/device/' + self.cid + '/detail',
            'get',
            headers=self._build_headers(),
        )

        if not isinstance(r_dict, dict):
            LibraryLogger.log_device_api_response_error(
                logger, self.device_name, self.device_type,
                'get_details', "Response is not valid JSON"
            )
            return

        if 'error' in r_dict:
            _ = Helpers.process_dev_response(logger, "get_details", self, r_dict)
            return
        self.state.update_ts()
        resp_model = Response7AOutlet.from_dict(r_dict)
        self.state.connection_status = ConnectionStatus.ONLINE
        self.state.device_status = resp_model.deviceStatus
        self.state.active_time = resp_model.activeTime
        self.state.energy = resp_model.energy
        self.state.power = self.parse_energy_detail(resp_model.power)
        self.state.voltage = self.parse_energy_detail(resp_model.voltage)

    @staticmethod
    def parse_energy_detail(energy: str | float) -> float:
        """Parse energy details to be compatible with new and old firmware."""
        try:
            if isinstance(energy, str) and ':' in energy:
                power = round(float(Helpers.calculate_hex(energy)), 2)
            else:
                power = float(energy)
        except ValueError:
            logger.debug('Error parsing power response - %s', energy)
            power = 0
        return power

    async def toggle_switch(self, toggle: bool | None = None) -> bool:
        if toggle is None:
            toggle = self.state.device_status != DeviceStatus.ON
        toggle_str = DeviceStatus.ON if toggle else DeviceStatus.OFF
        r_dict, status_code = await self.manager.async_call_api(
            f'/v1/wifi-switch-1.3/{self.cid}/status/{toggle_str}',
            'put',
            headers=Helpers.req_legacy_headers(self.manager),
        )

        if status_code != 200:
            LibraryLogger.log_device_api_response_error(
                logger, self.device_name, self.device_type,
                'toggle_switch', "Response code is not 200"
            )

        if isinstance(r_dict, dict) and 'error' in r_dict:
            _ = Helpers.process_dev_response(logger, "get_details", self, r_dict)
            return False

        self.state.update_ts()
        self.state.device_status = toggle_str
        self.state.connection_status = ConnectionStatus.ONLINE
        return True

    async def get_timer(self) -> None:
        r_dict, status_code = await self.manager.async_call_api(
            f"/v2/device/{self.cid}/timer",
            "get",
            headers=Helpers.req_legacy_headers(self.manager),
        )
        if not r_dict or status_code != 200:
            logger.debug("No timer set.")
            self.state.timer = None
            return
        if isinstance(r_dict, list) and len(r_dict) > 0:
            timer_model = Helpers.model_maker(logger, Timer7AItem, "get_timer", r_dict[0])
            if timer_model is None:
                self.state.timer = None
                return
            self.state.timer = Timer(
                timer_duration=int(timer_model.counterTimer),
                id=int(timer_model.timerID),
                action=timer_model.action,
            )
            if timer_model.timerStatus == 'off':
                self.state.timer.pause()
            return
        self.state.timer = None

    async def set_timer(self, duration: int, action: str | None = None) -> bool:
        if action is None:
            action = (
                DeviceStatus.ON
                if self.state.device_status == DeviceStatus.OFF
                else DeviceStatus.OFF
            )
        if not isinstance(action, str) or \
                action not in [DeviceStatus.ON, DeviceStatus.OFF]:
            logger.error("Invalid action for timer - %s", action)
            return False
        update_dict = {
            'action': action,
            'counterTimer': duration,
            "timerStatus": "start",
            'conflictAwayIds': [],
            'conflictScheduleIds': [],
            'conflictTimerIds': [],
        }
        r_dict, status_code = await self.manager.async_call_api(
            f"/v2/device/{self.cid}/timer",
            "post",
            headers=Helpers.req_legacy_headers(self.manager),
            json_object=update_dict,
        )
        if status_code != 200 or not isinstance(r_dict, dict):
            logger.debug("Failed to set timer.")
            return False

        if 'error' in r_dict:
            logger.debug("Error in response: %s", r_dict['error'])
            return False

        result_model = Helpers.model_maker(
            logger, TimerModels.ResultV1SetTimer, "set_timer", r_dict, self
        )
        if result_model is None:
            logger.debug("Failed to set timer.")
            return False
        if result_model.timerID == '':
            logger.debug("Unable to set timer.")
            if result_model.conflictTimerIds:
                logger.debug("Conflicting timer IDs - %s", result_model.conflictTimerIds)
            return False
        self.state.timer = Timer(duration, action, int(result_model.timerID))
        return True

    async def clear_timer(self) -> bool:
        if self.state.timer is None:
            logger.debug("No timer set, nothing to clear, run get_timer().")
            return False
        _, status_code = await self.manager.async_call_api(
            f"/v2/device/{self.cid}/timer/{self.state.timer.id}",
            "delete",
            headers=Helpers.req_legacy_headers(self.manager),
        )
        if status_code != 200:
            return False
        self.state.timer = None
        return True

Attributes

cid instance-attribute

cid: str = cid

Inherited From VeSyncBaseDevice

config_module instance-attribute

config_module: str = configModule

Inherited From VeSyncBaseDevice

connection_type instance-attribute

connection_type: str | None = connectionType

Inherited From VeSyncBaseDevice

current_firm_version instance-attribute

current_firm_version = currentFirmVersion

Inherited From VeSyncBaseDevice

device_image instance-attribute

device_image: str | None = deviceImg

Inherited From VeSyncBaseDevice

device_name instance-attribute

device_name: str = deviceName

Inherited From VeSyncBaseDevice

device_region instance-attribute

device_region: str | None = deviceRegion

Inherited From VeSyncBaseDevice

device_type instance-attribute

device_type: str = deviceType

Inherited From VeSyncBaseDevice

enabled instance-attribute

enabled: bool = True

Inherited From VeSyncBaseDevice

features instance-attribute

features: list[str] = features

Inherited From VeSyncBaseDevice

firmware_update property

firmware_update: bool

Inherited From VeSyncBaseDevice

Return True if firmware update available.

This is going to be updated.

is_on property

is_on: bool

Inherited From VeSyncBaseDevice

Return true if device is on.

last_response instance-attribute

last_response: ResponseInfo | None = None

Inherited From VeSyncBaseDevice

mac_id instance-attribute

mac_id: str | None = macID

Inherited From VeSyncBaseDevice

manager instance-attribute

manager = manager

Inherited From VeSyncBaseDevice

nightlight_modes instance-attribute

nightlight_modes = nightlight_modes

Inherited From VeSyncOutlet

pid instance-attribute

pid: str | None = None

Inherited From VeSyncBaseDevice

product_type instance-attribute

product_type: str = product_type

Inherited From VeSyncBaseDevice

state instance-attribute

state: OutletState = OutletState(self, details, feature_map)

Inherited From VeSyncBaseDevice

sub_device_no instance-attribute

sub_device_no: int | None = subDeviceNo

Inherited From VeSyncBaseDevice

supports_energy property

supports_energy: bool

Inherited From VeSyncOutlet

Return True if device supports energy.

Returns:

Name Type Description
bool bool

True if device supports energy, False otherwise.

supports_nightlight property

supports_nightlight: bool

Inherited From VeSyncOutlet

Return True if device supports nightlight.

Returns:

Name Type Description
bool bool

True if device supports nightlight, False otherwise.

type instance-attribute

type: str | None = type

Inherited From VeSyncBaseDevice

uuid instance-attribute

uuid: str | None = uuid

Inherited From VeSyncBaseDevice

Functions

clear_timer async

clear_timer() -> bool

Inherited From VeSyncBaseDevice

Clear timer for device from API.

This may not be implemented for all devices. Please open an issue if there is an error.

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def clear_timer(self) -> bool:
    if self.state.timer is None:
        logger.debug("No timer set, nothing to clear, run get_timer().")
        return False
    _, status_code = await self.manager.async_call_api(
        f"/v2/device/{self.cid}/timer/{self.state.timer.id}",
        "delete",
        headers=Helpers.req_legacy_headers(self.manager),
    )
    if status_code != 200:
        return False
    self.state.timer = None
    return True

display

display(state: bool = True) -> None

Inherited From VeSyncBaseDevice

Print formatted static device info to stdout.

Parameters:

Name Type Description Default
state bool

If True, include state in display, defaults to True.

True

Example:

Device Name:..................Living Room Lamp
Model:........................ESL100
Subdevice No:.................0
Type:.........................wifi
CID:..........................1234567890abcdef

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def display(self, state: bool = True) -> None:
    """Print formatted static device info to stdout.

    Args:
        state (bool): If True, include state in display, defaults to True.

    Example:
    ```
    Device Name:..................Living Room Lamp
    Model:........................ESL100
    Subdevice No:.................0
    Type:.........................wifi
    CID:..........................1234567890abcdef
    ```
    """
    # noinspection SpellCheckingInspection
    display_list = [
        ('Device Name:', self.device_name),
        ('Product Type: ', self.product_type),
        ('Model: ', self.device_type),
        ('Subdevice No: ', str(self.sub_device_no)),
        ('Type: ', self.type),
        ('CID: ', self.cid),
        ('Config Module: ', self.config_module),
        ('Connection Type: ', self.connection_type),
        ('Features', self.features),
        ('Last Response: ', self.last_response),
    ]
    if self.uuid is not None:
        display_list.append(('UUID: ', self.uuid))

    for line in display_list:
        print(f'{line[0]:.<30} {line[1]}')
    if state:
        self.state.display()

displayJSON deprecated

displayJSON(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Deprecated

Use to_json() instead

Return JSON details for device. - Deprecated use to_json().

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
@deprecated("Use to_json() instead")
def displayJSON(self, state: bool = True, indent: bool = True) -> str:  # pylint: disable=invalid-name
    """Return JSON details for device. - Deprecated use to_json()."""
    return self.to_json(state, indent)

get_details async

get_details() -> None

Inherited From VeSyncBaseDevice

Get device details.

This method is defined in each device class to contain the logic to pull the device state from the API and update the device's state attribute. The update() method should be called to update the device state.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def get_details(self) -> None:
    r_dict, _ = await self.manager.async_call_api(
        '/v1/device/' + self.cid + '/detail',
        'get',
        headers=self._build_headers(),
    )

    if not isinstance(r_dict, dict):
        LibraryLogger.log_device_api_response_error(
            logger, self.device_name, self.device_type,
            'get_details', "Response is not valid JSON"
        )
        return

    if 'error' in r_dict:
        _ = Helpers.process_dev_response(logger, "get_details", self, r_dict)
        return
    self.state.update_ts()
    resp_model = Response7AOutlet.from_dict(r_dict)
    self.state.connection_status = ConnectionStatus.ONLINE
    self.state.device_status = resp_model.deviceStatus
    self.state.active_time = resp_model.activeTime
    self.state.energy = resp_model.energy
    self.state.power = self.parse_energy_detail(resp_model.power)
    self.state.voltage = self.parse_energy_detail(resp_model.voltage)

get_monthly_energy async

get_monthly_energy() -> None

Inherited From VeSyncOutlet

Build Monthly Energy History Dictionary.

The data is stored in the device.state.monthly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_monthly_energy(self) -> None:
    """Build Monthly Energy History Dictionary.

    The data is stored in the `device.state.monthly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastMonthEnergy')

get_state

get_state(state_attr: str) -> Any

Inherited From VeSyncBaseDevice

Get device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def get_state(self, state_attr: str) -> Any:  # noqa: ANN401
    """Get device state attribute."""
    return getattr(self.state, state_attr)

get_timer async

get_timer() -> None

Inherited From VeSyncBaseDevice

Get timer for device from API and set the state.Timer attribute.

This may not be implemented for all devices. Please open an issue if there is an error.

Note

This method may not be implemented for all devices. Please open an issue if there is an error.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def get_timer(self) -> None:
    r_dict, status_code = await self.manager.async_call_api(
        f"/v2/device/{self.cid}/timer",
        "get",
        headers=Helpers.req_legacy_headers(self.manager),
    )
    if not r_dict or status_code != 200:
        logger.debug("No timer set.")
        self.state.timer = None
        return
    if isinstance(r_dict, list) and len(r_dict) > 0:
        timer_model = Helpers.model_maker(logger, Timer7AItem, "get_timer", r_dict[0])
        if timer_model is None:
            self.state.timer = None
            return
        self.state.timer = Timer(
            timer_duration=int(timer_model.counterTimer),
            id=int(timer_model.timerID),
            action=timer_model.action,
        )
        if timer_model.timerStatus == 'off':
            self.state.timer.pause()
        return
    self.state.timer = None

get_weekly_energy async

get_weekly_energy() -> None

Inherited From VeSyncOutlet

Build weekly energy history dictionary.

The data is stored in the device.state.weekly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_weekly_energy(self) -> None:
    """Build weekly energy history dictionary.

    The data is stored in the `device.state.weekly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastWeekEnergy')

get_yearly_energy async

get_yearly_energy() -> None

Inherited From VeSyncOutlet

Build Yearly Energy Dictionary.

The data is stored in the device.state.yearly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_yearly_energy(self) -> None:
    """Build Yearly Energy Dictionary.

    The data is stored in the `device.state.yearly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastYearEnergy')

parse_energy_detail staticmethod

parse_energy_detail(energy: str | float) -> float

Parse energy details to be compatible with new and old firmware.

Source code in src\pyvesync\devices\vesyncoutlet.py
@staticmethod
def parse_energy_detail(energy: str | float) -> float:
    """Parse energy details to be compatible with new and old firmware."""
    try:
        if isinstance(energy, str) and ':' in energy:
            power = round(float(Helpers.calculate_hex(energy)), 2)
        else:
            power = float(energy)
    except ValueError:
        logger.debug('Error parsing power response - %s', energy)
        power = 0
    return power

set_nightlight_auto async

set_nightlight_auto() -> bool

Inherited From VeSyncOutlet

Set nightlight to auto mode.

Source code in src\pyvesync\base_devices\outlet_base.py
async def set_nightlight_auto(self) -> bool:
    """Set nightlight to auto mode."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.AUTO)

set_nightlight_state async

set_nightlight_state(mode: str) -> bool

Inherited From VeSyncOutlet

Set nightlight mode.

Available nightlight states are found in the device.nightlight_modes attribute.

Parameters:

Name Type Description Default
mode str

Nightlight mode to set.

required

Returns:

Name Type Description
bool bool

True if nightlight mode set successfully, False otherwise.

Source code in src\pyvesync\base_devices\outlet_base.py
async def set_nightlight_state(self, mode: str) -> bool:
    """Set nightlight mode.

    Available nightlight states are found in the `device.nightlight_modes` attribute.

    Args:
        mode (str): Nightlight mode to set.

    Returns:
        bool: True if nightlight mode set successfully, False otherwise.
    """
    del mode  # unused
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
    else:
        logger.debug("Nightlight mode not configured for %s", self.device_name)
    return False

set_state

set_state(state_attr: str, stat_value: Any) -> None

Inherited From VeSyncBaseDevice

Set device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def set_state(self, state_attr: str, stat_value: Any) -> None:  # noqa: ANN401
    """Set device state attribute."""
    setattr(self, state_attr, stat_value)

set_timer async

set_timer(duration: int, action: str | None = None) -> bool

Inherited From VeSyncBaseDevice

Set timer for device.

This may not be implemented for all devices. Please open an issue if there is an error.

Parameters:

Name Type Description Default
duration int

Duration in seconds.

required
action str | None

Action to take when timer expires.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def set_timer(self, duration: int, action: str | None = None) -> bool:
    if action is None:
        action = (
            DeviceStatus.ON
            if self.state.device_status == DeviceStatus.OFF
            else DeviceStatus.OFF
        )
    if not isinstance(action, str) or \
            action not in [DeviceStatus.ON, DeviceStatus.OFF]:
        logger.error("Invalid action for timer - %s", action)
        return False
    update_dict = {
        'action': action,
        'counterTimer': duration,
        "timerStatus": "start",
        'conflictAwayIds': [],
        'conflictScheduleIds': [],
        'conflictTimerIds': [],
    }
    r_dict, status_code = await self.manager.async_call_api(
        f"/v2/device/{self.cid}/timer",
        "post",
        headers=Helpers.req_legacy_headers(self.manager),
        json_object=update_dict,
    )
    if status_code != 200 or not isinstance(r_dict, dict):
        logger.debug("Failed to set timer.")
        return False

    if 'error' in r_dict:
        logger.debug("Error in response: %s", r_dict['error'])
        return False

    result_model = Helpers.model_maker(
        logger, TimerModels.ResultV1SetTimer, "set_timer", r_dict, self
    )
    if result_model is None:
        logger.debug("Failed to set timer.")
        return False
    if result_model.timerID == '':
        logger.debug("Unable to set timer.")
        if result_model.conflictTimerIds:
            logger.debug("Conflicting timer IDs - %s", result_model.conflictTimerIds)
        return False
    self.state.timer = Timer(duration, action, int(result_model.timerID))
    return True

to_dict

to_dict(state: bool = True) -> dict[str, Any]

Inherited From VeSyncBaseDevice

Return device information as a dictionary.

Parameters:

Name Type Description Default
state bool

If True, include state in dictionary, defaults to True.

True

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Dictionary containing device information.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_dict(self, state: bool = True) -> dict[str, Any]:
    """Return device information as a dictionary.

    Args:
        state (bool): If True, include state in dictionary, defaults to True.

    Returns:
        dict[str, Any]: Dictionary containing device information.
    """
    device_dict = {
        "device_name": self.device_name,
        "product_type": self.product_type,
        "model": self.device_type,
        "subdevice_no": str(self.sub_device_no),
        "type": self.type,
        "cid": self.cid,
        "features:": self.features,
        "config_module": self.config_module,
        "connection_type": self.connection_type,
        "last_response": self.last_response,
    }
    state_dict = self.state.to_dict() if state else {}
    return device_dict | state_dict

to_json

to_json(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Print JSON API string for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
str str

JSON formatted string of device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_json(self, state: bool = True, indent: bool = True) -> str:
    """Print JSON API string for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        str: JSON formatted string of device details.
    """
    return self.to_jsonb(state, indent).decode()

to_jsonb

to_jsonb(state: bool = True, indent: bool = True) -> bytes

Inherited From VeSyncBaseDevice

JSON API bytes for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
bytes bytes

JSON formatted bytes of device details.

Example

This is an example without state.

{
    "Device Name": "Living Room Lamp",
    "Model": "ESL100",
    "Subdevice No": "0",
    "Type": "wifi",
    "CID": "1234567890abcdef"
}

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_jsonb(self, state: bool = True, indent: bool = True) -> bytes:
    """JSON API bytes for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        bytes: JSON formatted bytes of device details.

    Example:
        This is an example without state.
        ```
        {
            "Device Name": "Living Room Lamp",
            "Model": "ESL100",
            "Subdevice No": "0",
            "Type": "wifi",
            "CID": "1234567890abcdef"
        }
        ```
    """
    return_dict = self.to_dict(state=state)
    if indent:
        return orjson.dumps(
            return_dict,
            option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS,
        )

    return orjson.dumps(return_dict, option=orjson.OPT_NON_STR_KEYS)

toggle_switch async

toggle_switch(toggle: bool | None = None) -> bool

Inherited From VeSyncBaseToggleDevice

Toggle device power on or off.

Parameters:

Name Type Description Default
toggle bool | None

True to turn on, False to turn off, None to toggle.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def toggle_switch(self, toggle: bool | None = None) -> bool:
    if toggle is None:
        toggle = self.state.device_status != DeviceStatus.ON
    toggle_str = DeviceStatus.ON if toggle else DeviceStatus.OFF
    r_dict, status_code = await self.manager.async_call_api(
        f'/v1/wifi-switch-1.3/{self.cid}/status/{toggle_str}',
        'put',
        headers=Helpers.req_legacy_headers(self.manager),
    )

    if status_code != 200:
        LibraryLogger.log_device_api_response_error(
            logger, self.device_name, self.device_type,
            'toggle_switch', "Response code is not 200"
        )

    if isinstance(r_dict, dict) and 'error' in r_dict:
        _ = Helpers.process_dev_response(logger, "get_details", self, r_dict)
        return False

    self.state.update_ts()
    self.state.device_status = toggle_str
    self.state.connection_status = ConnectionStatus.ONLINE
    return True

turn_off async

turn_off() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device off.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_off(self) -> bool:
    """Turn device off."""
    return await self.toggle_switch(False)

turn_off_nightlight async

turn_off_nightlight() -> bool

Inherited From VeSyncOutlet

Turn off nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_off_nightlight(self) -> bool:
    """Turn off nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.OFF)

turn_on async

turn_on() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device on.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_on(self) -> bool:
    """Turn device on."""
    return await self.toggle_switch(True)

turn_on_nightlight async

turn_on_nightlight() -> bool

Inherited From VeSyncOutlet

Turn on nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_on_nightlight(self) -> bool:
    """Turn on nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.ON)

update async

update() -> None

Inherited From VeSyncBaseDevice

Update device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def update(self) -> None:
    """Update device details."""
    await self.get_details()

update_energy async

update_energy() -> None

Inherited From VeSyncOutlet

Build weekly, monthly and yearly dictionaries.

Source code in src\pyvesync\base_devices\outlet_base.py
async def update_energy(self) -> None:
    """Build weekly, monthly and yearly dictionaries."""
    if self.supports_energy:
        await self.get_weekly_energy()
        await self.get_monthly_energy()
        await self.get_yearly_energy()

pyvesync.devices.vesyncoutlet.VeSyncOutlet10A

Bases: VeSyncOutlet

Etekcity 10A Round Outlets.

Parameters:

Name Type Description Default
details ResponseDeviceDetailsModel

The device details.

required
manager VeSync

The VeSync manager.

required
feature_map OutletMap

The feature map for the device.

required

Attributes:

Name Type Description
state OutletState

The state of the outlet.

last_response ResponseInfo

Last response from API call.

device_status str

Device status.

connection_status str

Connection status.

manager VeSync

Manager object for API calls.

device_name str

Name of device.

device_image str

URL for device image.

cid str

Device ID.

connection_type str

Connection type of device.

device_type str

Type of device.

type str

Type of device.

uuid str

UUID of device, not always present.

config_module str

Configuration module of device.

mac_id str

MAC ID of device.

current_firm_version str

Current firmware version of device.

device_region str

Region of device. (US, EU, etc.)

pid str

Product ID of device, pulled by some devices on update.

sub_device_no int

Sub-device number of device.

product_type str

Product type of device.

features dict

Features of device.

Source code in src\pyvesync\devices\vesyncoutlet.py
class VeSyncOutlet10A(VeSyncOutlet):
    """Etekcity 10A Round Outlets.

    Args:
        details (ResponseDeviceDetailsModel): The device details.
        manager (VeSync): The VeSync manager.
        feature_map (OutletMap): The feature map for the device.

    Attributes:
        state (OutletState): The state of the outlet.
        last_response (ResponseInfo): Last response from API call.
        device_status (str): Device status.
        connection_status (str): Connection status.
        manager (VeSync): Manager object for API calls.
        device_name (str): Name of device.
        device_image (str): URL for device image.
        cid (str): Device ID.
        connection_type (str): Connection type of device.
        device_type (str): Type of device.
        type (str): Type of device.
        uuid (str): UUID of device, not always present.
        config_module (str): Configuration module of device.
        mac_id (str): MAC ID of device.
        current_firm_version (str): Current firmware version of device.
        device_region (str): Region of device. (US, EU, etc.)
        pid (str): Product ID of device, pulled by some devices on update.
        sub_device_no (int): Sub-device number of device.
        product_type (str): Product type of device.
        features (dict): Features of device.
    """

    __slots__ = ()

    def __init__(self, details: ResponseDeviceDetailsModel,
                 manager: VeSync, feature_map: OutletMap) -> None:
        """Initialize 10A outlet class."""
        super().__init__(details, manager, feature_map)
        self.request_keys = [
            "acceptLanguage",
            "appVersion",
            "accountId",
            "mobileId",
            "phoneBrand",
            "phoneOS",
            "timeZone",
            "token",
            "traceId",
            "uuid",
        ]

    def _build_headers(self) -> dict:
        """Build auth headers for 10A Outlet."""
        headers = RequestHeaders.copy()
        headers.update({
            "tz": self.manager.time_zone,
            'tk': self.manager.token,
            'accountid': self.manager.account_id,
        })
        return headers

    def _build_detail_request(self, method: str) -> dict:
        """Build 10A Outlet Request."""
        body = Helpers.get_class_attributes(DefaultValues, self.request_keys)
        body.update(Helpers.get_class_attributes(self.manager, self.request_keys))
        body.update(Helpers.get_class_attributes(self, self.request_keys))
        body['method'] = method
        return body

    def _build_status_request(self, status: str) -> dict:
        """Build 10A Outlet Request to set status."""
        status_keys = ['accountID', 'token', 'timeZone', 'uuid']
        body = Helpers.get_class_attributes(self.manager, status_keys)
        body.update(Helpers.get_class_attributes(self, status_keys))
        body['status'] = status
        return body

    async def get_details(self) -> None:
        body = self._build_detail_request('devicedetail')

        r_dict, _ = await self.manager.async_call_api(
            '/10a/v1/device/devicedetail',
            'post',
            headers=Helpers.req_legacy_headers(self.manager),
            json_object=body,
        )
        r = Helpers.process_dev_response(logger, "get_details", self, r_dict)
        if r is None:
            return

        resp_model = Response10ADetails.from_dict(r)

        self.state.device_status = resp_model.deviceStatus or "off"
        self.state.connection_status = resp_model.connectionStatus or "offline"
        self.state.energy = resp_model.energy or 0
        self.state.power = resp_model.power or 0
        self.state.voltage = resp_model.voltage or 0

    async def toggle_switch(self, toggle: bool | None = None) -> bool:
        if toggle is None:
            toggle = self.state.device_status != DeviceStatus.ON
        toggle_str = DeviceStatus.ON if toggle else DeviceStatus.OFF
        body = self._build_status_request(toggle_str)
        headers = self._build_headers()

        r_dict, _ = await self.manager.async_call_api(
            '/10a/v1/device/devicestatus',
            'put',
            headers=headers,
            json_object=body,
        )
        response = Helpers.process_dev_response(logger, "toggle_switch", self, r_dict)
        if response is None:
            return False

        self.state.device_status = toggle_str
        self.state.connection_status = ConnectionStatus.ONLINE
        return True

Attributes

cid instance-attribute

cid: str = cid

Inherited From VeSyncBaseDevice

config_module instance-attribute

config_module: str = configModule

Inherited From VeSyncBaseDevice

connection_type instance-attribute

connection_type: str | None = connectionType

Inherited From VeSyncBaseDevice

current_firm_version instance-attribute

current_firm_version = currentFirmVersion

Inherited From VeSyncBaseDevice

device_image instance-attribute

device_image: str | None = deviceImg

Inherited From VeSyncBaseDevice

device_name instance-attribute

device_name: str = deviceName

Inherited From VeSyncBaseDevice

device_region instance-attribute

device_region: str | None = deviceRegion

Inherited From VeSyncBaseDevice

device_type instance-attribute

device_type: str = deviceType

Inherited From VeSyncBaseDevice

enabled instance-attribute

enabled: bool = True

Inherited From VeSyncBaseDevice

features instance-attribute

features: list[str] = features

Inherited From VeSyncBaseDevice

firmware_update property

firmware_update: bool

Inherited From VeSyncBaseDevice

Return True if firmware update available.

This is going to be updated.

is_on property

is_on: bool

Inherited From VeSyncBaseDevice

Return true if device is on.

last_response instance-attribute

last_response: ResponseInfo | None = None

Inherited From VeSyncBaseDevice

mac_id instance-attribute

mac_id: str | None = macID

Inherited From VeSyncBaseDevice

manager instance-attribute

manager = manager

Inherited From VeSyncBaseDevice

nightlight_modes instance-attribute

nightlight_modes = nightlight_modes

Inherited From VeSyncOutlet

pid instance-attribute

pid: str | None = None

Inherited From VeSyncBaseDevice

product_type instance-attribute

product_type: str = product_type

Inherited From VeSyncBaseDevice

request_keys instance-attribute

request_keys = [
    'acceptLanguage',
    'appVersion',
    'accountId',
    'mobileId',
    'phoneBrand',
    'phoneOS',
    'timeZone',
    'token',
    'traceId',
    'uuid',
]

state instance-attribute

state: OutletState = OutletState(self, details, feature_map)

Inherited From VeSyncBaseDevice

sub_device_no instance-attribute

sub_device_no: int | None = subDeviceNo

Inherited From VeSyncBaseDevice

supports_energy property

supports_energy: bool

Inherited From VeSyncOutlet

Return True if device supports energy.

Returns:

Name Type Description
bool bool

True if device supports energy, False otherwise.

supports_nightlight property

supports_nightlight: bool

Inherited From VeSyncOutlet

Return True if device supports nightlight.

Returns:

Name Type Description
bool bool

True if device supports nightlight, False otherwise.

type instance-attribute

type: str | None = type

Inherited From VeSyncBaseDevice

uuid instance-attribute

uuid: str | None = uuid

Inherited From VeSyncBaseDevice

Functions

clear_timer async

clear_timer() -> bool

Inherited From VeSyncBaseDevice

Clear timer for device from API.

This may not be implemented for all devices. Please open an issue if there is an error.

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def clear_timer(self) -> bool:
    """Clear timer for device from API.

    This may not be implemented for all devices. Please open an issue
    if there is an error.

    Returns:
        bool: True if successful, False otherwise.
    """
    logger.debug('Not implemented - clear_timer')
    return False

display

display(state: bool = True) -> None

Inherited From VeSyncBaseDevice

Print formatted static device info to stdout.

Parameters:

Name Type Description Default
state bool

If True, include state in display, defaults to True.

True

Example:

Device Name:..................Living Room Lamp
Model:........................ESL100
Subdevice No:.................0
Type:.........................wifi
CID:..........................1234567890abcdef

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def display(self, state: bool = True) -> None:
    """Print formatted static device info to stdout.

    Args:
        state (bool): If True, include state in display, defaults to True.

    Example:
    ```
    Device Name:..................Living Room Lamp
    Model:........................ESL100
    Subdevice No:.................0
    Type:.........................wifi
    CID:..........................1234567890abcdef
    ```
    """
    # noinspection SpellCheckingInspection
    display_list = [
        ('Device Name:', self.device_name),
        ('Product Type: ', self.product_type),
        ('Model: ', self.device_type),
        ('Subdevice No: ', str(self.sub_device_no)),
        ('Type: ', self.type),
        ('CID: ', self.cid),
        ('Config Module: ', self.config_module),
        ('Connection Type: ', self.connection_type),
        ('Features', self.features),
        ('Last Response: ', self.last_response),
    ]
    if self.uuid is not None:
        display_list.append(('UUID: ', self.uuid))

    for line in display_list:
        print(f'{line[0]:.<30} {line[1]}')
    if state:
        self.state.display()

displayJSON deprecated

displayJSON(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Deprecated

Use to_json() instead

Return JSON details for device. - Deprecated use to_json().

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
@deprecated("Use to_json() instead")
def displayJSON(self, state: bool = True, indent: bool = True) -> str:  # pylint: disable=invalid-name
    """Return JSON details for device. - Deprecated use to_json()."""
    return self.to_json(state, indent)

get_details async

get_details() -> None

Inherited From VeSyncBaseDevice

Get device details.

This method is defined in each device class to contain the logic to pull the device state from the API and update the device's state attribute. The update() method should be called to update the device state.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def get_details(self) -> None:
    body = self._build_detail_request('devicedetail')

    r_dict, _ = await self.manager.async_call_api(
        '/10a/v1/device/devicedetail',
        'post',
        headers=Helpers.req_legacy_headers(self.manager),
        json_object=body,
    )
    r = Helpers.process_dev_response(logger, "get_details", self, r_dict)
    if r is None:
        return

    resp_model = Response10ADetails.from_dict(r)

    self.state.device_status = resp_model.deviceStatus or "off"
    self.state.connection_status = resp_model.connectionStatus or "offline"
    self.state.energy = resp_model.energy or 0
    self.state.power = resp_model.power or 0
    self.state.voltage = resp_model.voltage or 0

get_monthly_energy async

get_monthly_energy() -> None

Inherited From VeSyncOutlet

Build Monthly Energy History Dictionary.

The data is stored in the device.state.monthly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_monthly_energy(self) -> None:
    """Build Monthly Energy History Dictionary.

    The data is stored in the `device.state.monthly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastMonthEnergy')

get_state

get_state(state_attr: str) -> Any

Inherited From VeSyncBaseDevice

Get device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def get_state(self, state_attr: str) -> Any:  # noqa: ANN401
    """Get device state attribute."""
    return getattr(self.state, state_attr)

get_timer async

get_timer() -> Timer | None

Inherited From VeSyncBaseDevice

Get timer for device from API and set the state.Timer attribute.

This may not be implemented for all devices. Please open an issue if there is an error.

Note

This method may not be implemented for all devices. Please open an issue if there is an error.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def get_timer(self) -> Timer | None:
    """Get timer for device from API and set the `state.Timer` attribute.

    This may not be implemented for all devices. Please open an issue
    if there is an error.

    Note:
        This method may not be implemented for all devices. Please
        open an issue if there is an error.
    """
    logger.debug('Not implemented - get_timer')
    return None

get_weekly_energy async

get_weekly_energy() -> None

Inherited From VeSyncOutlet

Build weekly energy history dictionary.

The data is stored in the device.state.weekly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_weekly_energy(self) -> None:
    """Build weekly energy history dictionary.

    The data is stored in the `device.state.weekly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastWeekEnergy')

get_yearly_energy async

get_yearly_energy() -> None

Inherited From VeSyncOutlet

Build Yearly Energy Dictionary.

The data is stored in the device.state.yearly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_yearly_energy(self) -> None:
    """Build Yearly Energy Dictionary.

    The data is stored in the `device.state.yearly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastYearEnergy')

set_nightlight_auto async

set_nightlight_auto() -> bool

Inherited From VeSyncOutlet

Set nightlight to auto mode.

Source code in src\pyvesync\base_devices\outlet_base.py
async def set_nightlight_auto(self) -> bool:
    """Set nightlight to auto mode."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.AUTO)

set_nightlight_state async

set_nightlight_state(mode: str) -> bool

Inherited From VeSyncOutlet

Set nightlight mode.

Available nightlight states are found in the device.nightlight_modes attribute.

Parameters:

Name Type Description Default
mode str

Nightlight mode to set.

required

Returns:

Name Type Description
bool bool

True if nightlight mode set successfully, False otherwise.

Source code in src\pyvesync\base_devices\outlet_base.py
async def set_nightlight_state(self, mode: str) -> bool:
    """Set nightlight mode.

    Available nightlight states are found in the `device.nightlight_modes` attribute.

    Args:
        mode (str): Nightlight mode to set.

    Returns:
        bool: True if nightlight mode set successfully, False otherwise.
    """
    del mode  # unused
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
    else:
        logger.debug("Nightlight mode not configured for %s", self.device_name)
    return False

set_state

set_state(state_attr: str, stat_value: Any) -> None

Inherited From VeSyncBaseDevice

Set device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def set_state(self, state_attr: str, stat_value: Any) -> None:  # noqa: ANN401
    """Set device state attribute."""
    setattr(self, state_attr, stat_value)

set_timer async

set_timer(duration: int, action: str | None = None) -> bool

Inherited From VeSyncBaseDevice

Set timer for device.

This may not be implemented for all devices. Please open an issue if there is an error.

Parameters:

Name Type Description Default
duration int

Duration in seconds.

required
action str | None

Action to take when timer expires.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def set_timer(self, duration: int, action: str | None = None) -> bool:
    """Set timer for device.

    This may not be implemented for all devices. Please open an issue
    if there is an error.

    Args:
        duration (int): Duration in seconds.
        action (str | None): Action to take when timer expires.

    Returns:
        bool: True if successful, False otherwise.
    """
    del duration
    del action
    logger.debug('Not implemented - set_timer')
    return False

to_dict

to_dict(state: bool = True) -> dict[str, Any]

Inherited From VeSyncBaseDevice

Return device information as a dictionary.

Parameters:

Name Type Description Default
state bool

If True, include state in dictionary, defaults to True.

True

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Dictionary containing device information.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_dict(self, state: bool = True) -> dict[str, Any]:
    """Return device information as a dictionary.

    Args:
        state (bool): If True, include state in dictionary, defaults to True.

    Returns:
        dict[str, Any]: Dictionary containing device information.
    """
    device_dict = {
        "device_name": self.device_name,
        "product_type": self.product_type,
        "model": self.device_type,
        "subdevice_no": str(self.sub_device_no),
        "type": self.type,
        "cid": self.cid,
        "features:": self.features,
        "config_module": self.config_module,
        "connection_type": self.connection_type,
        "last_response": self.last_response,
    }
    state_dict = self.state.to_dict() if state else {}
    return device_dict | state_dict

to_json

to_json(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Print JSON API string for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
str str

JSON formatted string of device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_json(self, state: bool = True, indent: bool = True) -> str:
    """Print JSON API string for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        str: JSON formatted string of device details.
    """
    return self.to_jsonb(state, indent).decode()

to_jsonb

to_jsonb(state: bool = True, indent: bool = True) -> bytes

Inherited From VeSyncBaseDevice

JSON API bytes for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
bytes bytes

JSON formatted bytes of device details.

Example

This is an example without state.

{
    "Device Name": "Living Room Lamp",
    "Model": "ESL100",
    "Subdevice No": "0",
    "Type": "wifi",
    "CID": "1234567890abcdef"
}

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_jsonb(self, state: bool = True, indent: bool = True) -> bytes:
    """JSON API bytes for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        bytes: JSON formatted bytes of device details.

    Example:
        This is an example without state.
        ```
        {
            "Device Name": "Living Room Lamp",
            "Model": "ESL100",
            "Subdevice No": "0",
            "Type": "wifi",
            "CID": "1234567890abcdef"
        }
        ```
    """
    return_dict = self.to_dict(state=state)
    if indent:
        return orjson.dumps(
            return_dict,
            option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS,
        )

    return orjson.dumps(return_dict, option=orjson.OPT_NON_STR_KEYS)

toggle_switch async

toggle_switch(toggle: bool | None = None) -> bool

Inherited From VeSyncBaseToggleDevice

Toggle device power on or off.

Parameters:

Name Type Description Default
toggle bool | None

True to turn on, False to turn off, None to toggle.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def toggle_switch(self, toggle: bool | None = None) -> bool:
    if toggle is None:
        toggle = self.state.device_status != DeviceStatus.ON
    toggle_str = DeviceStatus.ON if toggle else DeviceStatus.OFF
    body = self._build_status_request(toggle_str)
    headers = self._build_headers()

    r_dict, _ = await self.manager.async_call_api(
        '/10a/v1/device/devicestatus',
        'put',
        headers=headers,
        json_object=body,
    )
    response = Helpers.process_dev_response(logger, "toggle_switch", self, r_dict)
    if response is None:
        return False

    self.state.device_status = toggle_str
    self.state.connection_status = ConnectionStatus.ONLINE
    return True

turn_off async

turn_off() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device off.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_off(self) -> bool:
    """Turn device off."""
    return await self.toggle_switch(False)

turn_off_nightlight async

turn_off_nightlight() -> bool

Inherited From VeSyncOutlet

Turn off nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_off_nightlight(self) -> bool:
    """Turn off nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.OFF)

turn_on async

turn_on() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device on.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_on(self) -> bool:
    """Turn device on."""
    return await self.toggle_switch(True)

turn_on_nightlight async

turn_on_nightlight() -> bool

Inherited From VeSyncOutlet

Turn on nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_on_nightlight(self) -> bool:
    """Turn on nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.ON)

update async

update() -> None

Inherited From VeSyncBaseDevice

Update device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def update(self) -> None:
    """Update device details."""
    await self.get_details()

update_energy async

update_energy() -> None

Inherited From VeSyncOutlet

Build weekly, monthly and yearly dictionaries.

Source code in src\pyvesync\base_devices\outlet_base.py
async def update_energy(self) -> None:
    """Build weekly, monthly and yearly dictionaries."""
    if self.supports_energy:
        await self.get_weekly_energy()
        await self.get_monthly_energy()
        await self.get_yearly_energy()

pyvesync.devices.vesyncoutlet.VeSyncOutlet15A

Bases: BypassV1Mixin, VeSyncOutlet

Class for Etekcity 15A Rectangular Outlets.

Parameters:

Name Type Description Default
details ResponseDeviceDetailsModel

The device details.

required
manager VeSync

The VeSync manager.

required
feature_map OutletMap

The feature map for the device.

required

Attributes:

Name Type Description
state OutletState

The state of the outlet.

last_response ResponseInfo

Last response from API call.

device_status str

Device status.

connection_status str

Connection status.

manager VeSync

Manager object for API calls.

device_name str

Name of device.

device_image str

URL for device image.

cid str

Device ID.

connection_type str

Connection type of device.

device_type str

Type of device.

type str

Type of device.

uuid str

UUID of device, not always present.

config_module str

Configuration module of device.

mac_id str

MAC ID of device.

current_firm_version str

Current firmware version of device.

device_region str

Region of device. (US, EU, etc.)

pid str

Product ID of device, pulled by some devices on update.

sub_device_no int

Sub-device number of device.

product_type str

Product type of device.

features dict

Features of device.

Source code in src\pyvesync\devices\vesyncoutlet.py
class VeSyncOutlet15A(BypassV1Mixin, VeSyncOutlet):
    """Class for Etekcity 15A Rectangular Outlets.

    Args:
        details (ResponseDeviceDetailsModel): The device details.
        manager (VeSync): The VeSync manager.
        feature_map (OutletMap): The feature map for the device.

    Attributes:
        state (OutletState): The state of the outlet.
        last_response (ResponseInfo): Last response from API call.
        device_status (str): Device status.
        connection_status (str): Connection status.
        manager (VeSync): Manager object for API calls.
        device_name (str): Name of device.
        device_image (str): URL for device image.
        cid (str): Device ID.
        connection_type (str): Connection type of device.
        device_type (str): Type of device.
        type (str): Type of device.
        uuid (str): UUID of device, not always present.
        config_module (str): Configuration module of device.
        mac_id (str): MAC ID of device.
        current_firm_version (str): Current firmware version of device.
        device_region (str): Region of device. (US, EU, etc.)
        pid (str): Product ID of device, pulled by some devices on update.
        sub_device_no (int): Sub-device number of device.
        product_type (str): Product type of device.
        features (dict): Features of device.
    """

    __slots__ = ()

    def __init__(self, details: ResponseDeviceDetailsModel,
                 manager: VeSync, feature_map: OutletMap) -> None:
        """Initialize 15A rectangular outlets."""
        super().__init__(details, manager, feature_map)

    async def get_details(self) -> None:

        r_dict = await self.call_bypassv1_api(
            Request15ADetails,
            method='deviceDetail',
            endpoint='deviceDetail'
        )

        r = Helpers.process_dev_response(logger, "get_details", self, r_dict)
        if r is None:
            return

        resp_model = Response15ADetails.from_dict(r)
        result = resp_model.result
        self.state.device_status = result.deviceStatus
        self.state.connection_status = result.connectionStatus
        self.state.nightlight_status = result.nightLightStatus
        self.state.nightlight_brightness = result.nightLightBrightness
        self.state.nightlight_automode = result.nightLightAutoMode
        self.state.active_time = result.activeTime
        self.state.power = result.power or 0
        self.state.voltage = result.voltage or 0
        self.state.energy = result.energy or 0

    async def toggle_switch(self, toggle: bool | None = None) -> bool:
        if toggle is None:
            toggle = self.state.device_status != DeviceStatus.ON
        toggle_str = DeviceStatus.ON if toggle else DeviceStatus.OFF
        r_dict = await self.call_bypassv1_api(
            Request15AStatus,
            update_dict={'status': toggle_str},
            method='deviceStatus',
            endpoint='deviceStatus'
        )
        response = Helpers.process_dev_response(logger, "toggle_switch", self, r_dict)
        if response is None:
            return False

        self.state.device_status = toggle_str
        self.state.connection_status = ConnectionStatus.ONLINE
        return True

    async def set_nightlight_state(self, mode: str) -> bool:
        """Set nightlight state for 15A Outlets."""
        if mode.lower() not in self.nightlight_modes:
            logger.error("Invalid nightlight mode - %s", mode)
            return False
        mode = mode.lower()
        r_dict = await self.call_bypassv1_api(
            Request15ANightlight,
            update_dict={'mode': mode},
            method='outletNightLightCtl',
            endpoint='outletNightLightCtl'
        )

        response = Helpers.process_dev_response(
            logger, "set_nightlight_state", self, r_dict
            )
        if response is None:
            return False

        self.state.nightlight_status = mode
        self.state.connection_status = ConnectionStatus.ONLINE
        return True

    async def get_timer(self) -> None:
        method = 'getTimers'
        endpoint = f'/timer/{method}'
        r_dict = await self.call_bypassv1_api(
            Request15ADetails,
            method=method,
            endpoint=endpoint
        )
        result_model = process_bypassv1_result(
            self, logger, "get_timer", r_dict, TimerModels.ResultV1GetTimer
        )
        if result_model is None:
            return
        timers = result_model.timers
        if not isinstance(timers, list) or len(timers) == 0:
            self.state.timer = None
            return
        timer = timers[0]
        if not isinstance(timer, TimerModels.TimerItemV1):
            logger.debug("Invalid timer model - %s", timer)
            return
        self.state.timer = Timer(
            timer_duration=int(timer.counterTimer),
            id=int(timer.timerID),
            action=timer.action,
        )

    async def set_timer(self, duration: int, action: str | None = None) -> bool:
        if action is None:
            action = (
                DeviceStatus.ON
                if self.state.device_status == DeviceStatus.OFF
                else DeviceStatus.OFF
            )
        if not isinstance(action, str) or \
                action not in [DeviceStatus.ON, DeviceStatus.OFF]:
            logger.error("Invalid action for timer - %s", action)
            return False
        update_dict = {
            'action': action,
            'counterTime': str(duration),
        }
        r_dict = await self.call_bypassv1_api(
            TimerModels.RequestV1SetTime,
            update_dict=update_dict,
            method='addTimer',
            endpoint='timer/addTimer'
        )
        result_model = process_bypassv1_result(
            self, logger, "set_timer", r_dict, TimerModels.ResultV1SetTimer
        )
        if result_model is None:
            return False
        self.state.timer = Timer(duration, action, int(result_model.timerID))
        return True

    async def clear_timer(self) -> bool:
        if self.state.timer is None:
            logger.debug("No timer set, nothing to clear, run get_timer().")
            return False
        if self.state.timer.time_remaining == 0:
            logger.debug("Timer already ended.")
            self.state.timer = None
            return True
        r_dict = await self.call_bypassv1_api(
            TimerModels.RequestV1ClearTimer,
            {'timerId': str(self.state.timer.id)},
            method='deleteTimer',
            endpoint='timer/deleteTimer'
        )
        r_dict = Helpers.process_dev_response(
            logger, "clear_timer", self, r_dict
        )
        if r_dict is None:
            if self.last_response is not None and \
                    self.last_response.name == 'TIMER_NOT_EXISTS':
                self.state.timer = None
            return False
        self.state.timer = None
        return True

Attributes

cid instance-attribute

cid: str = cid

Inherited From VeSyncBaseDevice

config_module instance-attribute

config_module: str = configModule

Inherited From VeSyncBaseDevice

connection_type instance-attribute

connection_type: str | None = connectionType

Inherited From VeSyncBaseDevice

current_firm_version instance-attribute

current_firm_version = currentFirmVersion

Inherited From VeSyncBaseDevice

device_image instance-attribute

device_image: str | None = deviceImg

Inherited From VeSyncBaseDevice

device_name instance-attribute

device_name: str = deviceName

Inherited From VeSyncBaseDevice

device_region instance-attribute

device_region: str | None = deviceRegion

Inherited From VeSyncBaseDevice

device_type instance-attribute

device_type: str = deviceType

Inherited From VeSyncBaseDevice

enabled instance-attribute

enabled: bool = True

Inherited From VeSyncBaseDevice

features instance-attribute

features: list[str] = features

Inherited From VeSyncBaseDevice

firmware_update property

firmware_update: bool

Inherited From VeSyncBaseDevice

Return True if firmware update available.

This is going to be updated.

is_on property

is_on: bool

Inherited From VeSyncBaseDevice

Return true if device is on.

last_response instance-attribute

last_response: ResponseInfo | None = None

Inherited From VeSyncBaseDevice

mac_id instance-attribute

mac_id: str | None = macID

Inherited From VeSyncBaseDevice

manager instance-attribute

manager: VeSync

Inherited From BypassV1Mixin

nightlight_modes instance-attribute

nightlight_modes = nightlight_modes

Inherited From VeSyncOutlet

pid instance-attribute

pid: str | None = None

Inherited From VeSyncBaseDevice

product_type instance-attribute

product_type: str = product_type

Inherited From VeSyncBaseDevice

request_keys class-attribute

request_keys: list[str] = [
    'acceptLanguage',
    'appVersion',
    'phoneBrand',
    'phoneOS',
    'accountID',
    'cid',
    'configModule',
    'debugMode',
    'traceId',
    'timeZone',
    'token',
    'userCountryCode',
    'uuid',
    'configModel',
    'deviceId',
]

Inherited From BypassV1Mixin

state instance-attribute

state: OutletState = OutletState(self, details, feature_map)

Inherited From VeSyncBaseDevice

sub_device_no instance-attribute

sub_device_no: int | None = subDeviceNo

Inherited From VeSyncBaseDevice

supports_energy property

supports_energy: bool

Inherited From VeSyncOutlet

Return True if device supports energy.

Returns:

Name Type Description
bool bool

True if device supports energy, False otherwise.

supports_nightlight property

supports_nightlight: bool

Inherited From VeSyncOutlet

Return True if device supports nightlight.

Returns:

Name Type Description
bool bool

True if device supports nightlight, False otherwise.

type instance-attribute

type: str | None = type

Inherited From VeSyncBaseDevice

uuid instance-attribute

uuid: str | None = uuid

Inherited From VeSyncBaseDevice

Functions

call_bypassv1_api async

call_bypassv1_api(
    request_model: type[RequestBypassV1],
    update_dict: dict | None = None,
    method: str = 'bypass',
    endpoint: str = 'bypass',
) -> dict | None

Inherited From BypassV1Mixin

Send ByPass V1 API request.

This uses the _build_request method to send API requests to the Bypass V1 API. The endpoint can be overridden with the endpoint argument.

Parameters:

Name Type Description Default
request_model type[RequestBypassV1]

The request model to use.

required
update_dict dict

Additional keys to add on.

None
method str

The method to use in the outer body.

'bypass'
endpoint str | None

The last part of the url path, defaults to bypass, e.g. /cloud/v1/deviceManaged/bypass.

'bypass'

Returns:

Name Type Description
bytes dict | None

The response from the API request.

Source code in src\pyvesync\utils\device_mixins.py
async def call_bypassv1_api(
    self,
    request_model: type[RequestBypassV1],
    update_dict: dict | None = None,
    method: str = "bypass",
    endpoint: str = "bypass",
) -> dict | None:
    """Send ByPass V1 API request.

    This uses the `_build_request` method to send API requests to the Bypass V1 API.
    The endpoint can be overridden with the `endpoint` argument.

    Args:
        request_model (type[RequestBypassV1]): The request model to use.
        update_dict (dict): Additional keys to add on.
        method (str): The method to use in the outer body.
        endpoint (str | None): The last part of the url path, defaults to
            `bypass`, e.g. `/cloud/v1/deviceManaged/bypass`.

    Returns:
        bytes: The response from the API request.
    """
    request = self._build_request(request_model, update_dict, method)
    url_path = BYPASS_V1_PATH + endpoint
    resp_dict, _ = await self.manager.async_call_api(
        url_path, "post", request, Helpers.req_header_bypass()
    )

    return resp_dict

clear_timer async

clear_timer() -> bool

Inherited From VeSyncBaseDevice

Clear timer for device from API.

This may not be implemented for all devices. Please open an issue if there is an error.

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def clear_timer(self) -> bool:
    if self.state.timer is None:
        logger.debug("No timer set, nothing to clear, run get_timer().")
        return False
    if self.state.timer.time_remaining == 0:
        logger.debug("Timer already ended.")
        self.state.timer = None
        return True
    r_dict = await self.call_bypassv1_api(
        TimerModels.RequestV1ClearTimer,
        {'timerId': str(self.state.timer.id)},
        method='deleteTimer',
        endpoint='timer/deleteTimer'
    )
    r_dict = Helpers.process_dev_response(
        logger, "clear_timer", self, r_dict
    )
    if r_dict is None:
        if self.last_response is not None and \
                self.last_response.name == 'TIMER_NOT_EXISTS':
            self.state.timer = None
        return False
    self.state.timer = None
    return True

display

display(state: bool = True) -> None

Inherited From VeSyncBaseDevice

Print formatted static device info to stdout.

Parameters:

Name Type Description Default
state bool

If True, include state in display, defaults to True.

True

Example:

Device Name:..................Living Room Lamp
Model:........................ESL100
Subdevice No:.................0
Type:.........................wifi
CID:..........................1234567890abcdef

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def display(self, state: bool = True) -> None:
    """Print formatted static device info to stdout.

    Args:
        state (bool): If True, include state in display, defaults to True.

    Example:
    ```
    Device Name:..................Living Room Lamp
    Model:........................ESL100
    Subdevice No:.................0
    Type:.........................wifi
    CID:..........................1234567890abcdef
    ```
    """
    # noinspection SpellCheckingInspection
    display_list = [
        ('Device Name:', self.device_name),
        ('Product Type: ', self.product_type),
        ('Model: ', self.device_type),
        ('Subdevice No: ', str(self.sub_device_no)),
        ('Type: ', self.type),
        ('CID: ', self.cid),
        ('Config Module: ', self.config_module),
        ('Connection Type: ', self.connection_type),
        ('Features', self.features),
        ('Last Response: ', self.last_response),
    ]
    if self.uuid is not None:
        display_list.append(('UUID: ', self.uuid))

    for line in display_list:
        print(f'{line[0]:.<30} {line[1]}')
    if state:
        self.state.display()

displayJSON deprecated

displayJSON(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Deprecated

Use to_json() instead

Return JSON details for device. - Deprecated use to_json().

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
@deprecated("Use to_json() instead")
def displayJSON(self, state: bool = True, indent: bool = True) -> str:  # pylint: disable=invalid-name
    """Return JSON details for device. - Deprecated use to_json()."""
    return self.to_json(state, indent)

get_details async

get_details() -> None

Inherited From VeSyncBaseDevice

Get device details.

This method is defined in each device class to contain the logic to pull the device state from the API and update the device's state attribute. The update() method should be called to update the device state.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def get_details(self) -> None:

    r_dict = await self.call_bypassv1_api(
        Request15ADetails,
        method='deviceDetail',
        endpoint='deviceDetail'
    )

    r = Helpers.process_dev_response(logger, "get_details", self, r_dict)
    if r is None:
        return

    resp_model = Response15ADetails.from_dict(r)
    result = resp_model.result
    self.state.device_status = result.deviceStatus
    self.state.connection_status = result.connectionStatus
    self.state.nightlight_status = result.nightLightStatus
    self.state.nightlight_brightness = result.nightLightBrightness
    self.state.nightlight_automode = result.nightLightAutoMode
    self.state.active_time = result.activeTime
    self.state.power = result.power or 0
    self.state.voltage = result.voltage or 0
    self.state.energy = result.energy or 0

get_monthly_energy async

get_monthly_energy() -> None

Inherited From VeSyncOutlet

Build Monthly Energy History Dictionary.

The data is stored in the device.state.monthly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_monthly_energy(self) -> None:
    """Build Monthly Energy History Dictionary.

    The data is stored in the `device.state.monthly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastMonthEnergy')

get_state

get_state(state_attr: str) -> Any

Inherited From VeSyncBaseDevice

Get device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def get_state(self, state_attr: str) -> Any:  # noqa: ANN401
    """Get device state attribute."""
    return getattr(self.state, state_attr)

get_timer async

get_timer() -> None

Inherited From VeSyncBaseDevice

Get timer for device from API and set the state.Timer attribute.

This may not be implemented for all devices. Please open an issue if there is an error.

Note

This method may not be implemented for all devices. Please open an issue if there is an error.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def get_timer(self) -> None:
    method = 'getTimers'
    endpoint = f'/timer/{method}'
    r_dict = await self.call_bypassv1_api(
        Request15ADetails,
        method=method,
        endpoint=endpoint
    )
    result_model = process_bypassv1_result(
        self, logger, "get_timer", r_dict, TimerModels.ResultV1GetTimer
    )
    if result_model is None:
        return
    timers = result_model.timers
    if not isinstance(timers, list) or len(timers) == 0:
        self.state.timer = None
        return
    timer = timers[0]
    if not isinstance(timer, TimerModels.TimerItemV1):
        logger.debug("Invalid timer model - %s", timer)
        return
    self.state.timer = Timer(
        timer_duration=int(timer.counterTimer),
        id=int(timer.timerID),
        action=timer.action,
    )

get_weekly_energy async

get_weekly_energy() -> None

Inherited From VeSyncOutlet

Build weekly energy history dictionary.

The data is stored in the device.state.weekly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_weekly_energy(self) -> None:
    """Build weekly energy history dictionary.

    The data is stored in the `device.state.weekly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastWeekEnergy')

get_yearly_energy async

get_yearly_energy() -> None

Inherited From VeSyncOutlet

Build Yearly Energy Dictionary.

The data is stored in the device.state.yearly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_yearly_energy(self) -> None:
    """Build Yearly Energy Dictionary.

    The data is stored in the `device.state.yearly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastYearEnergy')

set_nightlight_auto async

set_nightlight_auto() -> bool

Inherited From VeSyncOutlet

Set nightlight to auto mode.

Source code in src\pyvesync\base_devices\outlet_base.py
async def set_nightlight_auto(self) -> bool:
    """Set nightlight to auto mode."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.AUTO)

set_nightlight_state async

set_nightlight_state(mode: str) -> bool

Inherited From VeSyncOutlet

Set nightlight mode.

Available nightlight states are found in the device.nightlight_modes attribute.

Parameters:

Name Type Description Default
mode str

Nightlight mode to set.

required

Returns:

Name Type Description
bool bool

True if nightlight mode set successfully, False otherwise.

Set nightlight state for 15A Outlets.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def set_nightlight_state(self, mode: str) -> bool:
    """Set nightlight state for 15A Outlets."""
    if mode.lower() not in self.nightlight_modes:
        logger.error("Invalid nightlight mode - %s", mode)
        return False
    mode = mode.lower()
    r_dict = await self.call_bypassv1_api(
        Request15ANightlight,
        update_dict={'mode': mode},
        method='outletNightLightCtl',
        endpoint='outletNightLightCtl'
    )

    response = Helpers.process_dev_response(
        logger, "set_nightlight_state", self, r_dict
        )
    if response is None:
        return False

    self.state.nightlight_status = mode
    self.state.connection_status = ConnectionStatus.ONLINE
    return True

set_state

set_state(state_attr: str, stat_value: Any) -> None

Inherited From VeSyncBaseDevice

Set device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def set_state(self, state_attr: str, stat_value: Any) -> None:  # noqa: ANN401
    """Set device state attribute."""
    setattr(self, state_attr, stat_value)

set_timer async

set_timer(duration: int, action: str | None = None) -> bool

Inherited From VeSyncBaseDevice

Set timer for device.

This may not be implemented for all devices. Please open an issue if there is an error.

Parameters:

Name Type Description Default
duration int

Duration in seconds.

required
action str | None

Action to take when timer expires.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def set_timer(self, duration: int, action: str | None = None) -> bool:
    if action is None:
        action = (
            DeviceStatus.ON
            if self.state.device_status == DeviceStatus.OFF
            else DeviceStatus.OFF
        )
    if not isinstance(action, str) or \
            action not in [DeviceStatus.ON, DeviceStatus.OFF]:
        logger.error("Invalid action for timer - %s", action)
        return False
    update_dict = {
        'action': action,
        'counterTime': str(duration),
    }
    r_dict = await self.call_bypassv1_api(
        TimerModels.RequestV1SetTime,
        update_dict=update_dict,
        method='addTimer',
        endpoint='timer/addTimer'
    )
    result_model = process_bypassv1_result(
        self, logger, "set_timer", r_dict, TimerModels.ResultV1SetTimer
    )
    if result_model is None:
        return False
    self.state.timer = Timer(duration, action, int(result_model.timerID))
    return True

to_dict

to_dict(state: bool = True) -> dict[str, Any]

Inherited From VeSyncBaseDevice

Return device information as a dictionary.

Parameters:

Name Type Description Default
state bool

If True, include state in dictionary, defaults to True.

True

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Dictionary containing device information.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_dict(self, state: bool = True) -> dict[str, Any]:
    """Return device information as a dictionary.

    Args:
        state (bool): If True, include state in dictionary, defaults to True.

    Returns:
        dict[str, Any]: Dictionary containing device information.
    """
    device_dict = {
        "device_name": self.device_name,
        "product_type": self.product_type,
        "model": self.device_type,
        "subdevice_no": str(self.sub_device_no),
        "type": self.type,
        "cid": self.cid,
        "features:": self.features,
        "config_module": self.config_module,
        "connection_type": self.connection_type,
        "last_response": self.last_response,
    }
    state_dict = self.state.to_dict() if state else {}
    return device_dict | state_dict

to_json

to_json(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Print JSON API string for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
str str

JSON formatted string of device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_json(self, state: bool = True, indent: bool = True) -> str:
    """Print JSON API string for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        str: JSON formatted string of device details.
    """
    return self.to_jsonb(state, indent).decode()

to_jsonb

to_jsonb(state: bool = True, indent: bool = True) -> bytes

Inherited From VeSyncBaseDevice

JSON API bytes for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
bytes bytes

JSON formatted bytes of device details.

Example

This is an example without state.

{
    "Device Name": "Living Room Lamp",
    "Model": "ESL100",
    "Subdevice No": "0",
    "Type": "wifi",
    "CID": "1234567890abcdef"
}

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_jsonb(self, state: bool = True, indent: bool = True) -> bytes:
    """JSON API bytes for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        bytes: JSON formatted bytes of device details.

    Example:
        This is an example without state.
        ```
        {
            "Device Name": "Living Room Lamp",
            "Model": "ESL100",
            "Subdevice No": "0",
            "Type": "wifi",
            "CID": "1234567890abcdef"
        }
        ```
    """
    return_dict = self.to_dict(state=state)
    if indent:
        return orjson.dumps(
            return_dict,
            option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS,
        )

    return orjson.dumps(return_dict, option=orjson.OPT_NON_STR_KEYS)

toggle_switch async

toggle_switch(toggle: bool | None = None) -> bool

Inherited From VeSyncBaseToggleDevice

Toggle device power on or off.

Parameters:

Name Type Description Default
toggle bool | None

True to turn on, False to turn off, None to toggle.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def toggle_switch(self, toggle: bool | None = None) -> bool:
    if toggle is None:
        toggle = self.state.device_status != DeviceStatus.ON
    toggle_str = DeviceStatus.ON if toggle else DeviceStatus.OFF
    r_dict = await self.call_bypassv1_api(
        Request15AStatus,
        update_dict={'status': toggle_str},
        method='deviceStatus',
        endpoint='deviceStatus'
    )
    response = Helpers.process_dev_response(logger, "toggle_switch", self, r_dict)
    if response is None:
        return False

    self.state.device_status = toggle_str
    self.state.connection_status = ConnectionStatus.ONLINE
    return True

turn_off async

turn_off() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device off.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_off(self) -> bool:
    """Turn device off."""
    return await self.toggle_switch(False)

turn_off_nightlight async

turn_off_nightlight() -> bool

Inherited From VeSyncOutlet

Turn off nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_off_nightlight(self) -> bool:
    """Turn off nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.OFF)

turn_on async

turn_on() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device on.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_on(self) -> bool:
    """Turn device on."""
    return await self.toggle_switch(True)

turn_on_nightlight async

turn_on_nightlight() -> bool

Inherited From VeSyncOutlet

Turn on nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_on_nightlight(self) -> bool:
    """Turn on nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.ON)

update async

update() -> None

Inherited From VeSyncBaseDevice

Update device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def update(self) -> None:
    """Update device details."""
    await self.get_details()

update_energy async

update_energy() -> None

Inherited From VeSyncOutlet

Build weekly, monthly and yearly dictionaries.

Source code in src\pyvesync\base_devices\outlet_base.py
async def update_energy(self) -> None:
    """Build weekly, monthly and yearly dictionaries."""
    if self.supports_energy:
        await self.get_weekly_energy()
        await self.get_monthly_energy()
        await self.get_yearly_energy()

pyvesync.devices.vesyncoutlet.VeSyncOutdoorPlug

Bases: BypassV1Mixin, VeSyncOutlet

Class to hold Etekcity outdoor outlets.

Parameters:

Name Type Description Default
details ResponseDeviceDetailsModel

The device details.

required
manager VeSync

The VeSync manager.

required
feature_map OutletMap

The feature map for the device.

required

Attributes:

Name Type Description
state OutletState

The state of the outlet.

last_response ResponseInfo

Last response from API call.

device_status str

Device status.

connection_status str

Connection status.

manager VeSync

Manager object for API calls.

device_name str

Name of device.

device_image str

URL for device image.

cid str

Device ID.

connection_type str

Connection type of device.

device_type str

Type of device.

type str

Type of device.

uuid str

UUID of device, not always present.

config_module str

Configuration module of device.

mac_id str

MAC ID of device.

current_firm_version str

Current firmware version of device.

device_region str

Region of device. (US, EU, etc.)

pid str

Product ID of device, pulled by some devices on update.

sub_device_no int

Sub-device number of device.

product_type str

Product type of device.

features dict

Features of device.

Source code in src\pyvesync\devices\vesyncoutlet.py
class VeSyncOutdoorPlug(BypassV1Mixin, VeSyncOutlet):
    """Class to hold Etekcity outdoor outlets.

    Args:
        details (ResponseDeviceDetailsModel): The device details.
        manager (VeSync): The VeSync manager.
        feature_map (OutletMap): The feature map for the device.

    Attributes:
        state (OutletState): The state of the outlet.
        last_response (ResponseInfo): Last response from API call.
        device_status (str): Device status.
        connection_status (str): Connection status.
        manager (VeSync): Manager object for API calls.
        device_name (str): Name of device.
        device_image (str): URL for device image.
        cid (str): Device ID.
        connection_type (str): Connection type of device.
        device_type (str): Type of device.
        type (str): Type of device.
        uuid (str): UUID of device, not always present.
        config_module (str): Configuration module of device.
        mac_id (str): MAC ID of device.
        current_firm_version (str): Current firmware version of device.
        device_region (str): Region of device. (US, EU, etc.)
        pid (str): Product ID of device, pulled by some devices on update.
        sub_device_no (int): Sub-device number of device.
        product_type (str): Product type of device.
        features (dict): Features of device.
    """

    __slots__ = ()

    def __init__(self, details: ResponseDeviceDetailsModel,
                 manager: VeSync, feature_map: OutletMap) -> None:
        """Initialize Etekcity Outdoor Plug class."""
        super().__init__(details, manager, feature_map)

    async def get_details(self) -> None:
        r_dict = await self.call_bypassv1_api(
            Request15ADetails,
            method='deviceDetail',
            endpoint='deviceDetail'
        )
        r = Helpers.process_dev_response(logger, "get_details", self, r_dict)
        if r is None:
            return

        resp_model = ResponseOutdoorDetails.from_dict(r)
        self.state.connection_status = resp_model.result.connectionStatus
        self.state.energy = resp_model.result.energy
        self.state.power = resp_model.result.power
        self.state.voltage = resp_model.result.voltage
        self.state.active_time = resp_model.result.activeTime
        for outlet in resp_model.result.subDevices:
            if int(self.sub_device_no) == int(outlet.subDeviceNo):
                self.state.device_status = outlet.subDeviceStatus

    @deprecated(reason="Use toggle_switch(toggle: bool | None) instead")
    async def toggle(self, status: str) -> bool:
        """Deprecated, use toggle_switch() instead."""
        toggle = status != DeviceStatus.ON
        return await self.toggle_switch(toggle)

    async def toggle_switch(self, toggle: bool | None = None) -> bool:
        if toggle is None:
            toggle = self.state.device_status != DeviceStatus.ON
        status = DeviceStatus.ON if toggle else DeviceStatus.OFF

        r_dict = await self.call_bypassv1_api(
            RequestOutdoorStatus,
            update_dict={'switchNo': self.sub_device_no, 'status': status},
            method='deviceStatus',
            endpoint='deviceStatus'
        )

        response = Helpers.process_dev_response(logger, "toggle", self, r_dict)
        if response is None:
            return False

        self.state.device_status = status
        self.state.connection_status = ConnectionStatus.ONLINE
        return True

    async def get_timer(self) -> None:
        method = 'getTimers'
        endpoint = f'/timer/{method}'
        r_dict = await self.call_bypassv1_api(
            TimerModels.RequestV1GetTimer,
            {'switchNo': self.sub_device_no},
            method=method,
            endpoint=endpoint
        )
        result_model = process_bypassv1_result(
            self, logger, "get_timer", r_dict, TimerModels.ResultV1GetTimer
        )
        if result_model is None:
            return
        timers = result_model.timers
        if not isinstance(timers, list) or len(timers) == 0:
            self.state.timer = None
            return
        if len(timers) > 1:
            logger.debug(
                (
                    (
                        "Multiple timers found - %s, this method "
                        "will only return the most recent timer created."
                    ),
                ),
                timers,
            )
        timer = timers[0]
        if not isinstance(timer, TimerModels.TimerItemV1):
            logger.debug("Invalid timer model - %s", timer)
            return
        self.state.timer = Timer(
            timer_duration=int(timer.counterTimer),
            id=int(timer.timerID),
            action=timer.action,
        )

    async def set_timer(self, duration: int, action: str | None = None) -> bool:
        if action is None:
            action = (
                DeviceStatus.ON
                if self.state.device_status == DeviceStatus.OFF
                else DeviceStatus.OFF
            )
        if not isinstance(action, str) or \
                action not in [DeviceStatus.ON, DeviceStatus.OFF]:
            logger.error("Invalid action for timer - %s", action)
            return False
        update_dict = {
            'action': action,
            'counterTime': str(duration),
            'switchNo': self.sub_device_no,
        }
        r_dict = await self.call_bypassv1_api(
            TimerModels.RequestV1SetTime,
            update_dict=update_dict,
            method='addTimer',
            endpoint='timer/addTimer'
        )
        result_model = process_bypassv1_result(
            self, logger, "set_timer", r_dict, TimerModels.ResultV1SetTimer
        )
        if result_model is None:
            return False
        self.state.timer = Timer(duration, action, int(result_model.timerID))
        return True

    async def clear_timer(self) -> bool:
        if self.state.timer is None:
            logger.debug("No timer set, nothing to clear, run get_timer().")
            return False
        if self.state.timer.time_remaining == 0:
            logger.debug("Timer already ended.")
            self.state.timer = None
            return True
        r_dict = await self.call_bypassv1_api(
            TimerModels.RequestV1ClearTimer,
            {'timerId': str(self.state.timer.id)},
            method='deleteTimer',
            endpoint='timer/deleteTimer'
        )
        r_dict = Helpers.process_dev_response(
            logger, "clear_timer", self, r_dict
        )
        if r_dict is None:
            return False
        self.state.timer = None
        return True

Attributes

cid instance-attribute

cid: str = cid

Inherited From VeSyncBaseDevice

config_module instance-attribute

config_module: str = configModule

Inherited From VeSyncBaseDevice

connection_type instance-attribute

connection_type: str | None = connectionType

Inherited From VeSyncBaseDevice

current_firm_version instance-attribute

current_firm_version = currentFirmVersion

Inherited From VeSyncBaseDevice

device_image instance-attribute

device_image: str | None = deviceImg

Inherited From VeSyncBaseDevice

device_name instance-attribute

device_name: str = deviceName

Inherited From VeSyncBaseDevice

device_region instance-attribute

device_region: str | None = deviceRegion

Inherited From VeSyncBaseDevice

device_type instance-attribute

device_type: str = deviceType

Inherited From VeSyncBaseDevice

enabled instance-attribute

enabled: bool = True

Inherited From VeSyncBaseDevice

features instance-attribute

features: list[str] = features

Inherited From VeSyncBaseDevice

firmware_update property

firmware_update: bool

Inherited From VeSyncBaseDevice

Return True if firmware update available.

This is going to be updated.

is_on property

is_on: bool

Inherited From VeSyncBaseDevice

Return true if device is on.

last_response instance-attribute

last_response: ResponseInfo | None = None

Inherited From VeSyncBaseDevice

mac_id instance-attribute

mac_id: str | None = macID

Inherited From VeSyncBaseDevice

manager instance-attribute

manager: VeSync

Inherited From BypassV1Mixin

nightlight_modes instance-attribute

nightlight_modes = nightlight_modes

Inherited From VeSyncOutlet

pid instance-attribute

pid: str | None = None

Inherited From VeSyncBaseDevice

product_type instance-attribute

product_type: str = product_type

Inherited From VeSyncBaseDevice

request_keys class-attribute

request_keys: list[str] = [
    'acceptLanguage',
    'appVersion',
    'phoneBrand',
    'phoneOS',
    'accountID',
    'cid',
    'configModule',
    'debugMode',
    'traceId',
    'timeZone',
    'token',
    'userCountryCode',
    'uuid',
    'configModel',
    'deviceId',
]

Inherited From BypassV1Mixin

state instance-attribute

state: OutletState = OutletState(self, details, feature_map)

Inherited From VeSyncBaseDevice

sub_device_no instance-attribute

sub_device_no: int | None = subDeviceNo

Inherited From VeSyncBaseDevice

supports_energy property

supports_energy: bool

Inherited From VeSyncOutlet

Return True if device supports energy.

Returns:

Name Type Description
bool bool

True if device supports energy, False otherwise.

supports_nightlight property

supports_nightlight: bool

Inherited From VeSyncOutlet

Return True if device supports nightlight.

Returns:

Name Type Description
bool bool

True if device supports nightlight, False otherwise.

type instance-attribute

type: str | None = type

Inherited From VeSyncBaseDevice

uuid instance-attribute

uuid: str | None = uuid

Inherited From VeSyncBaseDevice

Functions

call_bypassv1_api async

call_bypassv1_api(
    request_model: type[RequestBypassV1],
    update_dict: dict | None = None,
    method: str = 'bypass',
    endpoint: str = 'bypass',
) -> dict | None

Inherited From BypassV1Mixin

Send ByPass V1 API request.

This uses the _build_request method to send API requests to the Bypass V1 API. The endpoint can be overridden with the endpoint argument.

Parameters:

Name Type Description Default
request_model type[RequestBypassV1]

The request model to use.

required
update_dict dict

Additional keys to add on.

None
method str

The method to use in the outer body.

'bypass'
endpoint str | None

The last part of the url path, defaults to bypass, e.g. /cloud/v1/deviceManaged/bypass.

'bypass'

Returns:

Name Type Description
bytes dict | None

The response from the API request.

Source code in src\pyvesync\utils\device_mixins.py
async def call_bypassv1_api(
    self,
    request_model: type[RequestBypassV1],
    update_dict: dict | None = None,
    method: str = "bypass",
    endpoint: str = "bypass",
) -> dict | None:
    """Send ByPass V1 API request.

    This uses the `_build_request` method to send API requests to the Bypass V1 API.
    The endpoint can be overridden with the `endpoint` argument.

    Args:
        request_model (type[RequestBypassV1]): The request model to use.
        update_dict (dict): Additional keys to add on.
        method (str): The method to use in the outer body.
        endpoint (str | None): The last part of the url path, defaults to
            `bypass`, e.g. `/cloud/v1/deviceManaged/bypass`.

    Returns:
        bytes: The response from the API request.
    """
    request = self._build_request(request_model, update_dict, method)
    url_path = BYPASS_V1_PATH + endpoint
    resp_dict, _ = await self.manager.async_call_api(
        url_path, "post", request, Helpers.req_header_bypass()
    )

    return resp_dict

clear_timer async

clear_timer() -> bool

Inherited From VeSyncBaseDevice

Clear timer for device from API.

This may not be implemented for all devices. Please open an issue if there is an error.

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def clear_timer(self) -> bool:
    if self.state.timer is None:
        logger.debug("No timer set, nothing to clear, run get_timer().")
        return False
    if self.state.timer.time_remaining == 0:
        logger.debug("Timer already ended.")
        self.state.timer = None
        return True
    r_dict = await self.call_bypassv1_api(
        TimerModels.RequestV1ClearTimer,
        {'timerId': str(self.state.timer.id)},
        method='deleteTimer',
        endpoint='timer/deleteTimer'
    )
    r_dict = Helpers.process_dev_response(
        logger, "clear_timer", self, r_dict
    )
    if r_dict is None:
        return False
    self.state.timer = None
    return True

display

display(state: bool = True) -> None

Inherited From VeSyncBaseDevice

Print formatted static device info to stdout.

Parameters:

Name Type Description Default
state bool

If True, include state in display, defaults to True.

True

Example:

Device Name:..................Living Room Lamp
Model:........................ESL100
Subdevice No:.................0
Type:.........................wifi
CID:..........................1234567890abcdef

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def display(self, state: bool = True) -> None:
    """Print formatted static device info to stdout.

    Args:
        state (bool): If True, include state in display, defaults to True.

    Example:
    ```
    Device Name:..................Living Room Lamp
    Model:........................ESL100
    Subdevice No:.................0
    Type:.........................wifi
    CID:..........................1234567890abcdef
    ```
    """
    # noinspection SpellCheckingInspection
    display_list = [
        ('Device Name:', self.device_name),
        ('Product Type: ', self.product_type),
        ('Model: ', self.device_type),
        ('Subdevice No: ', str(self.sub_device_no)),
        ('Type: ', self.type),
        ('CID: ', self.cid),
        ('Config Module: ', self.config_module),
        ('Connection Type: ', self.connection_type),
        ('Features', self.features),
        ('Last Response: ', self.last_response),
    ]
    if self.uuid is not None:
        display_list.append(('UUID: ', self.uuid))

    for line in display_list:
        print(f'{line[0]:.<30} {line[1]}')
    if state:
        self.state.display()

displayJSON deprecated

displayJSON(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Deprecated

Use to_json() instead

Return JSON details for device. - Deprecated use to_json().

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
@deprecated("Use to_json() instead")
def displayJSON(self, state: bool = True, indent: bool = True) -> str:  # pylint: disable=invalid-name
    """Return JSON details for device. - Deprecated use to_json()."""
    return self.to_json(state, indent)

get_details async

get_details() -> None

Inherited From VeSyncBaseDevice

Get device details.

This method is defined in each device class to contain the logic to pull the device state from the API and update the device's state attribute. The update() method should be called to update the device state.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def get_details(self) -> None:
    r_dict = await self.call_bypassv1_api(
        Request15ADetails,
        method='deviceDetail',
        endpoint='deviceDetail'
    )
    r = Helpers.process_dev_response(logger, "get_details", self, r_dict)
    if r is None:
        return

    resp_model = ResponseOutdoorDetails.from_dict(r)
    self.state.connection_status = resp_model.result.connectionStatus
    self.state.energy = resp_model.result.energy
    self.state.power = resp_model.result.power
    self.state.voltage = resp_model.result.voltage
    self.state.active_time = resp_model.result.activeTime
    for outlet in resp_model.result.subDevices:
        if int(self.sub_device_no) == int(outlet.subDeviceNo):
            self.state.device_status = outlet.subDeviceStatus

get_monthly_energy async

get_monthly_energy() -> None

Inherited From VeSyncOutlet

Build Monthly Energy History Dictionary.

The data is stored in the device.state.monthly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_monthly_energy(self) -> None:
    """Build Monthly Energy History Dictionary.

    The data is stored in the `device.state.monthly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastMonthEnergy')

get_state

get_state(state_attr: str) -> Any

Inherited From VeSyncBaseDevice

Get device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def get_state(self, state_attr: str) -> Any:  # noqa: ANN401
    """Get device state attribute."""
    return getattr(self.state, state_attr)

get_timer async

get_timer() -> None

Inherited From VeSyncBaseDevice

Get timer for device from API and set the state.Timer attribute.

This may not be implemented for all devices. Please open an issue if there is an error.

Note

This method may not be implemented for all devices. Please open an issue if there is an error.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def get_timer(self) -> None:
    method = 'getTimers'
    endpoint = f'/timer/{method}'
    r_dict = await self.call_bypassv1_api(
        TimerModels.RequestV1GetTimer,
        {'switchNo': self.sub_device_no},
        method=method,
        endpoint=endpoint
    )
    result_model = process_bypassv1_result(
        self, logger, "get_timer", r_dict, TimerModels.ResultV1GetTimer
    )
    if result_model is None:
        return
    timers = result_model.timers
    if not isinstance(timers, list) or len(timers) == 0:
        self.state.timer = None
        return
    if len(timers) > 1:
        logger.debug(
            (
                (
                    "Multiple timers found - %s, this method "
                    "will only return the most recent timer created."
                ),
            ),
            timers,
        )
    timer = timers[0]
    if not isinstance(timer, TimerModels.TimerItemV1):
        logger.debug("Invalid timer model - %s", timer)
        return
    self.state.timer = Timer(
        timer_duration=int(timer.counterTimer),
        id=int(timer.timerID),
        action=timer.action,
    )

get_weekly_energy async

get_weekly_energy() -> None

Inherited From VeSyncOutlet

Build weekly energy history dictionary.

The data is stored in the device.state.weekly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_weekly_energy(self) -> None:
    """Build weekly energy history dictionary.

    The data is stored in the `device.state.weekly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastWeekEnergy')

get_yearly_energy async

get_yearly_energy() -> None

Inherited From VeSyncOutlet

Build Yearly Energy Dictionary.

The data is stored in the device.state.yearly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_yearly_energy(self) -> None:
    """Build Yearly Energy Dictionary.

    The data is stored in the `device.state.yearly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastYearEnergy')

set_nightlight_auto async

set_nightlight_auto() -> bool

Inherited From VeSyncOutlet

Set nightlight to auto mode.

Source code in src\pyvesync\base_devices\outlet_base.py
async def set_nightlight_auto(self) -> bool:
    """Set nightlight to auto mode."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.AUTO)

set_nightlight_state async

set_nightlight_state(mode: str) -> bool

Inherited From VeSyncOutlet

Set nightlight mode.

Available nightlight states are found in the device.nightlight_modes attribute.

Parameters:

Name Type Description Default
mode str

Nightlight mode to set.

required

Returns:

Name Type Description
bool bool

True if nightlight mode set successfully, False otherwise.

Source code in src\pyvesync\base_devices\outlet_base.py
async def set_nightlight_state(self, mode: str) -> bool:
    """Set nightlight mode.

    Available nightlight states are found in the `device.nightlight_modes` attribute.

    Args:
        mode (str): Nightlight mode to set.

    Returns:
        bool: True if nightlight mode set successfully, False otherwise.
    """
    del mode  # unused
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
    else:
        logger.debug("Nightlight mode not configured for %s", self.device_name)
    return False

set_state

set_state(state_attr: str, stat_value: Any) -> None

Inherited From VeSyncBaseDevice

Set device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def set_state(self, state_attr: str, stat_value: Any) -> None:  # noqa: ANN401
    """Set device state attribute."""
    setattr(self, state_attr, stat_value)

set_timer async

set_timer(duration: int, action: str | None = None) -> bool

Inherited From VeSyncBaseDevice

Set timer for device.

This may not be implemented for all devices. Please open an issue if there is an error.

Parameters:

Name Type Description Default
duration int

Duration in seconds.

required
action str | None

Action to take when timer expires.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def set_timer(self, duration: int, action: str | None = None) -> bool:
    if action is None:
        action = (
            DeviceStatus.ON
            if self.state.device_status == DeviceStatus.OFF
            else DeviceStatus.OFF
        )
    if not isinstance(action, str) or \
            action not in [DeviceStatus.ON, DeviceStatus.OFF]:
        logger.error("Invalid action for timer - %s", action)
        return False
    update_dict = {
        'action': action,
        'counterTime': str(duration),
        'switchNo': self.sub_device_no,
    }
    r_dict = await self.call_bypassv1_api(
        TimerModels.RequestV1SetTime,
        update_dict=update_dict,
        method='addTimer',
        endpoint='timer/addTimer'
    )
    result_model = process_bypassv1_result(
        self, logger, "set_timer", r_dict, TimerModels.ResultV1SetTimer
    )
    if result_model is None:
        return False
    self.state.timer = Timer(duration, action, int(result_model.timerID))
    return True

to_dict

to_dict(state: bool = True) -> dict[str, Any]

Inherited From VeSyncBaseDevice

Return device information as a dictionary.

Parameters:

Name Type Description Default
state bool

If True, include state in dictionary, defaults to True.

True

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Dictionary containing device information.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_dict(self, state: bool = True) -> dict[str, Any]:
    """Return device information as a dictionary.

    Args:
        state (bool): If True, include state in dictionary, defaults to True.

    Returns:
        dict[str, Any]: Dictionary containing device information.
    """
    device_dict = {
        "device_name": self.device_name,
        "product_type": self.product_type,
        "model": self.device_type,
        "subdevice_no": str(self.sub_device_no),
        "type": self.type,
        "cid": self.cid,
        "features:": self.features,
        "config_module": self.config_module,
        "connection_type": self.connection_type,
        "last_response": self.last_response,
    }
    state_dict = self.state.to_dict() if state else {}
    return device_dict | state_dict

to_json

to_json(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Print JSON API string for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
str str

JSON formatted string of device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_json(self, state: bool = True, indent: bool = True) -> str:
    """Print JSON API string for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        str: JSON formatted string of device details.
    """
    return self.to_jsonb(state, indent).decode()

to_jsonb

to_jsonb(state: bool = True, indent: bool = True) -> bytes

Inherited From VeSyncBaseDevice

JSON API bytes for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
bytes bytes

JSON formatted bytes of device details.

Example

This is an example without state.

{
    "Device Name": "Living Room Lamp",
    "Model": "ESL100",
    "Subdevice No": "0",
    "Type": "wifi",
    "CID": "1234567890abcdef"
}

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_jsonb(self, state: bool = True, indent: bool = True) -> bytes:
    """JSON API bytes for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        bytes: JSON formatted bytes of device details.

    Example:
        This is an example without state.
        ```
        {
            "Device Name": "Living Room Lamp",
            "Model": "ESL100",
            "Subdevice No": "0",
            "Type": "wifi",
            "CID": "1234567890abcdef"
        }
        ```
    """
    return_dict = self.to_dict(state=state)
    if indent:
        return orjson.dumps(
            return_dict,
            option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS,
        )

    return orjson.dumps(return_dict, option=orjson.OPT_NON_STR_KEYS)

toggle async

toggle(status: str) -> bool

Deprecated, use toggle_switch() instead.

Source code in src\pyvesync\devices\vesyncoutlet.py
@deprecated(reason="Use toggle_switch(toggle: bool | None) instead")
async def toggle(self, status: str) -> bool:
    """Deprecated, use toggle_switch() instead."""
    toggle = status != DeviceStatus.ON
    return await self.toggle_switch(toggle)

toggle_switch async

toggle_switch(toggle: bool | None = None) -> bool

Inherited From VeSyncBaseToggleDevice

Toggle device power on or off.

Parameters:

Name Type Description Default
toggle bool | None

True to turn on, False to turn off, None to toggle.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def toggle_switch(self, toggle: bool | None = None) -> bool:
    if toggle is None:
        toggle = self.state.device_status != DeviceStatus.ON
    status = DeviceStatus.ON if toggle else DeviceStatus.OFF

    r_dict = await self.call_bypassv1_api(
        RequestOutdoorStatus,
        update_dict={'switchNo': self.sub_device_no, 'status': status},
        method='deviceStatus',
        endpoint='deviceStatus'
    )

    response = Helpers.process_dev_response(logger, "toggle", self, r_dict)
    if response is None:
        return False

    self.state.device_status = status
    self.state.connection_status = ConnectionStatus.ONLINE
    return True

turn_off async

turn_off() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device off.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_off(self) -> bool:
    """Turn device off."""
    return await self.toggle_switch(False)

turn_off_nightlight async

turn_off_nightlight() -> bool

Inherited From VeSyncOutlet

Turn off nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_off_nightlight(self) -> bool:
    """Turn off nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.OFF)

turn_on async

turn_on() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device on.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_on(self) -> bool:
    """Turn device on."""
    return await self.toggle_switch(True)

turn_on_nightlight async

turn_on_nightlight() -> bool

Inherited From VeSyncOutlet

Turn on nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_on_nightlight(self) -> bool:
    """Turn on nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.ON)

update async

update() -> None

Inherited From VeSyncBaseDevice

Update device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def update(self) -> None:
    """Update device details."""
    await self.get_details()

update_energy async

update_energy() -> None

Inherited From VeSyncOutlet

Build weekly, monthly and yearly dictionaries.

Source code in src\pyvesync\base_devices\outlet_base.py
async def update_energy(self) -> None:
    """Build weekly, monthly and yearly dictionaries."""
    if self.supports_energy:
        await self.get_weekly_energy()
        await self.get_monthly_energy()
        await self.get_yearly_energy()

pyvesync.devices.vesyncoutlet.VeSyncESW10USA

Bases: BypassV2Mixin, VeSyncOutlet10A

VeSync ESW10 USA outlet.

Note that this device does not support energy monitoring.

Parameters:

Name Type Description Default
details ResponseDeviceDetailsModel

The device details.

required
manager VeSync

The VeSync manager.

required
feature_map OutletMap

The feature map for the device.

required

Attributes:

Name Type Description
state OutletState

The state of the outlet.

last_response ResponseInfo

Last response from API call.

device_status str

Device status.

connection_status str

Connection status.

manager VeSync

Manager object for API calls.

device_name str

Name of device.

device_image str

URL for device image.

cid str

Device ID.

connection_type str

Connection type of device.

device_type str

Type of device.

type str

Type of device.

uuid str

UUID of device, not always present.

config_module str

Configuration module of device.

mac_id str

MAC ID of device.

current_firm_version str

Current firmware version of device.

device_region str

Region of device. (US, EU, etc.)

pid str

Product ID of device, pulled by some devices on update.

sub_device_no int

Sub-device number of device.

product_type str

Product type of device.

features dict

Features of device.

Source code in src\pyvesync\devices\vesyncoutlet.py
class VeSyncESW10USA(BypassV2Mixin, VeSyncOutlet10A):
    """VeSync ESW10 USA outlet.

    Note that this device does not support energy monitoring.

    Args:
        details (ResponseDeviceDetailsModel): The device details.
        manager (VeSync): The VeSync manager.
        feature_map (OutletMap): The feature map for the device.

    Attributes:
        state (OutletState): The state of the outlet.
        last_response (ResponseInfo): Last response from API call.
        device_status (str): Device status.
        connection_status (str): Connection status.
        manager (VeSync): Manager object for API calls.
        device_name (str): Name of device.
        device_image (str): URL for device image.
        cid (str): Device ID.
        connection_type (str): Connection type of device.
        device_type (str): Type of device.
        type (str): Type of device.
        uuid (str): UUID of device, not always present.
        config_module (str): Configuration module of device.
        mac_id (str): MAC ID of device.
        current_firm_version (str): Current firmware version of device.
        device_region (str): Region of device. (US, EU, etc.)
        pid (str): Product ID of device, pulled by some devices on update.
        sub_device_no (int): Sub-device number of device.
        product_type (str): Product type of device.
        features (dict): Features of device.
    """

    __slots__ = ()

    def __init__(self, details: ResponseDeviceDetailsModel,
                 manager: VeSync, feature_map: OutletMap) -> None:
        """Initialize ESW10 USA outlet."""
        super().__init__(details, manager, feature_map)

    async def get_details(self) -> None:
        payload_data = {
            "id": 0,
        }
        payload_method = "getSwitch"
        r_dict = await self.call_bypassv2_api(payload_method, payload_data)
        result = process_bypassv2_result(
            self, logger, "get_details", r_dict, ResultESW10Details
        )
        if not isinstance(result, dict) or not isinstance(result.get("enabled"), bool):
            logger.debug("Error getting %s details", self.device_name)
            self.state.connection_status = ConnectionStatus.OFFLINE
            return
        self.state.device_status = DeviceStatus.from_bool(result.enabled)
        self.state.connection_status = ConnectionStatus.ONLINE

    async def toggle_switch(self, toggle: bool | None = None) -> bool:
        if toggle is None:
            toggle = self.state.device_status != DeviceStatus.ON
        payload_data = {
            "id": 0,
            "enabled": toggle,
        }
        payload_method = "setSwitch"
        r_dict = await self.call_bypassv2_api(payload_method, payload_data)
        result = Helpers.process_dev_response(logger, "toggle_switch", self, r_dict)
        if not isinstance(result, dict):
            logger.debug("Error toggling %s switch", self.device_name)
            return False
        self.state.device_status = DeviceStatus.from_bool(toggle)
        self.state.connection_status = ConnectionStatus.ONLINE
        return True

    async def get_timer(self) -> Timer | None:
        r_dict = await self.call_bypassv2_api("getTimer")
        result_model = process_bypassv2_result(
            self, logger, "get_timer", r_dict, TimerModels.ResultV2GetTimer
        )
        if result_model is None:
            return None
        timers = result_model.timers
        if not timers:
            self.state.timer = None
            return None
        if len(timers) > 1:
            logger.debug(
                (
                    "Multiple timers found - %s, this method "
                    "will only return the most recent timer created."
                ),
                timers,
            )
        timer = timers[0]
        self.state.timer = Timer(
            timer_duration=int(timer.remain),
            id=int(timer.id),
            action=timer.action,
        )
        return self.state.timer

    async def set_timer(self, duration: int, action: str | None = None) -> bool:
        if action is None:
            action = (
                DeviceStatus.ON
                if self.state.device_status == DeviceStatus.OFF
                else DeviceStatus.OFF
            )
        if action not in [DeviceStatus.ON, DeviceStatus.OFF]:
            logger.error("Invalid action for timer - %s", action)
            return False
        payload_data = {
            'action': action,
            'total': duration
        }
        r_dict = await self.call_bypassv2_api(
            payload_method='addTimer',
            data=payload_data,
        )
        result_model = process_bypassv2_result(
            self, logger, "set_timer", r_dict, TimerModels.ResultV2SetTimer
        )
        if result_model is None:
            return False
        if result_model.id is None:
            logger.debug("Unable to set timer.")
            return False
        self.state.timer = Timer(duration, action, int(result_model.id))
        return True

    async def clear_timer(self) -> bool:
        if self.state.timer is None:
            logger.debug("No timer set, nothing to clear, run get_timer().")
            return False
        if self.state.timer.time_remaining == 0:
            logger.debug("Timer already ended.")
            self.state.timer = None
            return True
        r_dict = await self.call_bypassv2_api(
            payload_method='delTimer',
            data={"id": self.state.timer.id}
        )
        r_dict = Helpers.process_dev_response(
            logger, "clear_timer", self, r_dict
        )
        if r_dict is None:
            return False
        self.state.timer = None
        return True

Attributes

cid instance-attribute

cid: str = cid

Inherited From VeSyncBaseDevice

config_module instance-attribute

config_module: str = configModule

Inherited From VeSyncBaseDevice

connection_type instance-attribute

connection_type: str | None = connectionType

Inherited From VeSyncBaseDevice

current_firm_version instance-attribute

current_firm_version = currentFirmVersion

Inherited From VeSyncBaseDevice

device_image instance-attribute

device_image: str | None = deviceImg

Inherited From VeSyncBaseDevice

device_name instance-attribute

device_name: str = deviceName

Inherited From VeSyncBaseDevice

device_region instance-attribute

device_region: str | None = deviceRegion

Inherited From VeSyncBaseDevice

device_type instance-attribute

device_type: str = deviceType

Inherited From VeSyncBaseDevice

enabled instance-attribute

enabled: bool = True

Inherited From VeSyncBaseDevice

features instance-attribute

features: list[str] = features

Inherited From VeSyncBaseDevice

firmware_update property

firmware_update: bool

Inherited From VeSyncBaseDevice

Return True if firmware update available.

This is going to be updated.

is_on property

is_on: bool

Inherited From VeSyncBaseDevice

Return true if device is on.

last_response instance-attribute

last_response: ResponseInfo | None = None

Inherited From VeSyncBaseDevice

mac_id instance-attribute

mac_id: str | None = macID

Inherited From VeSyncBaseDevice

manager instance-attribute

manager: VeSync

Inherited From BypassV2Mixin

nightlight_modes instance-attribute

nightlight_modes = nightlight_modes

Inherited From VeSyncOutlet

pid instance-attribute

pid: str | None = None

Inherited From VeSyncBaseDevice

product_type instance-attribute

product_type: str = product_type

Inherited From VeSyncBaseDevice

request_keys class-attribute

request_keys: list[str] = [
    'acceptLanguage',
    'appVersion',
    'phoneBrand',
    'phoneOS',
    'accountID',
    'cid',
    'configModule',
    'debugMode',
    'traceId',
    'timeZone',
    'token',
    'userCountryCode',
    'configModel',
    'deviceId',
]

Inherited From BypassV2Mixin

state instance-attribute

state: OutletState = OutletState(self, details, feature_map)

Inherited From VeSyncBaseDevice

sub_device_no instance-attribute

sub_device_no: int | None = subDeviceNo

Inherited From VeSyncBaseDevice

supports_energy property

supports_energy: bool

Inherited From VeSyncOutlet

Return True if device supports energy.

Returns:

Name Type Description
bool bool

True if device supports energy, False otherwise.

supports_nightlight property

supports_nightlight: bool

Inherited From VeSyncOutlet

Return True if device supports nightlight.

Returns:

Name Type Description
bool bool

True if device supports nightlight, False otherwise.

type instance-attribute

type: str | None = type

Inherited From VeSyncBaseDevice

uuid instance-attribute

uuid: str | None = uuid

Inherited From VeSyncBaseDevice

Functions

call_bypassv2_api async

call_bypassv2_api(
    payload_method: str,
    data: dict | None = None,
    method: str = 'bypassV2',
    endpoint: str = 'bypassV2',
) -> dict | None

Inherited From BypassV2Mixin

Send Bypass V2 API request.

This uses the _build_request method to send API requests to the Bypass V2 API.

Parameters:

Name Type Description Default
payload_method str

The method to use in the payload dict.

required
data dict | None

The data to send in the request.

None
method str

The method to use in the outer body.

'bypassV2'
endpoint str | None

The last part of the API url, defaults to bypassV2, e.g. /cloud/v2/deviceManaged/bypassV2.

'bypassV2'

Returns:

Name Type Description
bytes dict | None

The response from the API request.

Source code in src\pyvesync\utils\device_mixins.py
async def call_bypassv2_api(
    self,
    payload_method: str,
    data: dict | None = None,
    method: str = "bypassV2",
    endpoint: str = "bypassV2",
) -> dict | None:
    """Send Bypass V2 API request.

    This uses the `_build_request` method to send API requests to the Bypass V2 API.

    Args:
        payload_method (str): The method to use in the payload dict.
        data (dict | None): The data to send in the request.
        method (str): The method to use in the outer body.
        endpoint (str | None): The last part of the API url, defaults to
            `bypassV2`, e.g. `/cloud/v2/deviceManaged/bypassV2`.

    Returns:
        bytes: The response from the API request.
    """
    request = self._build_request(payload_method, data, method)
    endpoint = BYPASS_V2_BASE + endpoint
    resp_dict, _ = await self.manager.async_call_api(
        endpoint, "post", request, Helpers.req_header_bypass()
    )
    return resp_dict

clear_timer async

clear_timer() -> bool

Inherited From VeSyncBaseDevice

Clear timer for device from API.

This may not be implemented for all devices. Please open an issue if there is an error.

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def clear_timer(self) -> bool:
    if self.state.timer is None:
        logger.debug("No timer set, nothing to clear, run get_timer().")
        return False
    if self.state.timer.time_remaining == 0:
        logger.debug("Timer already ended.")
        self.state.timer = None
        return True
    r_dict = await self.call_bypassv2_api(
        payload_method='delTimer',
        data={"id": self.state.timer.id}
    )
    r_dict = Helpers.process_dev_response(
        logger, "clear_timer", self, r_dict
    )
    if r_dict is None:
        return False
    self.state.timer = None
    return True

display

display(state: bool = True) -> None

Inherited From VeSyncBaseDevice

Print formatted static device info to stdout.

Parameters:

Name Type Description Default
state bool

If True, include state in display, defaults to True.

True

Example:

Device Name:..................Living Room Lamp
Model:........................ESL100
Subdevice No:.................0
Type:.........................wifi
CID:..........................1234567890abcdef

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def display(self, state: bool = True) -> None:
    """Print formatted static device info to stdout.

    Args:
        state (bool): If True, include state in display, defaults to True.

    Example:
    ```
    Device Name:..................Living Room Lamp
    Model:........................ESL100
    Subdevice No:.................0
    Type:.........................wifi
    CID:..........................1234567890abcdef
    ```
    """
    # noinspection SpellCheckingInspection
    display_list = [
        ('Device Name:', self.device_name),
        ('Product Type: ', self.product_type),
        ('Model: ', self.device_type),
        ('Subdevice No: ', str(self.sub_device_no)),
        ('Type: ', self.type),
        ('CID: ', self.cid),
        ('Config Module: ', self.config_module),
        ('Connection Type: ', self.connection_type),
        ('Features', self.features),
        ('Last Response: ', self.last_response),
    ]
    if self.uuid is not None:
        display_list.append(('UUID: ', self.uuid))

    for line in display_list:
        print(f'{line[0]:.<30} {line[1]}')
    if state:
        self.state.display()

displayJSON deprecated

displayJSON(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Deprecated

Use to_json() instead

Return JSON details for device. - Deprecated use to_json().

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
@deprecated("Use to_json() instead")
def displayJSON(self, state: bool = True, indent: bool = True) -> str:  # pylint: disable=invalid-name
    """Return JSON details for device. - Deprecated use to_json()."""
    return self.to_json(state, indent)

get_details async

get_details() -> None

Inherited From VeSyncOutlet10A

Get device details.

This method is defined in each device class to contain the logic to pull the device state from the API and update the device's state attribute. The update() method should be called to update the device state.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def get_details(self) -> None:
    payload_data = {
        "id": 0,
    }
    payload_method = "getSwitch"
    r_dict = await self.call_bypassv2_api(payload_method, payload_data)
    result = process_bypassv2_result(
        self, logger, "get_details", r_dict, ResultESW10Details
    )
    if not isinstance(result, dict) or not isinstance(result.get("enabled"), bool):
        logger.debug("Error getting %s details", self.device_name)
        self.state.connection_status = ConnectionStatus.OFFLINE
        return
    self.state.device_status = DeviceStatus.from_bool(result.enabled)
    self.state.connection_status = ConnectionStatus.ONLINE

get_monthly_energy async

get_monthly_energy() -> None

Inherited From VeSyncOutlet

Build Monthly Energy History Dictionary.

The data is stored in the device.state.monthly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_monthly_energy(self) -> None:
    """Build Monthly Energy History Dictionary.

    The data is stored in the `device.state.monthly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastMonthEnergy')

get_state

get_state(state_attr: str) -> Any

Inherited From VeSyncBaseDevice

Get device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def get_state(self, state_attr: str) -> Any:  # noqa: ANN401
    """Get device state attribute."""
    return getattr(self.state, state_attr)

get_timer async

get_timer() -> Timer | None

Inherited From VeSyncBaseDevice

Get timer for device from API and set the state.Timer attribute.

This may not be implemented for all devices. Please open an issue if there is an error.

Note

This method may not be implemented for all devices. Please open an issue if there is an error.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def get_timer(self) -> Timer | None:
    r_dict = await self.call_bypassv2_api("getTimer")
    result_model = process_bypassv2_result(
        self, logger, "get_timer", r_dict, TimerModels.ResultV2GetTimer
    )
    if result_model is None:
        return None
    timers = result_model.timers
    if not timers:
        self.state.timer = None
        return None
    if len(timers) > 1:
        logger.debug(
            (
                "Multiple timers found - %s, this method "
                "will only return the most recent timer created."
            ),
            timers,
        )
    timer = timers[0]
    self.state.timer = Timer(
        timer_duration=int(timer.remain),
        id=int(timer.id),
        action=timer.action,
    )
    return self.state.timer

get_weekly_energy async

get_weekly_energy() -> None

Inherited From VeSyncOutlet

Build weekly energy history dictionary.

The data is stored in the device.state.weekly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_weekly_energy(self) -> None:
    """Build weekly energy history dictionary.

    The data is stored in the `device.state.weekly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastWeekEnergy')

get_yearly_energy async

get_yearly_energy() -> None

Inherited From VeSyncOutlet

Build Yearly Energy Dictionary.

The data is stored in the device.state.yearly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_yearly_energy(self) -> None:
    """Build Yearly Energy Dictionary.

    The data is stored in the `device.state.yearly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastYearEnergy')

set_nightlight_auto async

set_nightlight_auto() -> bool

Inherited From VeSyncOutlet

Set nightlight to auto mode.

Source code in src\pyvesync\base_devices\outlet_base.py
async def set_nightlight_auto(self) -> bool:
    """Set nightlight to auto mode."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.AUTO)

set_nightlight_state async

set_nightlight_state(mode: str) -> bool

Inherited From VeSyncOutlet

Set nightlight mode.

Available nightlight states are found in the device.nightlight_modes attribute.

Parameters:

Name Type Description Default
mode str

Nightlight mode to set.

required

Returns:

Name Type Description
bool bool

True if nightlight mode set successfully, False otherwise.

Source code in src\pyvesync\base_devices\outlet_base.py
async def set_nightlight_state(self, mode: str) -> bool:
    """Set nightlight mode.

    Available nightlight states are found in the `device.nightlight_modes` attribute.

    Args:
        mode (str): Nightlight mode to set.

    Returns:
        bool: True if nightlight mode set successfully, False otherwise.
    """
    del mode  # unused
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
    else:
        logger.debug("Nightlight mode not configured for %s", self.device_name)
    return False

set_state

set_state(state_attr: str, stat_value: Any) -> None

Inherited From VeSyncBaseDevice

Set device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def set_state(self, state_attr: str, stat_value: Any) -> None:  # noqa: ANN401
    """Set device state attribute."""
    setattr(self, state_attr, stat_value)

set_timer async

set_timer(duration: int, action: str | None = None) -> bool

Inherited From VeSyncBaseDevice

Set timer for device.

This may not be implemented for all devices. Please open an issue if there is an error.

Parameters:

Name Type Description Default
duration int

Duration in seconds.

required
action str | None

Action to take when timer expires.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def set_timer(self, duration: int, action: str | None = None) -> bool:
    if action is None:
        action = (
            DeviceStatus.ON
            if self.state.device_status == DeviceStatus.OFF
            else DeviceStatus.OFF
        )
    if action not in [DeviceStatus.ON, DeviceStatus.OFF]:
        logger.error("Invalid action for timer - %s", action)
        return False
    payload_data = {
        'action': action,
        'total': duration
    }
    r_dict = await self.call_bypassv2_api(
        payload_method='addTimer',
        data=payload_data,
    )
    result_model = process_bypassv2_result(
        self, logger, "set_timer", r_dict, TimerModels.ResultV2SetTimer
    )
    if result_model is None:
        return False
    if result_model.id is None:
        logger.debug("Unable to set timer.")
        return False
    self.state.timer = Timer(duration, action, int(result_model.id))
    return True

to_dict

to_dict(state: bool = True) -> dict[str, Any]

Inherited From VeSyncBaseDevice

Return device information as a dictionary.

Parameters:

Name Type Description Default
state bool

If True, include state in dictionary, defaults to True.

True

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Dictionary containing device information.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_dict(self, state: bool = True) -> dict[str, Any]:
    """Return device information as a dictionary.

    Args:
        state (bool): If True, include state in dictionary, defaults to True.

    Returns:
        dict[str, Any]: Dictionary containing device information.
    """
    device_dict = {
        "device_name": self.device_name,
        "product_type": self.product_type,
        "model": self.device_type,
        "subdevice_no": str(self.sub_device_no),
        "type": self.type,
        "cid": self.cid,
        "features:": self.features,
        "config_module": self.config_module,
        "connection_type": self.connection_type,
        "last_response": self.last_response,
    }
    state_dict = self.state.to_dict() if state else {}
    return device_dict | state_dict

to_json

to_json(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Print JSON API string for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
str str

JSON formatted string of device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_json(self, state: bool = True, indent: bool = True) -> str:
    """Print JSON API string for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        str: JSON formatted string of device details.
    """
    return self.to_jsonb(state, indent).decode()

to_jsonb

to_jsonb(state: bool = True, indent: bool = True) -> bytes

Inherited From VeSyncBaseDevice

JSON API bytes for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
bytes bytes

JSON formatted bytes of device details.

Example

This is an example without state.

{
    "Device Name": "Living Room Lamp",
    "Model": "ESL100",
    "Subdevice No": "0",
    "Type": "wifi",
    "CID": "1234567890abcdef"
}

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_jsonb(self, state: bool = True, indent: bool = True) -> bytes:
    """JSON API bytes for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        bytes: JSON formatted bytes of device details.

    Example:
        This is an example without state.
        ```
        {
            "Device Name": "Living Room Lamp",
            "Model": "ESL100",
            "Subdevice No": "0",
            "Type": "wifi",
            "CID": "1234567890abcdef"
        }
        ```
    """
    return_dict = self.to_dict(state=state)
    if indent:
        return orjson.dumps(
            return_dict,
            option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS,
        )

    return orjson.dumps(return_dict, option=orjson.OPT_NON_STR_KEYS)

toggle_switch async

toggle_switch(toggle: bool | None = None) -> bool

Inherited From VeSyncOutlet10A

Toggle device power on or off.

Parameters:

Name Type Description Default
toggle bool | None

True to turn on, False to turn off, None to toggle.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def toggle_switch(self, toggle: bool | None = None) -> bool:
    if toggle is None:
        toggle = self.state.device_status != DeviceStatus.ON
    payload_data = {
        "id": 0,
        "enabled": toggle,
    }
    payload_method = "setSwitch"
    r_dict = await self.call_bypassv2_api(payload_method, payload_data)
    result = Helpers.process_dev_response(logger, "toggle_switch", self, r_dict)
    if not isinstance(result, dict):
        logger.debug("Error toggling %s switch", self.device_name)
        return False
    self.state.device_status = DeviceStatus.from_bool(toggle)
    self.state.connection_status = ConnectionStatus.ONLINE
    return True

turn_off async

turn_off() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device off.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_off(self) -> bool:
    """Turn device off."""
    return await self.toggle_switch(False)

turn_off_nightlight async

turn_off_nightlight() -> bool

Inherited From VeSyncOutlet

Turn off nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_off_nightlight(self) -> bool:
    """Turn off nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.OFF)

turn_on async

turn_on() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device on.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_on(self) -> bool:
    """Turn device on."""
    return await self.toggle_switch(True)

turn_on_nightlight async

turn_on_nightlight() -> bool

Inherited From VeSyncOutlet

Turn on nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_on_nightlight(self) -> bool:
    """Turn on nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.ON)

update async

update() -> None

Inherited From VeSyncBaseDevice

Update device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def update(self) -> None:
    """Update device details."""
    await self.get_details()

update_energy async

update_energy() -> None

Inherited From VeSyncOutlet

Build weekly, monthly and yearly dictionaries.

Source code in src\pyvesync\base_devices\outlet_base.py
async def update_energy(self) -> None:
    """Build weekly, monthly and yearly dictionaries."""
    if self.supports_energy:
        await self.get_weekly_energy()
        await self.get_monthly_energy()
        await self.get_yearly_energy()

pyvesync.devices.vesyncoutlet.VeSyncOutletBSDGO1

Bases: BypassV2Mixin, VeSyncOutlet

VeSync BSDGO1 smart plug.

Note that this device does not support energy monitoring.

Parameters:

Name Type Description Default
details ResponseDeviceDetailsModel

The device details.

required
manager VeSync

The VeSync manager.

required
feature_map OutletMap

The feature map for the device.

required

Attributes:

Name Type Description
state OutletState

The state of the outlet.

last_response ResponseInfo

Last response from API call.

device_status str

Device status.

connection_status str

Connection status.

manager VeSync

Manager object for API calls.

device_name str

Name of device.

device_image str

URL for device image.

cid str

Device ID.

connection_type str

Connection type of device.

device_type str

Type of device.

type str

Type of device.

uuid str

UUID of device, not always present.

config_module str

Configuration module of device.

mac_id str

MAC ID of device.

current_firm_version str

Current firmware version of device.

device_region str

Region of device. (US, EU, etc.)

pid str

Product ID of device, pulled by some devices on update.

sub_device_no int

Sub-device number of device.

product_type str

Product type of device.

features dict

Features of device.

Source code in src\pyvesync\devices\vesyncoutlet.py
class VeSyncOutletBSDGO1(BypassV2Mixin, VeSyncOutlet):
    """VeSync BSDGO1 smart plug.

    Note that this device does not support energy monitoring.

    Args:
        details (ResponseDeviceDetailsModel): The device details.
        manager (VeSync): The VeSync manager.
        feature_map (OutletMap): The feature map for the device.

    Attributes:
        state (OutletState): The state of the outlet.
        last_response (ResponseInfo): Last response from API call.
        device_status (str): Device status.
        connection_status (str): Connection status.
        manager (VeSync): Manager object for API calls.
        device_name (str): Name of device.
        device_image (str): URL for device image.
        cid (str): Device ID.
        connection_type (str): Connection type of device.
        device_type (str): Type of device.
        type (str): Type of device.
        uuid (str): UUID of device, not always present.
        config_module (str): Configuration module of device.
        mac_id (str): MAC ID of device.
        current_firm_version (str): Current firmware version of device.
        device_region (str): Region of device. (US, EU, etc.)
        pid (str): Product ID of device, pulled by some devices on update.
        sub_device_no (int): Sub-device number of device.
        product_type (str): Product type of device.
        features (dict): Features of device.
    """

    __slots__ = ()

    def __init__(self, details: ResponseDeviceDetailsModel,
                 manager: VeSync, feature_map: OutletMap) -> None:
        """Initialize BSDGO1 smart plug class."""
        super().__init__(details, manager, feature_map)

    async def get_details(self) -> None:
        r_dict = await self.call_bypassv2_api('getProperty')

        resp_model = process_bypassv2_result(
            self, logger, "get_details", r_dict, ResponseBSDGO1OutletResult
        )
        if resp_model is None:
            return

        device_state = resp_model.powerSwitch_1
        str_status = DeviceStatus.ON if device_state == 1 else DeviceStatus.OFF
        self.state.device_status = str_status
        self.state.connection_status = resp_model.connectionStatus
        self.state.active_time = resp_model.active_time

    async def toggle_switch(self, toggle: bool | None = None) -> bool:
        if toggle is None:
            toggle = self.state.device_status != DeviceStatus.ON
        toggle_int = 1 if toggle else 0
        r_dict = await self.call_bypassv2_api(
            "setProperty", data={"powerSwitch_1": toggle_int}
        )
        r = Helpers.process_dev_response(logger, "toggle_switch", self, r_dict)
        if r is None:
            return False

        self.state.device_status = DeviceStatus.ON if toggle else DeviceStatus.OFF
        self.state.connection_status = ConnectionStatus.ONLINE
        return True

    async def _set_power(self, power: bool) -> bool:
        """Set power state of BSDGO1 outlet."""
        return await self.toggle_switch(power)

Attributes

cid instance-attribute

cid: str = cid

Inherited From VeSyncBaseDevice

config_module instance-attribute

config_module: str = configModule

Inherited From VeSyncBaseDevice

connection_type instance-attribute

connection_type: str | None = connectionType

Inherited From VeSyncBaseDevice

current_firm_version instance-attribute

current_firm_version = currentFirmVersion

Inherited From VeSyncBaseDevice

device_image instance-attribute

device_image: str | None = deviceImg

Inherited From VeSyncBaseDevice

device_name instance-attribute

device_name: str = deviceName

Inherited From VeSyncBaseDevice

device_region instance-attribute

device_region: str | None = deviceRegion

Inherited From VeSyncBaseDevice

device_type instance-attribute

device_type: str = deviceType

Inherited From VeSyncBaseDevice

enabled instance-attribute

enabled: bool = True

Inherited From VeSyncBaseDevice

features instance-attribute

features: list[str] = features

Inherited From VeSyncBaseDevice

firmware_update property

firmware_update: bool

Inherited From VeSyncBaseDevice

Return True if firmware update available.

This is going to be updated.

is_on property

is_on: bool

Inherited From VeSyncBaseDevice

Return true if device is on.

last_response instance-attribute

last_response: ResponseInfo | None = None

Inherited From VeSyncBaseDevice

mac_id instance-attribute

mac_id: str | None = macID

Inherited From VeSyncBaseDevice

manager instance-attribute

manager: VeSync

Inherited From BypassV2Mixin

nightlight_modes instance-attribute

nightlight_modes = nightlight_modes

Inherited From VeSyncOutlet

pid instance-attribute

pid: str | None = None

Inherited From VeSyncBaseDevice

product_type instance-attribute

product_type: str = product_type

Inherited From VeSyncBaseDevice

request_keys class-attribute

request_keys: list[str] = [
    'acceptLanguage',
    'appVersion',
    'phoneBrand',
    'phoneOS',
    'accountID',
    'cid',
    'configModule',
    'debugMode',
    'traceId',
    'timeZone',
    'token',
    'userCountryCode',
    'configModel',
    'deviceId',
]

Inherited From BypassV2Mixin

state instance-attribute

state: OutletState = OutletState(self, details, feature_map)

Inherited From VeSyncBaseDevice

sub_device_no instance-attribute

sub_device_no: int | None = subDeviceNo

Inherited From VeSyncBaseDevice

supports_energy property

supports_energy: bool

Inherited From VeSyncOutlet

Return True if device supports energy.

Returns:

Name Type Description
bool bool

True if device supports energy, False otherwise.

supports_nightlight property

supports_nightlight: bool

Inherited From VeSyncOutlet

Return True if device supports nightlight.

Returns:

Name Type Description
bool bool

True if device supports nightlight, False otherwise.

type instance-attribute

type: str | None = type

Inherited From VeSyncBaseDevice

uuid instance-attribute

uuid: str | None = uuid

Inherited From VeSyncBaseDevice

Functions

call_bypassv2_api async

call_bypassv2_api(
    payload_method: str,
    data: dict | None = None,
    method: str = 'bypassV2',
    endpoint: str = 'bypassV2',
) -> dict | None

Inherited From BypassV2Mixin

Send Bypass V2 API request.

This uses the _build_request method to send API requests to the Bypass V2 API.

Parameters:

Name Type Description Default
payload_method str

The method to use in the payload dict.

required
data dict | None

The data to send in the request.

None
method str

The method to use in the outer body.

'bypassV2'
endpoint str | None

The last part of the API url, defaults to bypassV2, e.g. /cloud/v2/deviceManaged/bypassV2.

'bypassV2'

Returns:

Name Type Description
bytes dict | None

The response from the API request.

Source code in src\pyvesync\utils\device_mixins.py
async def call_bypassv2_api(
    self,
    payload_method: str,
    data: dict | None = None,
    method: str = "bypassV2",
    endpoint: str = "bypassV2",
) -> dict | None:
    """Send Bypass V2 API request.

    This uses the `_build_request` method to send API requests to the Bypass V2 API.

    Args:
        payload_method (str): The method to use in the payload dict.
        data (dict | None): The data to send in the request.
        method (str): The method to use in the outer body.
        endpoint (str | None): The last part of the API url, defaults to
            `bypassV2`, e.g. `/cloud/v2/deviceManaged/bypassV2`.

    Returns:
        bytes: The response from the API request.
    """
    request = self._build_request(payload_method, data, method)
    endpoint = BYPASS_V2_BASE + endpoint
    resp_dict, _ = await self.manager.async_call_api(
        endpoint, "post", request, Helpers.req_header_bypass()
    )
    return resp_dict

clear_timer async

clear_timer() -> bool

Inherited From VeSyncBaseDevice

Clear timer for device from API.

This may not be implemented for all devices. Please open an issue if there is an error.

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def clear_timer(self) -> bool:
    """Clear timer for device from API.

    This may not be implemented for all devices. Please open an issue
    if there is an error.

    Returns:
        bool: True if successful, False otherwise.
    """
    logger.debug('Not implemented - clear_timer')
    return False

display

display(state: bool = True) -> None

Inherited From VeSyncBaseDevice

Print formatted static device info to stdout.

Parameters:

Name Type Description Default
state bool

If True, include state in display, defaults to True.

True

Example:

Device Name:..................Living Room Lamp
Model:........................ESL100
Subdevice No:.................0
Type:.........................wifi
CID:..........................1234567890abcdef

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def display(self, state: bool = True) -> None:
    """Print formatted static device info to stdout.

    Args:
        state (bool): If True, include state in display, defaults to True.

    Example:
    ```
    Device Name:..................Living Room Lamp
    Model:........................ESL100
    Subdevice No:.................0
    Type:.........................wifi
    CID:..........................1234567890abcdef
    ```
    """
    # noinspection SpellCheckingInspection
    display_list = [
        ('Device Name:', self.device_name),
        ('Product Type: ', self.product_type),
        ('Model: ', self.device_type),
        ('Subdevice No: ', str(self.sub_device_no)),
        ('Type: ', self.type),
        ('CID: ', self.cid),
        ('Config Module: ', self.config_module),
        ('Connection Type: ', self.connection_type),
        ('Features', self.features),
        ('Last Response: ', self.last_response),
    ]
    if self.uuid is not None:
        display_list.append(('UUID: ', self.uuid))

    for line in display_list:
        print(f'{line[0]:.<30} {line[1]}')
    if state:
        self.state.display()

displayJSON deprecated

displayJSON(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Deprecated

Use to_json() instead

Return JSON details for device. - Deprecated use to_json().

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
@deprecated("Use to_json() instead")
def displayJSON(self, state: bool = True, indent: bool = True) -> str:  # pylint: disable=invalid-name
    """Return JSON details for device. - Deprecated use to_json()."""
    return self.to_json(state, indent)

get_details async

get_details() -> None

Inherited From VeSyncBaseDevice

Get device details.

This method is defined in each device class to contain the logic to pull the device state from the API and update the device's state attribute. The update() method should be called to update the device state.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def get_details(self) -> None:
    r_dict = await self.call_bypassv2_api('getProperty')

    resp_model = process_bypassv2_result(
        self, logger, "get_details", r_dict, ResponseBSDGO1OutletResult
    )
    if resp_model is None:
        return

    device_state = resp_model.powerSwitch_1
    str_status = DeviceStatus.ON if device_state == 1 else DeviceStatus.OFF
    self.state.device_status = str_status
    self.state.connection_status = resp_model.connectionStatus
    self.state.active_time = resp_model.active_time

get_monthly_energy async

get_monthly_energy() -> None

Inherited From VeSyncOutlet

Build Monthly Energy History Dictionary.

The data is stored in the device.state.monthly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_monthly_energy(self) -> None:
    """Build Monthly Energy History Dictionary.

    The data is stored in the `device.state.monthly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastMonthEnergy')

get_state

get_state(state_attr: str) -> Any

Inherited From VeSyncBaseDevice

Get device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def get_state(self, state_attr: str) -> Any:  # noqa: ANN401
    """Get device state attribute."""
    return getattr(self.state, state_attr)

get_timer async

get_timer() -> Timer | None

Inherited From VeSyncBaseDevice

Get timer for device from API and set the state.Timer attribute.

This may not be implemented for all devices. Please open an issue if there is an error.

Note

This method may not be implemented for all devices. Please open an issue if there is an error.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def get_timer(self) -> Timer | None:
    """Get timer for device from API and set the `state.Timer` attribute.

    This may not be implemented for all devices. Please open an issue
    if there is an error.

    Note:
        This method may not be implemented for all devices. Please
        open an issue if there is an error.
    """
    logger.debug('Not implemented - get_timer')
    return None

get_weekly_energy async

get_weekly_energy() -> None

Inherited From VeSyncOutlet

Build weekly energy history dictionary.

The data is stored in the device.state.weekly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_weekly_energy(self) -> None:
    """Build weekly energy history dictionary.

    The data is stored in the `device.state.weekly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastWeekEnergy')

get_yearly_energy async

get_yearly_energy() -> None

Inherited From VeSyncOutlet

Build Yearly Energy Dictionary.

The data is stored in the device.state.yearly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_yearly_energy(self) -> None:
    """Build Yearly Energy Dictionary.

    The data is stored in the `device.state.yearly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastYearEnergy')

set_nightlight_auto async

set_nightlight_auto() -> bool

Inherited From VeSyncOutlet

Set nightlight to auto mode.

Source code in src\pyvesync\base_devices\outlet_base.py
async def set_nightlight_auto(self) -> bool:
    """Set nightlight to auto mode."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.AUTO)

set_nightlight_state async

set_nightlight_state(mode: str) -> bool

Inherited From VeSyncOutlet

Set nightlight mode.

Available nightlight states are found in the device.nightlight_modes attribute.

Parameters:

Name Type Description Default
mode str

Nightlight mode to set.

required

Returns:

Name Type Description
bool bool

True if nightlight mode set successfully, False otherwise.

Source code in src\pyvesync\base_devices\outlet_base.py
async def set_nightlight_state(self, mode: str) -> bool:
    """Set nightlight mode.

    Available nightlight states are found in the `device.nightlight_modes` attribute.

    Args:
        mode (str): Nightlight mode to set.

    Returns:
        bool: True if nightlight mode set successfully, False otherwise.
    """
    del mode  # unused
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
    else:
        logger.debug("Nightlight mode not configured for %s", self.device_name)
    return False

set_state

set_state(state_attr: str, stat_value: Any) -> None

Inherited From VeSyncBaseDevice

Set device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def set_state(self, state_attr: str, stat_value: Any) -> None:  # noqa: ANN401
    """Set device state attribute."""
    setattr(self, state_attr, stat_value)

set_timer async

set_timer(duration: int, action: str | None = None) -> bool

Inherited From VeSyncBaseDevice

Set timer for device.

This may not be implemented for all devices. Please open an issue if there is an error.

Parameters:

Name Type Description Default
duration int

Duration in seconds.

required
action str | None

Action to take when timer expires.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def set_timer(self, duration: int, action: str | None = None) -> bool:
    """Set timer for device.

    This may not be implemented for all devices. Please open an issue
    if there is an error.

    Args:
        duration (int): Duration in seconds.
        action (str | None): Action to take when timer expires.

    Returns:
        bool: True if successful, False otherwise.
    """
    del duration
    del action
    logger.debug('Not implemented - set_timer')
    return False

to_dict

to_dict(state: bool = True) -> dict[str, Any]

Inherited From VeSyncBaseDevice

Return device information as a dictionary.

Parameters:

Name Type Description Default
state bool

If True, include state in dictionary, defaults to True.

True

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Dictionary containing device information.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_dict(self, state: bool = True) -> dict[str, Any]:
    """Return device information as a dictionary.

    Args:
        state (bool): If True, include state in dictionary, defaults to True.

    Returns:
        dict[str, Any]: Dictionary containing device information.
    """
    device_dict = {
        "device_name": self.device_name,
        "product_type": self.product_type,
        "model": self.device_type,
        "subdevice_no": str(self.sub_device_no),
        "type": self.type,
        "cid": self.cid,
        "features:": self.features,
        "config_module": self.config_module,
        "connection_type": self.connection_type,
        "last_response": self.last_response,
    }
    state_dict = self.state.to_dict() if state else {}
    return device_dict | state_dict

to_json

to_json(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Print JSON API string for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
str str

JSON formatted string of device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_json(self, state: bool = True, indent: bool = True) -> str:
    """Print JSON API string for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        str: JSON formatted string of device details.
    """
    return self.to_jsonb(state, indent).decode()

to_jsonb

to_jsonb(state: bool = True, indent: bool = True) -> bytes

Inherited From VeSyncBaseDevice

JSON API bytes for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
bytes bytes

JSON formatted bytes of device details.

Example

This is an example without state.

{
    "Device Name": "Living Room Lamp",
    "Model": "ESL100",
    "Subdevice No": "0",
    "Type": "wifi",
    "CID": "1234567890abcdef"
}

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_jsonb(self, state: bool = True, indent: bool = True) -> bytes:
    """JSON API bytes for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        bytes: JSON formatted bytes of device details.

    Example:
        This is an example without state.
        ```
        {
            "Device Name": "Living Room Lamp",
            "Model": "ESL100",
            "Subdevice No": "0",
            "Type": "wifi",
            "CID": "1234567890abcdef"
        }
        ```
    """
    return_dict = self.to_dict(state=state)
    if indent:
        return orjson.dumps(
            return_dict,
            option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS,
        )

    return orjson.dumps(return_dict, option=orjson.OPT_NON_STR_KEYS)

toggle_switch async

toggle_switch(toggle: bool | None = None) -> bool

Inherited From VeSyncBaseToggleDevice

Toggle device power on or off.

Parameters:

Name Type Description Default
toggle bool | None

True to turn on, False to turn off, None to toggle.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\devices\vesyncoutlet.py
async def toggle_switch(self, toggle: bool | None = None) -> bool:
    if toggle is None:
        toggle = self.state.device_status != DeviceStatus.ON
    toggle_int = 1 if toggle else 0
    r_dict = await self.call_bypassv2_api(
        "setProperty", data={"powerSwitch_1": toggle_int}
    )
    r = Helpers.process_dev_response(logger, "toggle_switch", self, r_dict)
    if r is None:
        return False

    self.state.device_status = DeviceStatus.ON if toggle else DeviceStatus.OFF
    self.state.connection_status = ConnectionStatus.ONLINE
    return True

turn_off async

turn_off() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device off.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_off(self) -> bool:
    """Turn device off."""
    return await self.toggle_switch(False)

turn_off_nightlight async

turn_off_nightlight() -> bool

Inherited From VeSyncOutlet

Turn off nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_off_nightlight(self) -> bool:
    """Turn off nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.OFF)

turn_on async

turn_on() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device on.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_on(self) -> bool:
    """Turn device on."""
    return await self.toggle_switch(True)

turn_on_nightlight async

turn_on_nightlight() -> bool

Inherited From VeSyncOutlet

Turn on nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_on_nightlight(self) -> bool:
    """Turn on nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.ON)

update async

update() -> None

Inherited From VeSyncBaseDevice

Update device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def update(self) -> None:
    """Update device details."""
    await self.get_details()

update_energy async

update_energy() -> None

Inherited From VeSyncOutlet

Build weekly, monthly and yearly dictionaries.

Source code in src\pyvesync\base_devices\outlet_base.py
async def update_energy(self) -> None:
    """Build weekly, monthly and yearly dictionaries."""
    if self.supports_energy:
        await self.get_weekly_energy()
        await self.get_monthly_energy()
        await self.get_yearly_energy()

pyvesync.base_devices.outlet_base.VeSyncOutlet

Bases: VeSyncBaseToggleDevice

Base class for Etekcity Outlets.

State is stored in the state attribute of the device. This is only for holding state information and does not contain any methods for controlling the device or retrieving information from the API.

Parameters:

Name Type Description Default
details ResponseDeviceDetailsModel

The device details.

required
manager VeSync

The VeSync manager.

required
feature_map OutletMap

The feature map for the device.

required

Attributes:

Name Type Description
state OutletState

The state of the outlet.

last_response ResponseInfo

Last response from API call.

manager VeSync

Manager object for API calls.

device_name str

Name of device.

device_image str

URL for device image.

cid str

Device ID.

connection_type str

Connection type of device.

device_type str

Type of device.

type str

Type of device.

uuid str

UUID of device, not always present.

config_module str

Configuration module of device.

mac_id str

MAC ID of device.

current_firm_version str

Current firmware version of device.

device_region str

Region of device. (US, EU, etc.)

pid str

Product ID of device, pulled by some devices on update.

sub_device_no int

Sub-device number of device.

product_type str

Product type of device.

features dict

Features of device.

Source code in src\pyvesync\base_devices\outlet_base.py
class VeSyncOutlet(VeSyncBaseToggleDevice):
    """Base class for Etekcity Outlets.

    State is stored in the `state` attribute of the device.
    This is only for holding state information and does not
    contain any methods for controlling the device or retrieving
    information from the API.

    Args:
        details (ResponseDeviceDetailsModel): The device details.
        manager (VeSync): The VeSync manager.
        feature_map (OutletMap): The feature map for the device.

    Attributes:
        state (OutletState): The state of the outlet.
        last_response (ResponseInfo): Last response from API call.
        manager (VeSync): Manager object for API calls.
        device_name (str): Name of device.
        device_image (str): URL for device image.
        cid (str): Device ID.
        connection_type (str): Connection type of device.
        device_type (str): Type of device.
        type (str): Type of device.
        uuid (str): UUID of device, not always present.
        config_module (str): Configuration module of device.
        mac_id (str): MAC ID of device.
        current_firm_version (str): Current firmware version of device.
        device_region (str): Region of device. (US, EU, etc.)
        pid (str): Product ID of device, pulled by some devices on update.
        sub_device_no (int): Sub-device number of device.
        product_type (str): Product type of device.
        features (dict): Features of device.
    """

    # __metaclass__ = ABCMeta

    def __init__(self, details: ResponseDeviceDetailsModel,
                 manager: VeSync, feature_map: OutletMap) -> None:
        """Initialize VeSync Outlet base class."""
        super().__init__(details, manager, feature_map)
        self.state: OutletState = OutletState(self, details, feature_map)
        self.nightlight_modes = feature_map.nightlight_modes

    def _build_energy_request(self, method: str) -> RequestEnergyHistory:
        """Build energy request post."""
        request_keys = ["acceptLanguage", "accountID", "appVersion", "phoneBrand",
                        "phoneOS", "timeZone", "token", "traceId", "userCountryCode",
                        "debugMode", "homeTimeZone", "uuid"]
        body = Helpers.get_class_attributes(DefaultValues, request_keys)
        body.update(Helpers.get_class_attributes(self.manager, request_keys))
        body.update(Helpers.get_class_attributes(self, request_keys))
        body['method'] = method
        return RequestEnergyHistory.from_dict(body)

    async def _get_energy_history(self, history_interval: str) -> None:
        """Internal function to pull energy history.

        Args:
            history_interval (str): The interval for the energy history,
                options are 'getLastWeekEnergy', 'getLastMonthEnergy', 'getLastYearEnergy'

        Note:
            Builds the state.<history_interval>_history attribute.
        """
        if not self.supports_energy:
            logger.debug("Device does not support energy monitoring.")
            return
        history_intervals = [
            'getLastWeekEnergy', 'getLastMonthEnergy', 'getLastYearEnergy'
            ]
        if history_interval not in history_intervals:
            logger.debug("Invalid history interval: %s", history_interval)
            return
        body = self._build_energy_request(history_interval)
        headers = Helpers.req_header_bypass()
        r_bytes, _ = await self.manager.async_call_api(
            f'/cloud/v1/device/{history_interval}',
            'post',
            headers=headers,
            json_object=body.to_dict(),
        )

        r = Helpers.process_dev_response(
            logger, history_interval, self, r_bytes
            )
        if r is None:
            return
        response = ResponseEnergyHistory.from_dict(r)
        match history_interval:
            case 'getLastWeekEnergy':
                self.state.weekly_history = response.result
            case 'getLastMonthEnergy':
                self.state.monthly_history = response.result
            case 'getLastYearEnergy':
                self.state.yearly_history = response.result

    @property
    def supports_nightlight(self) -> bool:
        """Return True if device supports nightlight.

        Returns:
            bool: True if device supports nightlight, False otherwise.
        """
        return OutletFeatures.NIGHTLIGHT in self.features

    @property
    def supports_energy(self) -> bool:
        """Return True if device supports energy.

        Returns:
            bool: True if device supports energy, False otherwise.
        """
        return OutletFeatures.ENERGY_MONITOR in self.features

    async def get_weekly_energy(self) -> None:
        """Build weekly energy history dictionary.

        The data is stored in the `device.state.weekly_history` attribute
        as a `ResponseEnergyResult` object.
        """
        await self._get_energy_history('getLastWeekEnergy')

    async def get_monthly_energy(self) -> None:
        """Build Monthly Energy History Dictionary.

        The data is stored in the `device.state.monthly_history` attribute
        as a `ResponseEnergyResult` object.
        """
        await self._get_energy_history('getLastMonthEnergy')

    async def get_yearly_energy(self) -> None:
        """Build Yearly Energy Dictionary.

        The data is stored in the `device.state.yearly_history` attribute
        as a `ResponseEnergyResult` object.
        """
        await self._get_energy_history('getLastYearEnergy')

    async def update_energy(self) -> None:
        """Build weekly, monthly and yearly dictionaries."""
        if self.supports_energy:
            await self.get_weekly_energy()
            await self.get_monthly_energy()
            await self.get_yearly_energy()

    async def set_nightlight_state(self, mode: str) -> bool:
        """Set nightlight mode.

        Available nightlight states are found in the `device.nightlight_modes` attribute.

        Args:
            mode (str): Nightlight mode to set.

        Returns:
            bool: True if nightlight mode set successfully, False otherwise.
        """
        del mode  # unused
        if not self.supports_nightlight:
            logger.debug("Device does not support nightlight.")
        else:
            logger.debug("Nightlight mode not configured for %s", self.device_name)
        return False

    async def turn_on_nightlight(self) -> bool:
        """Turn on nightlight if supported."""
        if not self.supports_nightlight:
            logger.debug("Device does not support nightlight.")
            return False
        return await self.set_nightlight_state(NightlightModes.ON)

    async def turn_off_nightlight(self) -> bool:
        """Turn off nightlight if supported."""
        if not self.supports_nightlight:
            logger.debug("Device does not support nightlight.")
            return False
        return await self.set_nightlight_state(NightlightModes.OFF)

    async def set_nightlight_auto(self) -> bool:
        """Set nightlight to auto mode."""
        if not self.supports_nightlight:
            logger.debug("Device does not support nightlight.")
            return False
        return await self.set_nightlight_state(NightlightModes.AUTO)

Attributes

cid instance-attribute

cid: str = cid

Inherited From VeSyncBaseDevice

config_module instance-attribute

config_module: str = configModule

Inherited From VeSyncBaseDevice

connection_type instance-attribute

connection_type: str | None = connectionType

Inherited From VeSyncBaseDevice

current_firm_version instance-attribute

current_firm_version = currentFirmVersion

Inherited From VeSyncBaseDevice

device_image instance-attribute

device_image: str | None = deviceImg

Inherited From VeSyncBaseDevice

device_name instance-attribute

device_name: str = deviceName

Inherited From VeSyncBaseDevice

device_region instance-attribute

device_region: str | None = deviceRegion

Inherited From VeSyncBaseDevice

device_type instance-attribute

device_type: str = deviceType

Inherited From VeSyncBaseDevice

enabled instance-attribute

enabled: bool = True

Inherited From VeSyncBaseDevice

features instance-attribute

features: list[str] = features

Inherited From VeSyncBaseDevice

firmware_update property

firmware_update: bool

Inherited From VeSyncBaseDevice

Return True if firmware update available.

This is going to be updated.

is_on property

is_on: bool

Inherited From VeSyncBaseDevice

Return true if device is on.

last_response instance-attribute

last_response: ResponseInfo | None = None

Inherited From VeSyncBaseDevice

mac_id instance-attribute

mac_id: str | None = macID

Inherited From VeSyncBaseDevice

manager instance-attribute

manager = manager

Inherited From VeSyncBaseDevice

nightlight_modes instance-attribute

nightlight_modes = nightlight_modes

Inherited From VeSyncOutlet

pid instance-attribute

pid: str | None = None

Inherited From VeSyncBaseDevice

product_type instance-attribute

product_type: str = product_type

Inherited From VeSyncBaseDevice

state instance-attribute

state: OutletState = OutletState(self, details, feature_map)

Inherited From VeSyncBaseDevice

sub_device_no instance-attribute

sub_device_no: int | None = subDeviceNo

Inherited From VeSyncBaseDevice

supports_energy property

supports_energy: bool

Inherited From VeSyncOutlet

Return True if device supports energy.

Returns:

Name Type Description
bool bool

True if device supports energy, False otherwise.

supports_nightlight property

supports_nightlight: bool

Inherited From VeSyncOutlet

Return True if device supports nightlight.

Returns:

Name Type Description
bool bool

True if device supports nightlight, False otherwise.

type instance-attribute

type: str | None = type

Inherited From VeSyncBaseDevice

uuid instance-attribute

uuid: str | None = uuid

Inherited From VeSyncBaseDevice

Functions

clear_timer async

clear_timer() -> bool

Inherited From VeSyncBaseDevice

Clear timer for device from API.

This may not be implemented for all devices. Please open an issue if there is an error.

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def clear_timer(self) -> bool:
    """Clear timer for device from API.

    This may not be implemented for all devices. Please open an issue
    if there is an error.

    Returns:
        bool: True if successful, False otherwise.
    """
    logger.debug('Not implemented - clear_timer')
    return False

display

display(state: bool = True) -> None

Inherited From VeSyncBaseDevice

Print formatted static device info to stdout.

Parameters:

Name Type Description Default
state bool

If True, include state in display, defaults to True.

True

Example:

Device Name:..................Living Room Lamp
Model:........................ESL100
Subdevice No:.................0
Type:.........................wifi
CID:..........................1234567890abcdef

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def display(self, state: bool = True) -> None:
    """Print formatted static device info to stdout.

    Args:
        state (bool): If True, include state in display, defaults to True.

    Example:
    ```
    Device Name:..................Living Room Lamp
    Model:........................ESL100
    Subdevice No:.................0
    Type:.........................wifi
    CID:..........................1234567890abcdef
    ```
    """
    # noinspection SpellCheckingInspection
    display_list = [
        ('Device Name:', self.device_name),
        ('Product Type: ', self.product_type),
        ('Model: ', self.device_type),
        ('Subdevice No: ', str(self.sub_device_no)),
        ('Type: ', self.type),
        ('CID: ', self.cid),
        ('Config Module: ', self.config_module),
        ('Connection Type: ', self.connection_type),
        ('Features', self.features),
        ('Last Response: ', self.last_response),
    ]
    if self.uuid is not None:
        display_list.append(('UUID: ', self.uuid))

    for line in display_list:
        print(f'{line[0]:.<30} {line[1]}')
    if state:
        self.state.display()

displayJSON deprecated

displayJSON(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Deprecated

Use to_json() instead

Return JSON details for device. - Deprecated use to_json().

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
@deprecated("Use to_json() instead")
def displayJSON(self, state: bool = True, indent: bool = True) -> str:  # pylint: disable=invalid-name
    """Return JSON details for device. - Deprecated use to_json()."""
    return self.to_json(state, indent)

get_details abstractmethod async

get_details() -> None

Inherited From VeSyncBaseDevice

Get device details.

This method is defined in each device class to contain the logic to pull the device state from the API and update the device's state attribute. The update() method should be called to update the device state.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
@abstractmethod
async def get_details(self) -> None:
    """Get device details.

    This method is defined in each device class to contain
    the logic to pull the device state from the API and update
    the device's `state` attribute. The `update()` method should
    be called to update the device state.
    """

get_monthly_energy async

get_monthly_energy() -> None

Inherited From VeSyncOutlet

Build Monthly Energy History Dictionary.

The data is stored in the device.state.monthly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_monthly_energy(self) -> None:
    """Build Monthly Energy History Dictionary.

    The data is stored in the `device.state.monthly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastMonthEnergy')

get_state

get_state(state_attr: str) -> Any

Inherited From VeSyncBaseDevice

Get device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def get_state(self, state_attr: str) -> Any:  # noqa: ANN401
    """Get device state attribute."""
    return getattr(self.state, state_attr)

get_timer async

get_timer() -> Timer | None

Inherited From VeSyncBaseDevice

Get timer for device from API and set the state.Timer attribute.

This may not be implemented for all devices. Please open an issue if there is an error.

Note

This method may not be implemented for all devices. Please open an issue if there is an error.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def get_timer(self) -> Timer | None:
    """Get timer for device from API and set the `state.Timer` attribute.

    This may not be implemented for all devices. Please open an issue
    if there is an error.

    Note:
        This method may not be implemented for all devices. Please
        open an issue if there is an error.
    """
    logger.debug('Not implemented - get_timer')
    return None

get_weekly_energy async

get_weekly_energy() -> None

Inherited From VeSyncOutlet

Build weekly energy history dictionary.

The data is stored in the device.state.weekly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_weekly_energy(self) -> None:
    """Build weekly energy history dictionary.

    The data is stored in the `device.state.weekly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastWeekEnergy')

get_yearly_energy async

get_yearly_energy() -> None

Inherited From VeSyncOutlet

Build Yearly Energy Dictionary.

The data is stored in the device.state.yearly_history attribute as a ResponseEnergyResult object.

Source code in src\pyvesync\base_devices\outlet_base.py
async def get_yearly_energy(self) -> None:
    """Build Yearly Energy Dictionary.

    The data is stored in the `device.state.yearly_history` attribute
    as a `ResponseEnergyResult` object.
    """
    await self._get_energy_history('getLastYearEnergy')

set_nightlight_auto async

set_nightlight_auto() -> bool

Inherited From VeSyncOutlet

Set nightlight to auto mode.

Source code in src\pyvesync\base_devices\outlet_base.py
async def set_nightlight_auto(self) -> bool:
    """Set nightlight to auto mode."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.AUTO)

set_nightlight_state async

set_nightlight_state(mode: str) -> bool

Inherited From VeSyncOutlet

Set nightlight mode.

Available nightlight states are found in the device.nightlight_modes attribute.

Parameters:

Name Type Description Default
mode str

Nightlight mode to set.

required

Returns:

Name Type Description
bool bool

True if nightlight mode set successfully, False otherwise.

Source code in src\pyvesync\base_devices\outlet_base.py
async def set_nightlight_state(self, mode: str) -> bool:
    """Set nightlight mode.

    Available nightlight states are found in the `device.nightlight_modes` attribute.

    Args:
        mode (str): Nightlight mode to set.

    Returns:
        bool: True if nightlight mode set successfully, False otherwise.
    """
    del mode  # unused
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
    else:
        logger.debug("Nightlight mode not configured for %s", self.device_name)
    return False

set_state

set_state(state_attr: str, stat_value: Any) -> None

Inherited From VeSyncBaseDevice

Set device state attribute.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def set_state(self, state_attr: str, stat_value: Any) -> None:  # noqa: ANN401
    """Set device state attribute."""
    setattr(self, state_attr, stat_value)

set_timer async

set_timer(duration: int, action: str | None = None) -> bool

Inherited From VeSyncBaseDevice

Set timer for device.

This may not be implemented for all devices. Please open an issue if there is an error.

Parameters:

Name Type Description Default
duration int

Duration in seconds.

required
action str | None

Action to take when timer expires.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def set_timer(self, duration: int, action: str | None = None) -> bool:
    """Set timer for device.

    This may not be implemented for all devices. Please open an issue
    if there is an error.

    Args:
        duration (int): Duration in seconds.
        action (str | None): Action to take when timer expires.

    Returns:
        bool: True if successful, False otherwise.
    """
    del duration
    del action
    logger.debug('Not implemented - set_timer')
    return False

to_dict

to_dict(state: bool = True) -> dict[str, Any]

Inherited From VeSyncBaseDevice

Return device information as a dictionary.

Parameters:

Name Type Description Default
state bool

If True, include state in dictionary, defaults to True.

True

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Dictionary containing device information.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_dict(self, state: bool = True) -> dict[str, Any]:
    """Return device information as a dictionary.

    Args:
        state (bool): If True, include state in dictionary, defaults to True.

    Returns:
        dict[str, Any]: Dictionary containing device information.
    """
    device_dict = {
        "device_name": self.device_name,
        "product_type": self.product_type,
        "model": self.device_type,
        "subdevice_no": str(self.sub_device_no),
        "type": self.type,
        "cid": self.cid,
        "features:": self.features,
        "config_module": self.config_module,
        "connection_type": self.connection_type,
        "last_response": self.last_response,
    }
    state_dict = self.state.to_dict() if state else {}
    return device_dict | state_dict

to_json

to_json(state: bool = True, indent: bool = True) -> str

Inherited From VeSyncBaseDevice

Print JSON API string for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
str str

JSON formatted string of device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_json(self, state: bool = True, indent: bool = True) -> str:
    """Print JSON API string for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        str: JSON formatted string of device details.
    """
    return self.to_jsonb(state, indent).decode()

to_jsonb

to_jsonb(state: bool = True, indent: bool = True) -> bytes

Inherited From VeSyncBaseDevice

JSON API bytes for device details.

Parameters:

Name Type Description Default
state bool

If True, include state in JSON output, defaults to True.

True
indent bool

If True, indent JSON output, defaults to True.

True

Returns:

Name Type Description
bytes bytes

JSON formatted bytes of device details.

Example

This is an example without state.

{
    "Device Name": "Living Room Lamp",
    "Model": "ESL100",
    "Subdevice No": "0",
    "Type": "wifi",
    "CID": "1234567890abcdef"
}

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
def to_jsonb(self, state: bool = True, indent: bool = True) -> bytes:
    """JSON API bytes for device details.

    Args:
        state (bool): If True, include state in JSON output, defaults to True.
        indent (bool): If True, indent JSON output, defaults to True.

    Returns:
        bytes: JSON formatted bytes of device details.

    Example:
        This is an example without state.
        ```
        {
            "Device Name": "Living Room Lamp",
            "Model": "ESL100",
            "Subdevice No": "0",
            "Type": "wifi",
            "CID": "1234567890abcdef"
        }
        ```
    """
    return_dict = self.to_dict(state=state)
    if indent:
        return orjson.dumps(
            return_dict,
            option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS,
        )

    return orjson.dumps(return_dict, option=orjson.OPT_NON_STR_KEYS)

toggle_switch abstractmethod async

toggle_switch(toggle: bool | None = None) -> bool

Inherited From VeSyncBaseToggleDevice

Toggle device power on or off.

Parameters:

Name Type Description Default
toggle bool | None

True to turn on, False to turn off, None to toggle.

None

Returns:

Name Type Description
bool bool

True if successful, False otherwise.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
@abstractmethod
async def toggle_switch(self, toggle: bool | None = None) -> bool:
    """Toggle device power on or off.

    Args:
        toggle (bool | None): True to turn on, False to turn off, None to toggle.

    Returns:
        bool: True if successful, False otherwise.
    """

turn_off async

turn_off() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device off.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_off(self) -> bool:
    """Turn device off."""
    return await self.toggle_switch(False)

turn_off_nightlight async

turn_off_nightlight() -> bool

Inherited From VeSyncOutlet

Turn off nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_off_nightlight(self) -> bool:
    """Turn off nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.OFF)

turn_on async

turn_on() -> bool

Inherited From VeSyncBaseToggleDevice

Turn device on.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def turn_on(self) -> bool:
    """Turn device on."""
    return await self.toggle_switch(True)

turn_on_nightlight async

turn_on_nightlight() -> bool

Inherited From VeSyncOutlet

Turn on nightlight if supported.

Source code in src\pyvesync\base_devices\outlet_base.py
async def turn_on_nightlight(self) -> bool:
    """Turn on nightlight if supported."""
    if not self.supports_nightlight:
        logger.debug("Device does not support nightlight.")
        return False
    return await self.set_nightlight_state(NightlightModes.ON)

update async

update() -> None

Inherited From VeSyncBaseDevice

Update device details.

Source code in src\pyvesync\base_devices\vesyncbasedevice.py
async def update(self) -> None:
    """Update device details."""
    await self.get_details()

update_energy async

update_energy() -> None

Inherited From VeSyncOutlet

Build weekly, monthly and yearly dictionaries.

Source code in src\pyvesync\base_devices\outlet_base.py
async def update_energy(self) -> None:
    """Build weekly, monthly and yearly dictionaries."""
    if self.supports_energy:
        await self.get_weekly_energy()
        await self.get_monthly_energy()
        await self.get_yearly_energy()