### Home Assistant Integration Setup Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/gateway-api.md Illustrates the initial setup flow for the Xiaomi Gateway 3 integration within Home Assistant. It involves creating a MultiGateway instance, setting up entities, and starting the gateway's services. ```python gw = MultiGateway(**entry.options) # host, token, key, etc. handle_add_entities(hass, entry, gw) # Create HA entities gw.start() # Start MQTT and device discovery ``` -------------------------------- ### Switch Turn On Service Call Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of how to call the switch.turn_on service. This is used for switches and relays. ```yaml service: switch.turn_on target: entity_id: switch.gateway_alarm_trigger data: {} ``` -------------------------------- ### Light Turn On Service Call Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of how to call the light.turn_on service with brightness, RGB color, and transition. Supports smart lights and LED strips. ```yaml service: light.turn_on target: entity_id: light.rgb_light data: brightness: 200 rgb_color: [255, 100, 50] transition: 1 ``` -------------------------------- ### MIoT Protocol Get Properties Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of getting properties for new devices, Mesh, and gateway using MIoT protocol format. ```json { "method": "get_properties", "params": [ { "did": "lumi.0x1234", "siid": 2, "piid": 1 } ] } ``` -------------------------------- ### Select Option Service Call Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of how to call the select.select_option service to choose an option from a dropdown. ```yaml service: select.select_option target: entity_id: select.light_mode data: option: "scene_1" ``` -------------------------------- ### start() Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/gateway-api.md Starts the gateway background task for connection and message handling. This method is typically called automatically by the Home Assistant integration. ```APIDOC ## start() ### Description Starts the gateway background task that establishes telnet connection, prepares the gateway, and handles MQTT messages. This method is typically called automatically by the Home Assistant integration. ### Method start ### Parameters - None ### Returns None ### Notes: - Creates an async task that runs continuously - If already started, calling again has no effect ### Example: ```python gw.start() ``` ``` -------------------------------- ### Button Press Service Call Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of how to call the button.press service to trigger an action button. ```yaml service: button.press target: entity_id: button.reset_device data: {} ``` -------------------------------- ### Patch Boot Info Command Example Source: https://github.com/alexxit/xiaomigateway3/wiki/Downgrade-Firmware An example command to patch the boot information in memory. This specific command modifies bytes related to firmware versioning. ```text eb A0000000 7C 91 00 00 E5 59 01 01 00 00 00 20 EC 04 C8 CF ``` -------------------------------- ### Device Specification Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/types.md An example of a device specification dictionary, including brand, name, market models, and converters. ```python device_spec = { # Model -> [Brand, Name, Market Models...] "lumi.sensor_motion.aq2": [ "Xiaomi", "Motion Sensor", "RTCGQ01LM", "RTCGQ11LM" ], # Converters list "spec": [ BinaryConv("motion", "binary_sensor", mi="5.7.85"), MathConv("illuminance", "sensor", mi="5.7.65", multiply=1.0), MathConv("battery", "sensor", mi="5.8.95"), ], # Optional: time-to-live before marking offline "ttl": 180 # seconds } ``` -------------------------------- ### MultiGateway Constructor Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/gateway-api.md Instantiate the MultiGateway class with essential parameters like host, token, and key. ```python gw = MultiGateway( host="192.168.1.100", token="abc123def456...", key="1234567890abcdef" ) ``` -------------------------------- ### Asynchronous Command Flow Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Demonstrates sending a command and setting up a listener for device updates. This covers the asynchronous command response handling. ```python # Send command await gw.send(device, { "cmd": "write", "did": device.did, "params": [{"res_name": "power", "value": 1}] }) # Device listener receives update def on_update(data): if "power" in data: print(f"Power state: {data['power']}") device.add_listener(on_update) ``` -------------------------------- ### Integration Setup Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/INDEX.md Provides the entry points for setting up the Xiaomi Gateway 3 integration within Home Assistant. ```APIDOC ## Integration Setup ### Description Provides the entry points for setting up the Xiaomi Gateway 3 integration within Home Assistant. ### Code ```python from custom_components.xiaomi_gateway3 import async_setup, async_setup_entry ``` ``` -------------------------------- ### Configuration Reference Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/INDEX.md Information on integration configuration options, YAML setup, and device matching. ```APIDOC ## Configuration This section details the configuration options for the integration. ### Covers - Integration entry options (host, token, key, stats, debug). - YAML configuration in `configuration.yaml`. - Device-specific configuration and matching (IEEE, DID, MAC, model). - Device options (name, model, entities, timeouts). - Logging configuration. - Advanced features like attribute templates and multispec. - Cloud integration and server selection. - Regional restrictions and cloud device types. ``` -------------------------------- ### Cover Set Position Service Call Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of how to call the cover.set_cover_position service to set the position of blinds or covers. ```yaml service: cover.set_cover_position target: entity_id: cover.blind data: position: 50 ``` -------------------------------- ### Example Configuration Entry Options Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/configuration.md Illustrates the structure of options stored for a gateway integration entry. Ensure all required fields like 'host' and 'token' are provided. ```python { "host": "192.168.1.100", "token": "abc123def456789abc123def456789ab", "key": "1234567890abcdef", "stats": "binary_sensor", "debug": ["true", "mqtt"] } ``` -------------------------------- ### Motion Sensor Configuration Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Example of configuring a motion sensor with a 3-minute occupancy timeout. ```python device.extra = { "occupancy_timeout": 180, ... } ``` -------------------------------- ### Number Set Value Service Call Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of how to call the number.set_value service to set a numeric parameter like thresholds or timeouts. ```yaml service: number.set_value target: entity_id: number.brightness_threshold data: value: 100 ``` -------------------------------- ### Entity Identity Examples Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/entity-api.md Illustrates the expected formats for Home Assistant entity IDs, including custom and default configurations. ```python "binary_sensor.00158d0001d82999_motion" ``` ```python "sensor.kitchen_motion_battery" ``` ```python "light.living_room_bulb_brightness" ``` -------------------------------- ### Example Event Listener for Device Addition Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/gateway-api.md Demonstrates how to register a callback function to handle the 'add_device' event, printing a message when a new device is added. ```python def on_device_added(device): print(f"Device {device.human_name} added") gw.add_event_listener("add_device", on_device_added) ``` -------------------------------- ### Gateway Creation Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/INDEX.md Demonstrates how to create and start a `MultiGateway` instance, which represents the Xiaomi Gateway hub. ```APIDOC ## Gateway Creation ### Description Demonstrates how to create and start a `MultiGateway` instance, which represents the Xiaomi Gateway hub. ### Code ```python from custom_components.xiaomi_gateway3.core.gateway import MultiGateway gw = MultiGateway(host="192.168.1.100", token="...", key="...") gw.start() ``` ``` -------------------------------- ### on_init Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/entity-api.md Initialization hook for subclasses, called during __init__() for subclass setup. ```APIDOC ## on_init() ### Description Subclass initialization hook. Called during __init__() for subclass setup. ### Method Signature ```python def on_init(self) ``` ### Parameters N/A ### Request Example ```python class LightEntity(XEntity): def on_init(self): self.listen_attrs.add("brightness") self.listen_attrs.add("color") self._attr_supported_color_modes = {"rgb", "xy"} ``` ### Response N/A ``` -------------------------------- ### Setup Entity Description Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/entity-api.md Configures the Home Assistant entity description based on converter configuration, domain type, and attribute naming conventions. ```python setup_entity_description(entity: XEntity, conv: BaseConv) ``` -------------------------------- ### Matter Protocol Set Properties (v3) Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of setting properties for Matter protocol devices using v3 format. ```json { "method": "set_properties_v3", "params": [ { "did": "M.1234", "iid": 257, "value": 1 } ] } ``` -------------------------------- ### Get Human-Readable Model Description Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Get a descriptive string for the device's model, including type and market model if available. ```python @property def human_model(self) -> str ``` -------------------------------- ### BLE Lock Automations Example Source: https://github.com/alexxit/xiaomigateway3/wiki/Handle-BLE-Locks Examples of Home Assistant automations triggered by BLE lock events. These snippets demonstrate how to monitor doorbell rings, lock errors, and lock opening events. ```yaml automation: - alias: Doorbell trigger: platform: state entity_id: sensor.ble_1010274797_action to: door condition: condition: template value_template: "{{ trigger.to_state.attributes['action_id'] == 3 }}" action: service: persistent_notification.create data_template: title: Doorbell message: The doorbell is ringing - alias: Lock Error trigger: platform: state entity_id: sensor.ble_1010274797_action to: lock condition: condition: template value_template: "{{ trigger.to_state.attributes['error'] }}" action: service: persistent_notification.create data_template: title: Lock ERROR message: "{{ trigger.to_state.attributes['error'] }}" - alias: Open lock trigger: platform: state entity_id: sensor.ble_1010274797_action to: lock condition: condition: template value_template: "{{ trigger.to_state.attributes['action_id'] == 0 }}" action: service: persistent_notification.create data_template: title: Lock is open message: | Opening method: {{ trigger.to_state.attributes['method'] }} User ID: {{ trigger.to_state.attributes['key_id'] }} ``` -------------------------------- ### Device Automation Trigger Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of a Home Assistant automation triggered by a device action, specifically a double press on button 1 of a multi-button device. ```yaml automation: - id: toggle_lights_with_button alias: Toggle lights with button trigger: platform: device device_id: "abc123def456" domain: xiaomi_gateway3 type: action state: button_1_double action: service: light.toggle target: entity_id: light.living_room ``` -------------------------------- ### Example Debug and Error Logging Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/gateway-api.md Shows how to log debug messages with contextual information like device model, and how to log errors with exception details. ```python gw.debug("Device initialized", device=device, model=device.model) gw.error("MQTT connection failed", exc_info=e) ``` -------------------------------- ### Gateway Alarm Trigger Service Call Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of how to call the alarm_control_panel.alarm_trigger service to trigger the gateway's buzzer with specific duration and volume. ```yaml service: alarm_control_panel.alarm_trigger target: entity_id: alarm_control_panel.gateway_alarm data: code: "10,3" # duration (seconds), volume (1-3) ``` -------------------------------- ### Extra State Attributes Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/entity-api.md Provides examples of extra attributes that can be included in the entity's state, such as last seen time, battery voltage, link quality, and parent device. ```python _attr_extra_state_attributes: dict ``` ```python { "last_seen": "2m30s", "battery_voltage": 3.1, "link_quality": 150, "parent": "0x1234" } ``` -------------------------------- ### MIoT Protocol Action Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of performing an action for new devices, Mesh, and gateway using MIoT protocol format. ```json { "method": "action", "params": { "did": "lumi.0x1234", "siid": 3, "aiid": 1, "in": [param1, param2] } } ``` -------------------------------- ### Lumi Protocol Write Command Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of a write command in Lumi protocol format for old Zigbee devices. ```json { "cmd": "write", "did": "lumi.0x1234", "params": [ { "res_name": "power", "value": 1 } ] } ``` -------------------------------- ### MIoT Protocol Set Properties Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of setting properties for new devices, Mesh, and gateway using MIoT protocol format. ```json { "method": "set_properties", "params": [ { "did": "lumi.0x1234", "siid": 2, "piid": 1, "value": 1 } ] } ``` -------------------------------- ### Binary Sensor Inverted Logic Configuration Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Example of configuring a binary sensor to use inverted logic. ```python device.extra = { "invert_state": True, ... } ``` -------------------------------- ### Device Matching Examples Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/configuration.md Demonstrates various methods for identifying and matching devices within the YAML configuration. Use Zigbee IEEE addresses, Device IDs, MAC addresses, or device models. ```yaml "0x00158d0001d82999" # Full IEEE with 0x prefix "00:15:8d:00:01:d8:29:99" # IEEE without 0x prefix ``` ```yaml "lumi.0x1234" # Zigbee device ID "blt.3.5678" # BLE device ID "group.123" # Mesh group ID ``` ```yaml "54:ef:44:xx:xx:xx" # MAC address ``` ```yaml "lumi.sensor_motion.aq2" # Zigbee model "4741" # BLE model (numeric) ``` -------------------------------- ### Lumi Protocol Read Command Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of a read command in Lumi protocol format for old Zigbee devices. ```json { "cmd": "read", "did": "lumi.0x1234", "params": [ { "res_name": "power" } ] } ``` -------------------------------- ### Example Device State and Attributes Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Illustrates a typical device state with common attributes like device information, gateway details, last seen time, and message counts. ```yaml state: "25.5" attributes: device: name: "Motion Sensor" model: "lumi.sensor_motion.aq2" available: true gateway: name: "Gateway" host: "192.168.1.100" last_seen: "30s" msg_received: 1024 ``` -------------------------------- ### Integration Setup API Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/INDEX.md Python code for setting up the Xiaomi Gateway 3 integration asynchronously. This is typically used in Home Assistant's custom component structure. ```python from custom_components.xiaomi_gateway3 import async_setup, async_setup_entry ``` -------------------------------- ### Gateway Creation API Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/INDEX.md Python code to instantiate and start the `MultiGateway` object. Requires host, token, and key for initialization. ```python from custom_components.xiaomi_gateway3.core.gateway import MultiGateway gw = MultiGateway(host="192.168.1.100", token="...", key="...") gw.start() ``` -------------------------------- ### Device Specification Format Example Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/converters.md Defines a list of devices with their associated converters. Each device entry includes a unique identifier and a 'spec' list detailing how to convert specific MI properties to Home Assistant entities. ```python DEVICES = [ { "lumi.sensor_motion.aq2": ["Xiaomi", "Motion Sensor", "RTCGQ01LM"], "spec": [ BinaryConv("motion", "binary_sensor", mi="5.7.85"), MathConv("illuminance", "sensor", mi="5.7.65", multiply=1.0), MathConv("battery", "sensor", mi="5.8.95"), ] } ] ``` -------------------------------- ### Start MultiGateway Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/gateway-api.md Initiates the gateway's background task for connection and message handling. This is typically called automatically by the Home Assistant integration. ```python gw.start() ``` -------------------------------- ### Internal Gateway Event Listener Registration Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of how to register an event listener for the EVENT_ADD_DEVICE event within the integration's core. ```python def on_device_added(device: XDevice): pass gateway.add_event_listener("add_device", on_device_added) ``` -------------------------------- ### Subclass Initialization Hook Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/entity-api.md This hook is called during __init__() for subclass setup. Use it to configure listenable attributes and supported modes. ```python def on_init(self) ``` ```python class LightEntity(XEntity): def on_init(self): self.listen_attrs.add("brightness") self.listen_attrs.add("color") self._attr_supported_color_modes = {"rgb", "xy"} ``` -------------------------------- ### Custom Model and Entity Domain Overrides Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Example of overriding a device's model and specifying custom entity domains for attributes. ```python device.extra = { "model": "lumi.plug", # Use plug converter "entities": { "power": "light", # Create light instead of switch "temperature": "sensor" }, ... } ``` -------------------------------- ### Custom Entity Class Registration Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/entity-api.md Allows registering custom entity subclasses for specific domains or attributes. This example shows how to use a custom light entity or a specific brightness-controlled light entity. ```python XEntity.NEW["light"] = CustomLightEntity # Use custom light entity class ``` ```python XEntity.NEW["light.brightness"] = BrightnessControlledLight # For brightness attribute ``` -------------------------------- ### Get Human-Readable Device Name Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Obtain a user-friendly name for the device, prioritizing YAML configuration, then cloud name, market name, or a default fallback. ```python @property def human_name(self) -> str ``` -------------------------------- ### Handle Button Actions Automation Source: https://github.com/alexxit/xiaomigateway3/blob/master/README.md An example automation that triggers when a specific button action is detected. Ensure to update the entity_id and the 'to' state to match your button's configuration. ```yaml automation: - alias: Turn off all lights trigger: - platform: state entity_id: sensor.0x158d0002fa99fd_action # change to your button to: button_1_single # change to your button state action: - service: light.turn_off entity_id: all mode: single ``` -------------------------------- ### Simple Relay Converter Source: https://github.com/alexxit/xiaomigateway3/wiki/Converters Example of a simple on/off converter for a Zigbee relay device (Sonoff Mini). Uses ZOnOffConv for basic switch functionality. ```python from custom_components.xiaomi_gateway3.core.devices import * DEVICES = [{ "01MINIZB": ["Sonoff", "Mini", "ZBMINI"], "spec": [ZOnOffConv("switch", "switch")] }] + DEVICES ``` -------------------------------- ### init_device(model: str | int | None, **kwargs) -> XDevice Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/gateway-api.md Create and register a new device. ```APIDOC ## `init_device(model: str | int | None, **kwargs) -> XDevice` ### Description Create and register a new device. ### Parameters #### Path Parameters - **model** (str or int) - Required - Device model (string for Zigbee, int for BLE/Mesh) - **kwargs** (dict) - Optional - Device extra attributes (type, did, mac, ieee, etc.) ### Returns: Initialized `XDevice` object ### Example: ```python device = gw.init_device( "lumi.sensor_motion.aq2", type="zigbee", did="lumi.0x1234", ieee="00:11:22:33:44:55:66:77" ) ``` ``` -------------------------------- ### Enter Bootloader Commands Source: https://github.com/alexxit/xiaomigateway3/wiki/Downgrade-Firmware After holding 'u' and powering on the gateway, enter these commands in the UART console to prepare for firmware manipulation. ```text dbgmsg 9 ri 0 1 1 ``` -------------------------------- ### Custom Device Configuration Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/modules-overview.md Configure custom device names and entities within the xiaomi_gateway3 configuration. This example sets a custom name and maps an attribute 'attr' to the 'domain' entity. ```yaml xiaomi_gateway3: devices: "device_id": name: "Custom Name" entities: attr: domain ``` -------------------------------- ### prepare_gateway() Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/gateway-api.md Initializes the gateway and loads all connected devices from different protocols. This method performs several checks and loads device information. ```APIDOC ## prepare_gateway() ### Description Initializes gateway and loads all connected devices from different protocols. ### Method async prepare_gateway ### Parameters - None ### Returns: - `True` if gateway prepared successfully - `False` if preparation failed (connection issue, second Hass detected, etc.) ### Operations: 1. Checks for concurrent Hass instances via telnet 2. Reads gateway information (model, firmware) 3. Loads Zigbee devices (Lumi protocol) 4. Loads Silabs devices (Zigbee via Silabs protocol) 5. Loads OpenMiio gateway info 6. Loads BLE/Mesh/Matter devices if supported by model 7. Registers MQTT event listeners ### Supported Gateway Models: - `lumi.gateway.mgl03` - Xiaomi Multimode Gateway (all fw versions) - `lumi.gateway.aqcn02` - Aqara Hub E1 CN - `lumi.gateway.aqcn03` - Aqara Hub E1 EU - `lumi.gateway.mcn001` - Xiaomi Multimode Gateway 2 CN - `lumi.gateway.mgl001` - Xiaomi Multimode Gateway 2 EU ### Feature Support by Model: - BLE/Mesh: `mgl03`, `mcn001`, `mgl001` - Matter: `mgl001` with fw >= 1.0.7_0019 ``` -------------------------------- ### Initialize and Register a New Device Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/gateway-api.md Creates and registers a new device with the gateway. Requires the device model and optional extra attributes. ```python def init_device(self, model: str | int | None, **kwargs) -> XDevice ``` ```python device = gw.init_device( "lumi.sensor_motion.aq2", type="zigbee", did="lumi.0x1234", ieee="00:11:22:33:44:55:66:77" ) ``` -------------------------------- ### Get XDevice DID Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Retrieve the device ID (DID) for an XDevice. The format is specific to the device type. ```python @cached_property def did(self) -> str ``` -------------------------------- ### XDevice.nwk Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Gets the Zigbee network address for Zigbee devices. For non-Zigbee devices, it returns '0x0000'. ```APIDOC ## XDevice.nwk ### Description Gets the Zigbee network address for Zigbee devices. For non-Zigbee devices, it returns '0x0000'. ### Method nwk ### Endpoint N/A (Property) ### Parameters None ### Request Example ```python print(device.nwk) ``` ### Response #### Success Response (200) * **nwk** (str) - The Zigbee network address in "0xXXXX" format, or "0x0000" for non-Zigbee devices. #### Response Example ```json "0x5678" ``` ``` -------------------------------- ### Get XDevice Type Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Retrieve the classification type of the XDevice (e.g., 'gateway', 'zigbee', 'ble'). ```python @cached_property def type(self) -> str ``` -------------------------------- ### Gateway of Last Report Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Identifies the gateway that received the last report, relevant for multi-gateway setups. ```python last_report_gw: Optional["XGateway"] ``` -------------------------------- ### Enable Flash and Read Boot Info Source: https://github.com/alexxit/xiaomigateway3/wiki/Downgrade-Firmware These commands enable flash access and read the current boot information from NAND memory into the gateway's RAM. ```text snwbi snwbrecc a0000000 140 800 ``` -------------------------------- ### XDevice.miot_model Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Gets the model string suitable for Xiaomi MIoT cloud queries. Returns None if not available. ```APIDOC ## XDevice.miot_model ### Description Gets the model string suitable for Xiaomi MIoT cloud queries. Returns None if not available. ### Method miot_model ### Endpoint N/A (Property) ### Parameters None ### Request Example ```python print(device.miot_model) ``` ### Response #### Success Response (200) * **miot_model** (str | None) - The MIoT model string, or None. #### Response Example ```json "lumi.sensor_motion.aq2" ``` ``` -------------------------------- ### XDevice.did Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Gets the Device ID (DID), also known as MID. The format of the DID varies depending on the device type. ```APIDOC ## XDevice.did ### Description Gets the Device ID (DID), also known as MID. The format of the DID varies depending on the device type. ### Method did ### Endpoint N/A (Property) ### Parameters None ### Request Example ```python print(device.did) ``` ### Response #### Success Response (200) * **did** (str) - The device ID. **Formats by Type:** - GATEWAY: Numeric string (e.g., "0", "1") - ZIGBEE: "lumi.xxxx" format (e.g., "lumi.0x1234") - BLE: "blt.x.xxxx" or numeric string (device-specific) - MESH: Numeric string (e.g., "12345") - GROUP: "group.xxxx" (e.g., "group.269") - MATTER: "M.xxxx" (e.g., "M.1234") #### Response Example ```json "lumi.0x1234" ``` ``` -------------------------------- ### Get Zigbee IEEE Address Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Retrieve the Zigbee IEEE address for Zigbee devices in the standard format. ```python @cached_property def ieee(self) -> str ``` -------------------------------- ### Get XDevice Model Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Access the immutable model identifier of the XDevice, set during its initialization. This can be a string or an integer. ```python model: str | int ``` -------------------------------- ### Get XDevice Cloud DID Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Retrieve the cloud-assigned device ID (cloud_did). For newer Zigbee devices, this will be a numeric ID. ```python @cached_property def cloud_did(self) -> str | None ``` -------------------------------- ### Instantiate XDevice for Zigbee Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Create an XDevice instance for a Zigbee device, providing its model, type, and unique identifiers. ```python device = XDevice( "lumi.sensor_motion.aq2", type="zigbee", did="lumi.0x1234", ieee="00:11:22:33:44:55:66:77", nwk="0x5678" ) ``` -------------------------------- ### Sending Commands Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/INDEX.md Illustrates how to send commands to a specific device through the gateway instance. ```APIDOC ## Sending Commands ### Description Illustrates how to send commands to a specific device through the gateway instance. ### Code ```python await gw.send(device, {"cmd": "write", "did": device.did, ...}) ``` ``` -------------------------------- ### Loading External Converters Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/converters.md Demonstrates how to load external converter modules from the 'xiaomi_gateway3' Python package. This allows for extending device support without modifying the core integration code. ```python try: from xiaomi_gateway3 import DEVICES # loading external converters except ModuleNotFoundError: pass ``` -------------------------------- ### XDevice Constructor Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Initializes an XDevice object. It requires the device model and can accept additional keyword arguments for device attributes. ```APIDOC ## XDevice Constructor ### Description Initializes an XDevice object. It requires the device model and can accept additional keyword arguments for device attributes. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **model** (str | int) - Required - Device model (string for Zigbee devices like "lumi.sensor_motion.aq2", int for BLE/Mesh devices) * **kwargs** (dict) - Optional - Device extra attributes (type, did, mac, ieee, fw_ver, etc.) ### Request Example ```python # Zigbee device device = XDevice( "lumi.sensor_motion.aq2", type="zigbee", did="lumi.0x1234", ieee="00:11:22:33:44:55:66:77", nwk="0x5678" ) # BLE device device = XDevice( 4741, # pdid/model number type="ble", did="blt.3.xxx", mac="4a:5b:6c:7d:8e:9f" ) ``` ### Response None #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Display Boot Info Source: https://github.com/alexxit/xiaomigateway3/wiki/Downgrade-Firmware Displays the boot information currently held in memory. This output is crucial for identifying and patching boot parameters. ```text db a0000000 40 ``` -------------------------------- ### XDevice.uid Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Gets the universal unique identifier for the device, used by Home Assistant. The format varies based on the device type. ```APIDOC ## XDevice.uid ### Description Gets the universal unique identifier for the device, used by Home Assistant. The format varies based on the device type. ### Method uid ### Endpoint N/A (Property) ### Parameters None ### Request Example ```python print(device.uid) ``` ### Response #### Success Response (200) * **uid** (str) - The unique identifier for the device. **Formats by Type:** - GATEWAY/BLE/MESH: MAC address without colons (e.g., "54ef44xxxxx") - ZIGBEE: "0x" + IEEE address without colons (e.g., "0x00158d0001d82999") - GROUP: Group ID (e.g., "269") - MATTER: Matter device ID (e.g., "1234") #### Response Example ```json "0x00158d0001d82999" ``` ``` -------------------------------- ### Create Sensor from Binary Attribute Configuration Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/INDEX.md YAML configuration to create specific Home Assistant entities (e.g., sensor, binary_sensor) from device attributes. This allows mapping raw device data to usable entities. ```yaml xiaomi_gateway3: devices: "lumi.sensor_motion.aq2": entities: occupancy: binary_sensor battery: sensor ``` -------------------------------- ### Instantiate XDevice for BLE Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Create an XDevice instance for a Bluetooth Low Energy (BLE) device, using its numeric model ID and other attributes. ```python device = XDevice( 4741, # pdid/model number type="ble", did="blt.3.xxx", mac="4a:5b:6c:7d:8e:9f" ) ``` -------------------------------- ### Enable Telnet Service via miio Client Source: https://github.com/alexxit/xiaomigateway3/wiki/Decode-Telnet-Password Use this command with the miio client to enable the Telnet service on the gateway. Ensure you replace the IP address, token, and other parameters with your gateway's specific details. ```bash php miio-cli.php --ip 192.168.1.123 --token 7766634c72хххххххх50743165 --sendcmd '{"id":0,"method":"enable_telnet_service", "params":[]}' ``` -------------------------------- ### Silabs Zigbee Send Cluster Command Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/services-and-events.md Example of sending a cluster command for Zigbee devices via Silabs chip (EFR32). ```json { "commands": [ { "endpoint": 1, "cluster": "0x0006", "command": "toggle" } ] } ``` -------------------------------- ### Custom Attributes Template Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/modules-overview.md Define a Jinja2 template for custom attributes in the xiaomi_gateway3 configuration. This example shows how to use a 'custom' attribute. ```yaml xiaomi_gateway3: attributes_template: | {% if attr == 'custom' %} {{ custom_attributes }} {% endif %} ``` -------------------------------- ### Get MIoT Model String Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Retrieve a model string formatted for Xiaomi MIoT cloud queries. Returns None if not available. ```python @cached_property def miot_model(self) -> str | None ``` -------------------------------- ### YAML Device Configuration Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Configure devices in Home Assistant's YAML file, allowing overrides for names, models, and entity domains based on unique identifiers like IEEE address. ```yaml xiaomi_gateway3: devices: "0x00158d0001d82999": # Match by IEEE (Zigbee) name: "My Motion Sensor" model: "lumi.sensor_motion.aq2" # Override device model entities: motion: binary_sensor # Change entity domain battery: sensor # Create sensor from attribute ``` -------------------------------- ### Converter Entity Description Extension Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/types.md Example of a converter with extended entity configuration, specifying attributes like domain, icon, and polling behavior. ```python converter = BaseConv( attr="brightness", domain="light", mi="2.p.1", entity={ "feature": "brightness", "class": "data", "icon": "mdi:brightness", "poll": False, "lazy": False, "entity_category": "config" } ) ``` -------------------------------- ### Device Option: entity_name Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/configuration.md Example of customizing the entity ID pattern for a device. This allows for more descriptive and consistent naming of entities in Home Assistant. ```yaml devices: "0x00158d0001d82999": entity_name: "kitchen_motion" # entity_id becomes binary_sensor.kitchen_motion_motion ``` -------------------------------- ### Device Option: name Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/configuration.md Example of overriding the default device name displayed in Home Assistant. This is useful for distinguishing multiple devices of the same type. ```yaml devices: "0x00158d0001d82999": name: "Kitchen Motion Sensor" ``` -------------------------------- ### MultiGateway Constructor Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/gateway-api.md Initializes the MultiGateway class with essential connection and authentication parameters. ```APIDOC ## MultiGateway Constructor ### Description Initializes the MultiGateway class with essential connection and authentication parameters. ### Method __init__ ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **host** (str) - Required - Gateway IP address on local network - **token** (str) - Required - Mi Home device token for gateway authentication - **key** (str) - Optional - Gateway secret key (required for fw 1.5.5+) - **stats** (bool|str) - Optional - Enable statistics sensors: False (disabled), True (sensor domain), "binary_sensor" - **debug** (list[str]) - Optional - Debug logging modes: "true" (basic), "mqtt", "zigbee" ### Request Example ```python gw = MultiGateway( host="192.168.1.100", token="abc123def456...", key="1234567890abcdef" ) ``` ### Response - None #### Success Response (200) - None #### Response Example - None ``` -------------------------------- ### Set Default Light Transition Time Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/configuration.md Configures the default transition time in seconds for light brightness and color changes. A value of 5 corresponds to a 0.5-second transition. ```yaml devices: "86bd7fffe0000000": default_transition: 5 # 0.5 second transition ``` -------------------------------- ### Get Entity State Method Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/entity-api.md Retrieves entity state attributes for persistence across restarts. The default implementation returns an empty dictionary. ```python def get_state(self) -> dict ``` ```python class PersistentEntity(XEntity): def get_state(self) -> dict: return { "last_color": self._attr_state, "brightness": self._attr_brightness, } ``` -------------------------------- ### Get Zigbee Network Address (nwk) Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/device-api.md Retrieve the Zigbee network address (nwk) for Zigbee devices. Returns '0x0000' for non-Zigbee devices. ```python @cached_property def nwk(self) -> str ``` -------------------------------- ### enable_telnet() Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/gateway-api.md Enables telnet on the gateway using the miio protocol, providing remote shell access. Requires a valid token and network connectivity. ```APIDOC ## enable_telnet() ### Description Enables telnet on gateway using miio protocol for remote shell access. ### Method async enable_telnet ### Parameters - None ### Returns - `True` if telnet was successfully enabled - `False` if token is missing or operation failed ### Requirements: - Valid token from Mi Home app - Gateway must be online - Network connectivity to gateway ### Example: ```python success = await gw.enable_telnet() if success: # Telnet is now available on port 23 pass ``` ``` -------------------------------- ### Entity Configuration for Converters Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/converters.md Shows extended entity configuration options for converters, including device class, icon override, and polling behavior. These options allow fine-tuning how entities are represented and updated in Home Assistant. ```python entity={ "class": "motion", # Device class for binary_sensor "icon": "mdi:motion", # Icon override "poll": True, # Require polling "lazy": True, # Create entity only on first data } ``` -------------------------------- ### XEntity Constructor Signature Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/entity-api.md The constructor for the XEntity class takes a device reference and a converter object. It initializes entity properties and sets up device information for Home Assistant. ```python def __init__(self, device: "XDevice", conv: "BaseConv") ``` -------------------------------- ### Migrate from Legacy YAML to New Format Source: https://github.com/alexxit/xiaomigateway3/blob/master/_autodocs/configuration.md Shows the difference between the old (v3) and new (v4) YAML configuration formats for devices. The integration handles unique_id migration automatically. ```yaml xiaomi_gateway3: devices: - did: "lumi.xxx" name: "My Device" ``` ```yaml xiaomi_gateway3: devices: "lumi.xxx": name: "My Device" ```