Skip to main content

A Python client for the dLight smart lamp API.

Project description

python-dlight-client - Async Python Client for dLight API

PyPI version Python Versions

This Python package provides an asynchronous (asyncio) client library for discovering and controlling dLight smart lamps over a local Wi-Fi network. It allows you to find dLight devices using UDP broadcasts and control them using TCP commands.

Table of Contents

Features

  • Asynchronous: Built with asyncio for efficient, non-blocking network operations.
  • Device Discovery: Find dLight devices on your local network using UDP broadcast (discover_devices).
  • High-Level Device Control: An easy-to-use DLightDevice class for object-oriented control of a specific lamp.
  • Performance Optimized (New):
    • Persistent TCP Connections: Reuse connections for sequential commands to reduce latency.
    • Connection Concurrency Safety: Automatic locking ensures multiple concurrent tasks can share a client safely.
    • Idle Timeout: Stale connections are automatically closed and refreshed after a period of inactivity (default 60s).
    • State Caching & Optimistic Updates: Internal cache in DLightDevice reduces redundant network queries and provides immediate feedback.
  • Developer Friendly:
    • Structured Models: Use TypedDict models (DeviceState, DeviceInfo, etc.) for better IDE support and type safety.
  • State Control:
    • Turn On/Off
    • Set Brightness (0-100%)
    • Set Color Temperature (2600K-6000K)
  • Device Query:
    • Get the current state (power, brightness, color).
    • Get device information (model, firmware version, etc.).
  • Wi-Fi Provisioning: Send Wi-Fi credentials to a device in SoftAP mode for initial setup.
  • Robust Communication: Handles the dLight TCP protocol (4-byte length prefix + JSON payload) and includes timeouts.
  • Custom Error Handling: Specific exceptions for network and device errors (e.g., DLightTimeoutError, DLightResponseError).
  • Command-Line Tool: A convenient CLI for quick discovery and interaction.

Prerequisites

  • A dLight device connected to your local Wi-Fi network (or in SoftAP mode for initial setup).
  • Python 3.9 through 3.13 (officially supported).

Installation

pip install dlight-client

Usage

You can use this package as a library in your Python projects or via the included command-line tool.

As a Library

Using the library typically involves two steps: discovering devices to get their IP address and ID, and then creating a DLightDevice instance to interact with a specific lamp.

1. Discovering Devices

First, use the discover_devices function to find lamps on your network.

import asyncio
from dlightclient import discover_devices

async def find_devices():
    print("--- Discovering Devices ---")
    devices = await discover_devices(discovery_duration=3.0)

    for i, device_info in enumerate(devices):
        ip = device_info.get('ip_address')
        dev_id = device_info.get('deviceId')
        print(f"  Device {i+1}: ID={dev_id}, IP={ip}")

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

2. Controlling a Device

Once you have the ip_address and deviceId, you can use the high-level DLightDevice class for intuitive control.

import asyncio
from dlightclient import AsyncDLightClient, DLightDevice

async def run_example():
    # The client handles the underlying TCP communication
    client = AsyncDLightClient()

    # The device object is the high-level interface
    device = DLightDevice(ip_address="192.168.1.123", device_id="DL12345", client=client)

    # Simple control commands
    await device.turn_on()
    await device.set_brightness(75)
    
    # State caching: get_state() returns cached value by default
    state = await device.get_state() 
    print(f"Current Brightness (cached): {state.get('brightness')}%")

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

3. Performance Optimization

For applications that need to send many commands in a row, use Persistent Connections to eliminate connection setup overhead.

Option A: Scoped Persistence (Context Manager)

from dlightclient import AsyncDLightClient, DLightDevice

async with AsyncDLightClient() as client:
    device = DLightDevice(ip_address="192.168.1.123", device_id="DL12345", client=client)
    # Both commands will use the SAME TCP connection
    await device.turn_on()
    await device.set_brightness(50)

Option B: Global Persistence

client = AsyncDLightClient(persistent=True)
# ... perform operations ...
await client.close() # Explicitly close when finished

Using the Command-Line Tool (CLI)

The package includes a basic CLI for common operations.

# Discover all devices on the network
python -m dlightclient.cli --discover

# Interact with a specific device using a test sequence
python -m dlightclient.cli --ip 192.168.1.100 --id DL12345

API Overview

  • dlightclient.discovery.discover_devices: Uses UDP broadcast to find devices on the network.
  • dlightclient.client.AsyncDLightClient: The low-level TCP client. Supports persistent=True.
  • dlightclient.device.DLightDevice: High-level class. Includes state caching automatically.
  • dlightclient.exceptions: Custom exceptions hierarchy rooted in DLightError.

Development and Testing

  1. Set up a virtual environment:

    python -m venv .venv
    source .venv/bin/activate
    
  2. Install in editable mode:

    pip install -e .
    
  3. Run tests:

    python -m unittest discover tests/
    

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dlight_client-1.6.0.tar.gz (37.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dlight_client-1.6.0-py3-none-any.whl (26.2 kB view details)

Uploaded Python 3

File details

Details for the file dlight_client-1.6.0.tar.gz.

File metadata

  • Download URL: dlight_client-1.6.0.tar.gz
  • Upload date:
  • Size: 37.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for dlight_client-1.6.0.tar.gz
Algorithm Hash digest
SHA256 e80eaaabcd112e2cb83a381854607da065115bdd830e18b6ab35ece05e846ec4
MD5 878da1fa821242feccef39bcbda922a8
BLAKE2b-256 cc2d8e0ab6de0babbe69617b0ba26e320d5875b02a1a7988947fe0244e7d8ad8

See more details on using hashes here.

Provenance

The following attestation bundles were made for dlight_client-1.6.0.tar.gz:

Publisher: python-publish.yml on Irishsmurf/dlight-client

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file dlight_client-1.6.0-py3-none-any.whl.

File metadata

  • Download URL: dlight_client-1.6.0-py3-none-any.whl
  • Upload date:
  • Size: 26.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for dlight_client-1.6.0-py3-none-any.whl
Algorithm Hash digest
SHA256 cf423645bc326801dcf7bd1e61a3a85389bfa9854637d320d4fa1fc62b993994
MD5 5e06ef813d4c3b01c0b1c46bc696d038
BLAKE2b-256 2f8b795c479e17e81cbbda34df2eba4562ebf6a70e8df4d1eb59ffe771c0f629

See more details on using hashes here.

Provenance

The following attestation bundles were made for dlight_client-1.6.0-py3-none-any.whl:

Publisher: python-publish.yml on Irishsmurf/dlight-client

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page