zigbee.mqtt#

class platypush.plugins.zigbee.mqtt.ZigbeeMqttPlugin(*_, **__)[source]#

Bases: RunnablePlugin, MqttPlugin, DimmerEntityManager, EnumSwitchEntityManager, LightEntityManager, SensorEntityManager, SwitchEntityManager

This plugin allows you to interact with Zigbee devices over MQTT through any Zigbee sniffer and zigbee2mqtt.

In order to get started you’ll need:

  • A Zigbee USB adapter/sniffer (in this example I’ll use the CC2531.

  • A Zigbee debugger/emulator + downloader cable (only to flash the firmware).

Instructions:

  • Install cc-tool either from sources or from a package manager.

  • Connect the Zigbee to your PC/RaspberryPi in this way:

    USB -> CC debugger -> downloader cable -> CC2531 -> USB
    
  • The debugger and the adapter should be connected at the same time. If the later cc-tool command throws up an error, put the device in sync while connected by pressing the _Reset_ button on the debugger.

  • Check where the device is mapped. On Linux it will usually be /dev/ttyACM0.

  • Download the latest Z-Stack firmware to your device. Instructions for a CC2531 device:

    wget https://github.com/Koenkk/Z-Stack-firmware/raw/master                     /coordinator/Z-Stack_Home_1.2/bin/default/CC2531_DEFAULT_20201127.zip
    unzip CC2531_DEFAULT_20201127.zip
    [sudo] cc-tool -e -w CC2531ZNP-Prod.hex
    
  • You can disconnect your debugger and downloader cable once the firmware is flashed.

  • Install zigbee2mqtt. First install a node/npm environment, then either install zigbee2mqtt manually or through your package manager. NOTE: many API breaking changes have occurred on Zigbee2MQTT 1.17.0, therefore this integration will only be compatible with the version 1.17.0 of the service or higher versions. Manual instructions:

    # Clone zigbee2mqtt repository
    [sudo] git clone https://github.com/Koenkk/zigbee2mqtt.git /opt/zigbee2mqtt
    [sudo] chown -R pi:pi /opt/zigbee2mqtt  # Or whichever is your user
    
    # Install dependencies (as user "pi")
    cd /opt/zigbee2mqtt
    npm install
    
  • You need to have an MQTT broker running somewhere. If not, you can install

    Mosquitto through your package manager on any device in your network.

  • Edit the /opt/zigbee2mqtt/data/configuration.yaml file to match the configuration of your MQTT broker:

    # MQTT settings
    mqtt:
        # MQTT base topic for zigbee2mqtt MQTT messages
        base_topic: zigbee2mqtt
        # MQTT server URL
        server: 'mqtt://localhost'
        # MQTT server authentication, uncomment if required:
        # user: my_user
        # password: my_password
    
  • Also make sure that permit_join is set to True, in order to allow Zigbee devices to join the network while you’re configuring it. It’s equally important to set permit_join to False once you have configured your network, to prevent accidental/malignant joins from outer Zigbee devices.

  • Start the zigbee2mqtt daemon on your device (the official documentation also contains instructions on how to configure it as a systemd service:

    cd /opt/zigbee2mqtt
    npm start
    
  • If you have Zigbee devices that are paired to other bridges, unlink them or do a factory reset to pair them to your new bridge.

  • If it all goes fine, once the daemon is running and a new device is found you should see traces like this in the output of zigbee2mqtt:

    zigbee2mqtt:info  2019-11-09T12:19:56: Successfully interviewed '0x00158d0001dc126a', device has
    successfully been paired
    
  • You are now ready to use this integration.

Requires:

  • paho-mqtt (pip install paho-mqtt)

Triggers:

__init__(host: str = 'localhost', port: int = 1883, base_topic: str = 'zigbee2mqtt', timeout: int = 10, tls_certfile: str | None = None, tls_keyfile: str | None = None, tls_version: str | None = None, tls_ciphers: str | None = None, username: str | None = None, password: str | None = None, **kwargs)[source]#
Parameters:
  • host – Default MQTT broker where zigbee2mqtt publishes its messages (default: localhost).

  • port – Broker listen port (default: 1883).

  • base_topic – Topic prefix, as specified in /opt/zigbee2mqtt/data/configuration.yaml (default: ‘base_topic’).

  • timeout – If the command expects from a response, then this timeout value will be used (default: 60 seconds).

  • tls_cafile – If the connection requires TLS/SSL, specify the certificate authority file (default: None)

  • tls_certfile – If the connection requires TLS/SSL, specify the certificate file (default: None)

  • tls_keyfile – If the connection requires TLS/SSL, specify the key file (default: None)

  • tls_version – If the connection requires TLS/SSL, specify the minimum TLS supported version (default: None)

  • tls_ciphers – If the connection requires TLS/SSL, specify the supported ciphers (default: None)

  • username – If the connection requires user authentication, specify the username (default: None)

  • password – If the connection requires user authentication, specify the password (default: None)

bind_devices(source: str, target: str, **kwargs)[source]#

Bind two devices. Binding makes it possible that devices can directly control each other without the intervention of zigbee2mqtt or any home automation software. You may want to use this feature to bind for example an IKEA/Philips Hue dimmer switch to a light bulb, or a Zigbee remote to a thermostat. Read more on the zigbee2mqtt binding page.

Parameters:
  • source – Name of the source device. It can also be a group name, although the support is still experimental. You can also bind a specific device endpoint - for example MySensor/temperature.

  • target – Name of the target device. You can also bind a specific device endpoint - for example MyLight/state.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

device_ban(device: str, **kwargs)[source]#

Ban a device from the network.

Parameters:
  • device – Display name of the device.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

device_check_ota_updates(device: str, **kwargs) dict[source]#

Check if the specified device has any OTA updates available to install.

Parameters:
  • device – Address or friendly name of the device.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

Returns:

{
    "id": "<device ID>",
    "update_available": true,
    "status": "ok"
}

device_get(device: str, property: str | None = None, **kwargs) Dict[str, Any][source]#

Get the properties of a device. The returned keys vary depending on the device. For example, a light bulb may have the “state” and “brightness” properties, while an environment sensor may have the “temperature” and “humidity” properties, and so on.

Parameters:
  • device – Display name of the device.

  • property – Name of the property that should be retrieved (default: all).

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

Returns:

Key->value map of the device properties.

device_install_ota_updates(device: str, **kwargs)[source]#

Install OTA updates for a device if available.

Parameters:
  • device – Address or friendly name of the device.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

device_remove(device: str, force: bool = False, **kwargs)[source]#

Remove a device from the network.

Parameters:
  • device – Display name of the device.

  • force – Force the remove also if the removal wasn’t acknowledged by the device. Note: a forced remove only removes the entry from the internal database, but the device is likely to connect again when restarted unless it’s factory reset (default: False).

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

device_rename(name: str, device: str | None = None, **kwargs)[source]#

Rename a device on the network.

Parameters:
  • name – New name.

  • device – Current name of the device to rename. If no name is specified then the rename will affect the last device that joined the network.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

device_set(device: str, property: str | None = None, value: Any | None = None, values: Dict[str, Any] | None = None, **kwargs)[source]#

Set a properties on a device. The compatible properties vary depending on the device. For example, a light bulb may have the “state” and “brightness” properties, while an environment sensor may have the “temperature” and “humidity” properties, and so on.

Parameters:
  • device – Display name of the device.

  • property – Name of the property that should be set.

  • value – New value of the property.

  • values – If you want to set multiple values, then pass this mapping instead of property``+``value.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

device_set_option(device: str, option: str, value: Any, **kwargs)[source]#

Change the options of a device. Options can only be changed, not added or deleted.

Parameters:
  • device – Display name or IEEE address of the device.

  • option – Option name.

  • value – New value.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

device_whitelist(device: str, **kwargs)[source]#

Whitelist a device on the network. Note: once at least a device is whitelisted, all the other non-whitelisted devices will be removed from the network.

Parameters:
  • device – Display name of the device.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

devices(**kwargs) List[Dict[str, Any]][source]#

Get the list of devices registered to the service.

Parameters:

kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

Returns:

List of paired devices. Example output:

[
    {
        "date_code": "20190608",
        "friendly_name": "Coordinator",
        "ieee_address": "0x00123456789abcde",
        "network_address": 0,
        "supported": false,
        "type": "Coordinator",
        "interviewing": false,
        "interviewing_completed": true,
        "definition": null,
        "endpoints": {
            "13": {
                "bindings": [],
                "clusters": {
                    "input": ["genOta"],
                    "output": []
                },
                "output": []
            }
        }
    },

    {
        "date_code": "20180906",
        "friendly_name": "My Lightbulb",
        "ieee_address": "0x00123456789abcdf",
        "network_address": 52715,
        "power_source": "Mains (single phase)",
        "software_build_id": "5.127.1.26581",
        "model_id": "LCT001",
        "supported": true,
        "interviewing": false,
        "interviewing_completed": true,
        "type": "Router",
        "definition": {
            "description": "Hue white and color ambiance E26/E27/E14",
            "model": "9290012573A",
            "vendor": "Philips",
            "exposes": [
                {
                    "features": [
                        {
                            "access": 7,
                            "description": "On/off state of this light",
                            "name": "state",
                            "property": "state",
                            "type": "binary",
                            "value_off": "OFF",
                            "value_on": "ON",
                            "value_toggle": "TOGGLE"
                        },
                        {
                            "access": 7,
                            "description": "Brightness of this light",
                            "name": "brightness",
                            "property": "brightness",
                            "type": "numeric",
                            "value_max": 254,
                            "value_min": 0
                        },
                        {
                            "access": 7,
                            "description": "Color temperature of this light",
                            "name": "color_temp",
                            "property": "color_temp",
                            "type": "numeric",
                            "unit": "mired",
                            "value_max": 500,
                            "value_min": 150
                        },
                        {
                            "description": "Color of this light in the XY space",
                            "features": [
                                {
                                    "access": 7,
                                    "name": "x",
                                    "property": "x",
                                    "type": "numeric"
                                },
                                {
                                    "access": 7,
                                    "name": "y",
                                    "property": "y",
                                    "type": "numeric"
                                }
                            ],
                            "name": "color_xy",
                            "property": "color",
                            "type": "composite"
                        }
                    ],
                    "type": "light"
                },
                {
                    "access": 2,
                    "description": "Triggers an effect on the light",
                    "name": "effect",
                    "property": "effect",
                    "type": "enum",
                    "values": [
                        "blink",
                        "breathe",
                        "okay",
                        "channel_change",
                        "finish_effect",
                        "stop_effect"
                    ]
                },
                {
                    "access": 1,
                    "description": "Link quality (signal strength)",
                    "name": "linkquality",
                    "property": "linkquality",
                    "type": "numeric",
                    "unit": "lqi",
                    "value_max": 255,
                    "value_min": 0
                }
            ]
        },

        "endpoints": {
            "11": {
                "bindings": [],
                "clusters": {
                    "input": [
                        "genBasic",
                        "genIdentify",
                        "genGroups",
                        "genScenes",
                        "genOnOff",
                        "genLevelCtrl",
                        "touchlink",
                        "lightingColorCtrl",
                    ],
                    "output": [
                        "genOta"
                    ]
                },
                "configured_reportings": []
            },
            "242": {
                "bindings": [],
                "clusters": {
                    "input": [
                        "greenPower"
                    ],
                    "output": [
                        "greenPower"
                    ]
                },
                "configured_reportings": []
            }
        }
    }
]
devices_get(devices: List[str] | None = None, **kwargs) Dict[str, dict][source]#

Get the properties of the devices connected to the network.

Parameters:
  • devices – If set, then only the status of these devices (by friendly name) will be retrieved (default: retrieve all).

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

Returns:

Key->value map of the device properties:

{
    "Bulb": {
        "state": "ON",
        "brightness": 254
    },
    "Sensor": {
        "temperature": 22.5
    }
}

factory_reset(**kwargs)[source]#

Perform a factory reset of a device connected to the network, following the procedure required by the particular device (for instance, Hue bulbs require the Zigbee adapter to be close to the device while a button on the back of the bulb is pressed).

Parameters:

kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

group_add(name: str, id: int | None = None, **kwargs)[source]#

Add a new group.

Parameters:
  • name – Display name of the group.

  • id – Optional numeric ID (default: auto-generated).

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

group_add_device(group: str, device: str, **kwargs)[source]#

Add a device to a group.

Parameters:
  • group – Display name of the group.

  • device – Display name of the device to be added.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

group_get(group: str, property: str | None = None, **kwargs) dict[source]#

Get one or more properties of a group. The compatible properties vary depending on the devices on the group. For example, a light bulb may have the “state” (with values "ON" and "OFF") and “brightness” properties, while an environment sensor may have the “temperature” and “humidity” properties, and so on.

Parameters:
  • group – Display name of the group.

  • property – Name of the property to retrieve (default: all available properties)

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

group_remove(name: str, **kwargs)[source]#

Remove a group.

Parameters:
  • name – Display name of the group.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

group_remove_device(group: str, device: str | None = None, **kwargs)[source]#

Remove a device from a group.

Parameters:
  • group – Display name of the group.

  • device – Display name of the device to be removed. If none is specified then all the devices registered to the specified group will be removed.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

group_rename(name: str, group: str, **kwargs)[source]#

Rename a group.

Parameters:
  • name – New name.

  • group – Current name of the group to rename.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

group_set(group: str, property: str, value: Any, **kwargs)[source]#

Set a properties on a group. The compatible properties vary depending on the devices on the group. For example, a light bulb may have the “state” (with values "ON" and "OFF") and “brightness” properties, while an environment sensor may have the “temperature” and “humidity” properties, and so on.

Parameters:
  • group – Display name of the group.

  • property – Name of the property that should be set.

  • value – New value of the property.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

groups(**kwargs) List[dict][source]#

Get the groups registered on the device.

Parameters:

kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

info(**kwargs) dict[source]#

Get the information, configuration and state of the network.

Parameters:

kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

Returns:

Example:

{
    "state": "online",
    "commit": "07cdc9d",
    "config": {
        "advanced": {
            "adapter_concurrent": null,
            "adapter_delay": null,
            "availability_blacklist": [],
            "availability_blocklist": [],
            "availability_passlist": [],
            "availability_timeout": 0,
            "availability_whitelist": [],
            "cache_state": true,
            "cache_state_persistent": true,
            "cache_state_send_on_startup": true,
            "channel": 11,
            "elapsed": false,
            "ext_pan_id": [
                221,
                221,
                221,
                221,
                221,
                221,
                221,
                221
            ],
            "homeassistant_discovery_topic": "homeassistant",
            "homeassistant_legacy_triggers": true,
            "homeassistant_status_topic": "hass/status",
            "last_seen": "disable",
            "legacy_api": true,
            "log_directory": "/opt/zigbee2mqtt/data/log/%TIMESTAMP%",
            "log_file": "log.txt",
            "log_level": "debug",
            "log_output": [
                "console",
                "file"
            ],
            "log_rotation": true,
            "log_syslog": {},
            "pan_id": 6754,
            "report": false,
            "soft_reset_timeout": 0,
            "timestamp_format": "YYYY-MM-DD HH:mm:ss"
        },
        "ban": [],
        "blocklist": [],
        "device_options": {},
        "devices": {
            "0x00123456789abcdf": {
                "friendly_name": "My Lightbulb"
            }
        },
        "experimental": {
            "output": "json"
        },
        "external_converters": [],
        "groups": {},
        "homeassistant": false,
        "map_options": {
            "graphviz": {
                "colors": {
                    "fill": {
                        "coordinator": "#e04e5d",
                        "enddevice": "#fff8ce",
                        "router": "#4ea3e0"
                    },
                    "font": {
                        "coordinator": "#ffffff",
                        "enddevice": "#000000",
                        "router": "#ffffff"
                    },
                    "line": {
                        "active": "#009900",
                        "inactive": "#994444"
                    }
                }
            }
        },
        "mqtt": {
            "base_topic": "zigbee2mqtt",
            "force_disable_retain": false,
            "include_device_information": false,
            "server": "mqtt://localhost"
        },
        "passlist": [],
        "permit_join": true,
        "serial": {
            "disable_led": false,
            "port": "/dev/ttyUSB0"
        },
        "whitelist": []
    },
    "coordinator": {
        "meta": {
            "maintrel": 3,
            "majorrel": 2,
            "minorrel": 6,
            "product": 0,
            "revision": 20190608,
            "transportrev": 2
        },
        "type": "zStack12"
    },
    "log_level": "debug",
    "network": {
        "channel": 11,
        "extended_pan_id": "0xdddddddddddddddd",
        "pan_id": 6754
    },
    "permit_join": true,
    "version": "1.17.0"
}

log_level(level: str, **kwargs)[source]#

Change the log level at runtime. This change will not be persistent.

Parameters:
  • level – Possible values: ‘debug’, ‘info’, ‘warn’, ‘error’.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

main()[source]#

Implementation of the main loop of the plugin.

off(device, *_, **__)[source]#

Turn off/set to false a switch, a binary property or an option.

on(device, *_, **__)[source]#

Turn on/set to true a switch, a binary property or an option.

permit_join(permit: bool = True, timeout: float | None = None, **kwargs)[source]#

Enable/disable devices from joining the network. This is not persistent (will not be saved to configuration.yaml).

Parameters:
  • permit – Set to True to allow joins, False otherwise.

  • timeout – Allow/disallow joins only for this amount of time.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

set(entity: str, value: Any, attribute: str | None = None, **kwargs)[source]#

Set the value of an entity.

Parameters:
  • entity – The entity to set the value for. It’s usually the ID of the entity provided by the plugin.

  • value – The value to set the entity to.

set_lights(*_, lights, **kwargs)[source]#

Set the state for one or more Zigbee lights.

set_value(device: str, property: str | None = None, data=None, **kwargs)[source]#

Entity-compatible way of setting a value on a node.

Parameters:
  • device – Device friendly name, IEEE address or internal entity ID in <address>:<property> format.

  • property – Name of the property to set. If not specified here, it should be specified on device in <address>:<property> format.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).

status(*args, device: str | None = None, **kwargs)[source]#

Get the status of a device (by friendly name) or of all the connected devices (it wraps devices_get()).

Parameters:

device – Device friendly name (default: get all devices).

toggle(device, *_, **__)[source]#

Toggles the state of a switch, a binary property or an option.

transform_entities(entities: Collection[dict]) List[Entity][source]#

This method takes a list of entities in any (plugin-specific) format and converts them into a standardized collection of Entity objects. Since this method is called by publish_entities() before entity updates are published, you may usually want to extend it to pre-process the entities managed by your extension into the standard format before they are stored and published to all the consumers.

unbind_devices(source: str, target: str, **kwargs)[source]#

Un-bind two devices.

Parameters:
  • source – Name of the source device. You can also bind a specific device endpoint - for example MySensor/temperature.

  • target – Name of the target device. You can also bind a specific device endpoint - for example MyLight/state.

  • kwargs – Extra arguments to be passed to platypush.plugins.mqtt.MqttPlugin.publish`() (default: query the default configured device).