zigbee-herdsman

repository·master·Indexed 20 days ago

https://github.com/koenkk/zigbee-herdsman

An open source Zigbee gateway solution built on Node.js. It provides the low-level core Zigbee communication logic used by ecosystem projects such as Zigbee2MQTT and ioBroker. The library includes a Controller class for network management, EZSP driver utilities for payload serialization, and support for Ember network parameters, security states, and OTA firmware updates.

Tokens
25.2K
Snippets
57
Records
98
Agent score
69%

What's inside zigbee-herdsman

  1. Overview of zigbee-herdsman

    master
    zigbee-herdsman is an open source Zigbee gateway solution with a Node.js JavaScript runtime back-end. It serves as a low-level core for Zigbee communication and is used as a foundational module by other projects like Zigbee2MQTT and ioBroker.
  2. Understand the TLV (Type-Length-Value) system

    master

    Zigbee uses a TLV encoding scheme for various responses. A Tlv object consists of a tagId (0-63 for Local, 64-255 for Global), a length (which encodes the number of bytes in the value field plus an offset), and the actual tlv data payload.

    • Global TLVs: Can be added multiple times to the same frame.
    • Local TLVs: Specific to certain command/response contexts (e.g., BeaconSurveyConfigurationTLV, PotentialParentsTLV).
    export type Tlv = {
        tagId: number;
        length: number;
        tlv: ManufacturerSpecificGlobalTLV | SupportedKeyNegotiationMethodsGlobalTLV | ... | LocalTLVType;
    };
    
    export type TLVs = {
        tlvs: Tlv[];
    };
  3. Understand MAC Capability Flags

    master

    The MACCapabilityFlags type represents the bitmask of a device's hardware and operational capabilities. It defines whether a device can act as a coordinator, its function type (FFD vs RFD), power source status, and security capabilities.

    export type MACCapabilityFlags = {
        alternatePANCoordinator: number;
        deviceType: number;
        powerSource: number;
        rxOnWhenIdle: number;
        reserved1: number;
        reserved2: number;
        securityCapability: number;
        allocateAddress: number;
    };
  4. Understand Server Mask capabilities

    master

    The ServerMask type indicates the roles and specification compliance of a Zigbee stack. It identifies if a device acts as a Primary or Backup Trust Center, a Network Manager, and specifies the stackComplianceRevision (e.g., a value of 23 indicates compliance with Zigbee Pro Core Revision 23).

    export type ServerMask = {
        primaryTrustCenter: number;
        backupTrustCenter: number;
        deprecated1: number;
        deprecated2: number;
        deprecated3: number;
        deprecated4: number;
        networkManager: number;
        reserved1: number;
        reserved2: number;
        stackComplianceRevision: number;
    };
  5. Work with ZCL Cluster types and payloads

    master

    The library provides several utility types to programmatically access cluster definitions, attributes, and commands based on a cluster ID or name. This is useful when building generic drivers or handling dynamic ZCL messages.

    • TClusterAttributeKeys<Cl>: Gets valid attribute keys for a cluster.
    • TClusterAttributes<Cl>: Gets the attribute definitions for a cluster.
    • TClusterCommandKeys<Cl>: Gets valid command keys for a cluster.
    • TClusterCommandPayload<Cl, Co>: Gets the payload type for a specific command Co in cluster Cl.
    • TClusterPayload<Cl, Co>: A helper that resolves the payload type, whether it's a command or a command response.
    export type TClusterAttributeKeys<Cl extends number | string> = Cl extends keyof TClusters
        ? (keyof TClusters[Cl]["attributes"])[]
        : (string | number)[];
    
    export type TClusterCommandPayload<Cl extends number | string, Co extends number | string> = Cl extends keyof TClusters
        ? Co extends keyof TClusters[Cl]["commands"]
            ? TClusters[Cl]["commands"][Co]
            : Co extends keyof TClusters[Cl]["commandResponses"]
              ? TClusters[Cl]["commandResponses"][Co]
              : never
        : never;
  6. Understand Ember Zigbee network and ZLL structures

    master

    The Ember adapter provides specific types for managing standard Zigbee networks and Zigbee Light Link (ZLL) networks.

    Standard Zigbee Network

    EmberZigbeeNetwork defines the core network state:

    • panId: 16-bit PAN ID.
    • channel: Radio channel.
    • allowingJoin: Boolean indicating if joining is permitted.
    • extendedPanId: Extended PAN ID.
    • stackProfile: Stack profile identifier.
    • nwkUpdateId: Network update ID.

    EmberZllNetwork provides details for ZLL-specific devices:

    • zigbeeNetwork: The underlying EmberZigbeeNetwork.
    • securityAlgorithm: EmberZllSecurityAlgorithmData containing transaction and response IDs.
    • eui64: The device's EUI64.
    • nodeId: The device's Node ID.
    • state: The EmberZllState.
    • nodeType: The EmberNodeType.
    • numberSubDevices: Count of sub-devices.
    • totalGroupIdentifiers: Count of group identifiers.
    • rssiCorrection: RSSI correction value.
  7. Manage Ember radio operation priorities

    master

    To control how the Zigbee radio prioritizes different operations (especially in multi-protocol environments), use Ember802154RadioPriorities. This replaces the deprecated EmberMultiprotocolPriorities.

    Fields:

    • backgroundRx: Priority of a Zigbee RX operation while not receiving a packet.
    • minTxPriority: Starting priority for the first transmit of a packet.
    • txStep: The amount by which TX priority is increased (value decremented) for each retry.
    • maxTxPriority: The maximum priority allowed for retried messages.
    • activeRx: Priority of a Zigbee RX operation while receiving a packet.
    export type Ember802154RadioPriorities = {
        backgroundRx: number;
        minTxPriority: number;
        txStep: number;
        maxTxPriority: number;
        activeRx: number;
    };
  8. Configure Ember network parameters

    master

    When initializing or querying a Zigbee network using the Ember adapter, use the EmberNetworkParameters type to manage core network settings.

    Key fields include:

    • extendedPanId: The network's extended PAN identifier.
    • panId: The network's PAN identifier.
    • radioTxPower: Power setting in dBm.
    • radioChannel: The specific radio channel to use.
    • joinMethod: The protocol messages used to establish an initial parent (e.g., EmberJoinMethod).
    • nwkManagerId: The ID of the network manager (only settable during joining with EMBER_USE_CONFIGURED_NWK_STATE).
    • nwkUpdateId: The Zigbee nwkUpdateId used to track network instances after PAN/channel changes.
    • channels: A bitmask of preferred channels for the NWK manager.
    export type EmberNetworkParameters = {
        extendedPanId: ExtendedPanId;
        panId: PanId;
        radioTxPower: number;
        radioChannel: number;
        joinMethod: EmberJoinMethod;
        nwkManagerId: NodeId;
        nwkUpdateId: number;
        channels: number;
    };
  9. Configure Ember initial security state

    master

    Use EmberInitialSecurityState to define security requirements for forming or joining a network. This structure uses a bitmask to indicate which features are present.

    Important fields:

    • bitmask: Enumerates security features (see EmberInitialSecurityBitmask).
    • preconfiguredKey: A EmberKeyData object used if EMBER_HAVE_PRECONFIGURED_KEY is set in the bitmask.
    • networkKey: The Network Key used when forming the network (required if EMBER_HAVE_NETWORK_KEY is set).
    • networkKeySequenceNumber: The sequence number for the network key.
    • preconfiguredTrustCenterEui64: The long address of the Trust Center (required for commissioning mode; must be in little-endian format).
    export type EmberInitialSecurityState = {
        bitmask: number;
        preconfiguredKey: EmberKeyData;
        networkKey: EmberKeyData;
        networkKeySequenceNumber: number;
        preconfiguredTrustCenterEui64: Eui64;
    };
  10. Configure Door Lock cluster attributes and commands

    master

    The closuresDoorLock cluster manages smart lock security, user codes, and event masking.

    Key Attributes

    • lockState (ENUM8): Current state of the lock.
    • lockType (ENUM8): Type of lock.
    • doorState (ENUM8): Current state of the door.
    • maxPinLen / minPinLen: Constraints for PIN codes.
    • autoRelockTime (UINT32): Time before automatic relocking.
    • enableLocalProgramming (BOOLEAN): Whether local programming is allowed.
    • alarmMask (BITMAP16): Mask for triggering alarms.
    • keypadOperationEventMask (BITMAP16): Mask for keypad events.
    • rfOperationEventMask (BITMAP16): Mask for RF events.

    Key Commands

    • lockDoor: Locks the door using a pincodevalue.
    • unlockDoor: Unlocks the door using a pincodevalue.
    • toggleDoor: Toggles the lock state.
    • unlockWithTimeout: Unlocks for a specific timeout period.
    • setPinCode: Sets a PIN for a specific userid and usertype.
    • getPinCode: Retrieves the PIN for a userid.
    • clearPinCode: Removes a PIN for a userid.
    • clearAllPinCodes: Removes all stored PIN codes.
    // Example: Unlocking a door
    doorLockCluster.commands.unlockDoor({
      pincodevalue: Buffer.from([0x01, 0x02, 0x03, 0x04])
    });
  11. Use the Controller class for Zigbee operations

    master

    The Controller class is the primary entry point for managing Zigbee operations within zigbee-herdsman. It serves as the main orchestrator for the Zigbee network, handling device management, communication, and network state. Note that while it is exported from the main entry point, it is marked as @internal in this specific file, suggesting it is intended to be used by higher-level integrations (like Zigbee2MQTT) or specific library consumers rather than as a low-level standalone utility for general users.

    import Controller from 'zigbee-herdsman/controller';