dirigera Python Client

repository·main·Indexed 42 days ago

https://github.com/leggin/dirigera

An unofficial Python client (v1.2.7) for controlling the IKEA Dirigera Smart Home Hub. It provides a Pythonic API to interact with lights, outlets, air purifiers, blinds, and various sensors, as well as tools for scene management and real-time event listening via a Hub client.

Tokens
12.7K
Snippets
57
Records
70
Agent score
52%

What's inside dirigera

  1. Understand Core Device Data and Attributes

    main

    Every device in the Dirigera ecosystem shares a common data structure.

    Core Data Fields

    • id: Unique identifier (string).
    • relation_id: Optional relation identifier.
    • type / device_type: Categorization strings.
    • is_reachable: Boolean indicating if the device is online.
    • attributes: A nested object containing device-specific properties.
    • capabilities: Lists of can_send and can_receive actions.
    • room: An optional Room object containing id, name, color, and icon.

    Common Attributes

    All devices include these attributes:

    • custom_name: User-defined name.
    • model, manufacturer, firmware_version, hardware_version.
    • serial_number, product_code (optional).
    • ota_status, ota_state, ota_progress, ota_policy, ota_schedule_start, ota_schedule_end (OTA update related).
  2. Set up the development environment

    main

    To set up a local development environment, run the provided setup.sh script. This script automates the creation of a virtual environment (venv) and installs both standard (requirements.txt) and development (dev-requirements.txt) dependencies.

    Testing and Linting Commands:

    • Run tests: ./run-test.sh or pytest .
    • Run linting: ./run-pylint.sh
    • Run type checking: ./run-mypy.sh
    • Test multiple Python versions: ./run-python-verions-test.sh (requires Docker)
    ./setup.sh
  3. Generate a Dirigera authentication token

    main

    To use the client, you must first obtain an authentication token from your Dirigera hub.

    1. Identify your Dirigera's IP address via your router.
    2. Run the generate-token script provided by the package, passing the IP address as an argument.
    3. When prompted, physically press the action button on the bottom of your Dirigera hub.
    4. Press ENTER in the terminal to receive your token.
    ```bashngenerate-token <Dirigera ip-address>
  4. Initialize the Dirigera Hub client

    main

    Create a dirigera.Hub instance by providing your generated authentication token and the hub's IP address. This object serves as the primary entry point for interacting with your smart home devices.

    import dirigera
    
    dirigera_hub = dirigera.Hub(
        token="mgwB.aXqwpzV89N0aUwBhZMJjD8a...",
        ip_address="192.1..."
    )
  5. Manage Remote Controllers

    main

    Retrieve available controllers (currently tested with STYRBAR) using get_controllers().

    Attributes:

    • is_on: Boolean status.
    • battery_percentage: Integer percentage.
    • switch_label: String label.

    Methods:

    • reload(): Refresh controller data.
    • set_name(name: str): Update the controller's name.
    controllers = dirigera_hub.get_controllers()
  6. Use the Dirigera Hub API

    main

    The dirigera.Hub class provides methods for low-level HTTP requests and high-level device management.

    Low-level HTTP Methods

    • patch(route, data): Send a PATCH request.
    • get(route): Send a GET request.
    • post(route, data): Send a POST request.
    • delete(route): Send a DELETE request.

    High-level Device Fetching

    The hub provides specialized methods to fetch specific device types by ID, name, or in bulk:

    • Air Purifiers: get_air_purifiers(), get_air_purifier_by_id(id_)
    • Lights: get_lights(), get_light_by_id(id_), get_light_by_name(lamp_name)
    • Outlets: get_outlets(), get_outlet_by_id(id_), get_outlet_by_name(outlet_name)
    • Environment Sensors: get_environment_sensors(), get_environment_sensor_by_id(id_)
    • Motion Sensors: get_motion_sensors(), get_motion_sensor_by_id(id_), get_motion_sensor_by_name(motion_sensor_name)
    • Open/Close Sensors: get_open_close_sensors(), get_open_close_by_id(id_)
    • Blinds: get_blinds(), get_blind_by_id(id_), get_blind_by_name(blind_name)
    • Controllers: get_controllers(), get_controller_by_id(id_), get_controller_by_name(controller_name)
    • Water Sensors: get_water_sensors(), get_water_sensor_by_id(id_)
    • Occupancy Sensors: get_occupancy_sensors(), get_occupancy_sensor_by_id(id_)
    • Light Sensors: get_light_sensors(), get_light_sensor_by_id(id_)
    • General: get_all_devices()

    Scene Management

    • get_scenes(): Fetch all scenes.
    • get_scene_by_id(scene_id): Fetch a specific scene.
    • create_scene(info, scene_type, triggers, actions): Create a new scene.
    • delete_scene(scene_id): Delete a scene.
  7. Control Blinds

    main

    Use get_blinds() on the dirigera_hub instance to retrieve a list of available blinds. Each blind object provides access to its current and target levels, state, and battery percentage.

    Available Methods:

    • reload(): Refresh the blind's data from the hub.
    • set_name(name: str): Update the blind's name.
    • set_target_level(target_level: int): Set the blind level (0-100).
    blinds = dirigera_hub.get_blinds()
    # Example usage
    blind = blinds[0]
    blind.set_target_level(target_level=90)
  8. Listen to Hub Events

    main

    Use create_event_listener to subscribe to real-time events published by the Dirigera hub (e.g., deviceStateChanged). This allows you to react to changes like lights turning on/off or color temperature adjustments.

    Provide two callback functions:

    1. on_message(ws, message): Handles incoming event data. The message is a JSON string containing the event type and data.
    2. on_error(ws, message): Handles errors.
    import json
    from typing import Any
    
    def on_message(ws: Any, message: str):
        message_dict = json.loads(message)
        data = message_dict["data"]
        # Example: check if the event belongs to a specific light
        if data["id"] == bed_light.light_id:
            print(f"Event on {bed_light.custom_name}: {data['attributes']}")
    
    def on_error(ws: Any, message: str):
        print(f"Error: {message}")
    
    dirigera_hub.create_event_listener(
        on_message=on_message, on_error=on_error
    )
  9. Control Lights

    main

    After fetching a light object via get_lights(), you can control its state and appearance.

    Light Attributes

    • is_on: Current power state.
    • light_level: Brightness (0-100).
    • color_temperature: Kelvin value.
    • color_hue: Hue (0-360).
    • color_saturation: Saturation (0.0-1.0).

    Light Methods

    • reload(): Refresh data from the hub.
    • set_name(name): Update the device name.
    • set_light(lamp_on): Turn the light on or off.
    • set_light_level(light_level): Set brightness (1-100).
    • set_color_temperature(color_temp): Set temperature.
    • set_light_color(hue, saturation): Set color using HSL.
    • set_startup_behaviour(behaviour): Set behavior on power-up using StartupEnum.
    lights = dirigera_hub.get_lights()
    light = lights[0]
    light.set_light(lamp_on=True)
    light.set_light_level(light_level=90)
    light.set_light_color(hue=128, saturation=0.5)
  10. Monitor Motion and Open/Close Sensors

    main

    Motion Sensors

    Retrieve motion sensors via get_motion_sensors().

    • Attributes: is_on (bool), is_detected (bool), light_level (float), battery_percentage (int).
    • Methods: reload(), set_name(name: str).

    Open/Close Sensors

    Retrieve sensors via get_open_close_sensors().

    • Attributes: is_open (bool), battery_percentage (int).
    • Methods: reload(), set_name(name: str).
    motions_sensors = dirigera_hub.get_motion_sensors()
    open_close_sensors = dirigera_hub.get_open_close_sensors()
  11. Control Air Purifiers

    main

    Manage air purifiers fetched via get_air_purifiers().

    Air Purifier Attributes

    • fan_mode: Current mode (uses FanModeEnum).
    • child_lock: Boolean lock state.
    • status_light: Boolean light state.
    • current_p_m25: Current particulate matter reading.
    • filter_lifetime, filter_elapsed_time: Filter health data.

    Air Purifier Methods

    • reload(): Refresh data.
    • set_name(name): Update name.
    • set_fan_mode(fan_mode): Change mode using FanModeEnum.
    • set_motor_state(motor_state): Set motor speed (0-50).
    • set_child_lock(child_lock): Toggle child lock.
    • set_status_light(light_state): Toggle status light.
    air_purifiers = dirigera_hub.get_air_purifiers()
    purifier = air_purifiers[0]
    purifier.set_fan_mode(fan_mode=FanModeEnum.AUTO)
    purifier.set_motor_state(motor_state=42)