zigbee-on-host
    Preparing search index...

    Centralized shared state and counters for the Zigbee stack.

    This context holds all shared state between protocol layers including:

    • Network parameters
    • Device and routing tables
    • Frame counters (MAC, NWK, APS, ZDO)
    • Trust Center policies
    • RSSI/LQI ranges
    Index

    Constructors

    Properties

    address16ToAddress64: Map<number, bigint> = ...

    Address lookup: 16-bit to 64-bit (synced with deviceTable)

    appLinkKeyTable: Map<string, AppLinkKeyStoreEntry> = ...

    Application link keys stored for device pairs (ordered by IEEE address)

    associationPermit: boolean = false

    MAC association permit flag

    configAttributes: ConfigurationAttributes = ...

    Configuration attributes

    deviceTable: Map<bigint, DeviceTableEntry> = ...

    Master table of all known devices on the network (mapped by IEEE address)

    indirectTransmissions: Map<bigint, IndirectTxContext[]> = ...

    Indirect transmission for devices with rxOnWhenIdle=false (mapping by IEEE address)

    installCodeTable: Map<bigint, Buffer<ArrayBufferLike>> = ...

    Install code metadata per device (mapped by IEEE address)

    lqiMax: number = 250

    Maximum observed LQI

    lqiMin: number = 15

    Minimum observed LQI

    macNoACKs: Map<number, number> = ...

    Count of MAC NO_ACK reported for each device (mapping by network address)

    Network parameters

    pendingAssociations: Map<bigint, AssociationContext> = ...

    Associations pending DATA_RQ from device (mapping by IEEE address)

    rssiMax: number = -25

    Maximum observed RSSI

    rssiMin: number = -100

    Minimum observed RSSI

    sourceRouteTable: Map<number, SourceRouteTableEntry[]> = ...

    Source routing table (mapped by 16-bit address)

    tcVerifyKeyHash: Buffer = ...

    Pre-computed hash of default TC link key for VERIFY_KEY

    trustCenterPolicies: TrustCenterPolicies = ...

    Trust Center policies

    Accessors

    Methods

    • 05-3474-23 #4.4.11.5 (Switch Key)

      Activate the staged network key if the sequence number matches. Resets frame counters and re-registers hashed keys for cryptographic operations.

      SPEC COMPLIANCE NOTES:

      • ✅ Activates staged key only when sequence matches SWITCH_KEY command
      • ✅ Resets NWK frame counter as mandated after key activation
      • ✅ Re-registers hashed keys for LINK/NWK/TRANSPORT/LOAD contexts to keep crypto in sync
      • ✅ Clears staging buffers to prevent reuse or leakage
      • ⚠️ Does not emit management notifications; assumes higher layer handles ANNCE broadcasts DEVICE SCOPE: Trust Center

      Parameters

      • sequenceNumber: number

        Sequence number referenced by SWITCH_KEY command

      Returns boolean

      true when activation succeeded, false when no matching pending key exists

    • 05-3474-23 #4.5.1 (Install Code processing)

      SPEC COMPLIANCE NOTES:

      • ✅ Validates install code length against permitted sizes (8/10/14/18/22/26 bytes)
      • ✅ Verifies CRC-16 per Zigbee specification before accepting raw install codes
      • ✅ Derives link key using AES-MMO hash when provided with plain install code
      • ✅ Stores hashed value when caller already supplied derived key (e.g., from commissioning tool)
      • ⚠️ CRC computed locally; assumes little-endian order per spec Appendix B DEVICE SCOPE: Trust Center

      Parameters

      • device64: bigint

        IEEE address of device whose code is being stored

      • installCode: Buffer

        Install code or hashed key buffer (length varies)

      • hashed: boolean = false

        Indicates that installCode already contains derived key material

      Returns Buffer

      Derived application link key associated with Trust Center

    • SPEC COMPLIANCE:

      • ✅ Implements timed join window per spec
      • ✅ Updates Trust Center policies
      • ✅ Sets MAC associationPermit flag
      • ✅ Clamps 0xff to 0xfe for security
      • ✅ Auto-disallows after timeout DEVICE SCOPE: Trust Center

      Parameters

      • duration: number

        The length of time in seconds during which the trust center will allow joins. The value 0x00 and 0xff indicate that permission is disabled or enabled, respectively, without a specified time limit. 0xff is clamped to 0xfe for security reasons

      • macAssociationPermit: boolean

        If true, also allow association on coordinator itself. Ignored if duration 0.

      Returns void

    • 05-3474-23 #3.6.1.10 (Network address allocation)

      SPEC COMPLIANCE NOTES:

      • ✅ Allocates short addresses within 0x0001-0xfff7 range, excluding coordinator and broadcast values
      • ✅ Ensures uniqueness against current address16ToAddress64 map before assignment
      • ⚠️ Uses pseudo-random selection rather than deterministic increment (allowed by spec)
      • ⚠️ No persistence of last issued address; relies on state table to avoid collisions after reboot DEVICE SCOPE: Coordinator, routers (N/A)

      Returns number

    • Handle device association (initial join or rejoin)

      SPEC COMPLIANCE:

      • ✅ Validates allowJoins policy for initial join
      • ✅ Assigns network addresses correctly
      • ✅ Detects and handles address conflicts
      • ✅ Creates device table entries with capabilities
      • ✅ Sets up indirect transmission for rxOnWhenIdle=false
      • ✅ Returns appropriate status codes per IEEE 802.15.4
      • ✅ Triggers state save after association
      • ⚠️ Unknown rejoins succeed if allowOverride=true (potential security risk)
      • ✅ Enforces install code requirement (denies initial join when missing)
      • ✅ Detects network key changes on rejoin and schedules transport DEVICE SCOPE: Coordinator, routers (N/A)

      Parameters

      • source16: number | undefined
      • source64: bigint | undefined

        Assumed valid if assocType === 0x00

      • initialJoin: boolean

        If false, rejoin.

      • capabilities: MACCapabilities | undefined

        MAC capabilities

      • neighbor: boolean

        True if the device associating is a neighbor of the coordinator

      • OptionaldenyOverride: boolean

        Treat as MACAssociationStatus.PAN_ACCESS_DENIED

      • OptionalallowOverride: boolean

        Treat as MACAssociationStatus.SUCCESS

      Returns Promise<[status: number, newAddress16: number, requiresTransportKey: boolean]>

    • 05-3474-23 #4.7.6 (Trust Center maintenance)

      Remove the save file and clear tables (just in case)

      SPEC COMPLIANCE NOTES:

      • ✅ Clears persistent storage and in-memory tables when performing factory reset
      • ⚠️ Caller must reinitialize descriptors/netParams afterwards per spec flow DEVICE SCOPE: Trust Center

      Returns Promise<void>

    • 05-3474-23 #2.4.4.2.3 (Neighbor table reporting)

      Compute the median LQA for a device from recentLQAs or using signalStrength directly if device unknown. If given, stores the computed LQA from given parameters in the recentLQAs list of the device before computing median.

      SPEC COMPLIANCE NOTES:

      • ✅ Maintains rolling median of recent LQA samples for stable reporting in Mgmt_Lqi_rsp
      • ✅ Falls back to instantaneous computation when history absent, matching spec guidance
      • ✅ Resolves IEEE address from short address when needed for table lookup
      • ⚠️ Median window size configurable (default 10) - spec does not mandate exact count
      • ⚠️ Zero returned when device unknown aligns with spec allowance for missing entries DEVICE SCOPE: Coordinator, routers (N/A), end devices (N/A)

      Parameters

      • address16: number | undefined

        Used to retrieve address64 if not given (must be valid if 64 is not)

      • address64: bigint | undefined

        The IEEE address of the device

      • OptionalsignalStrength: number

        RSSI. Optional (only use existing entries if not given)

      • OptionalsignalQuality: number

        LQI. Optional (only use existing entries if not given)

      • maxRecent: number = 10

        Number of entries to retain in rolling window (default 10)

      Returns number

      Median LQA for the device or 0 when unavailable

    • 05-3474-23 #3.3.4.3 (Link Quality Assessment)

      LQA_raw (c, r) = 255 * (c - c_min) / (c_max - c_min) * (r - r_min) / (r_max - r_min)

      • c_min is the lowest signal quality ever reported, i.e. for a packet that can barely be received
      • c_max is the highest signal quality ever reported, i.e. for a packet received under ideal conditions
      • r_min is the lowest signal strength ever reported, i.e. for a packet close to receiver sensitivity
      • r_max is the highest signal strength ever reported, i.e. for a packet received from a strong, close-by transmitter HOT PATH: Called for every incoming frame to compute link quality assessment.

      SPEC COMPLIANCE NOTES:

      • ✅ Computes link quality assessment (LQA) using normalized RSSI/LQI ranges per Zigbee PRO guidance
      • ✅ Ensures output range 0-255 for compatibility with NLME-LQI reports
      • ✅ Accepts externally provided LQI or derives from RSSI for MACs that omit it
      • ⚠️ Logistic coefficients tuned empirically; spec allows vendor-specific mapping
      • ⚠️ Runtime min/max windows updated elsewhere; assumes values reflect current environment DEVICE SCOPE: Coordinator, routers (N/A), end devices (N/A)

      Parameters

      • signalStrength: number

        RSSI value

      • OptionalsignalQuality: number

        LQI value (optional, computed from RSSI if not provided)

      Returns number

      Computed LQA value (0-255)

    • 05-3474-23 #3.3.1.5 (NWK radius handling)

      Decrement radius value for NWK frame forwarding. HOT PATH: Optimized computation

      SPEC COMPLIANCE NOTES:

      • ✅ Decrements NWK radius while enforcing minimum value of 1 as mandated
      • ✅ Substitutes CONFIG_NWK_MAX_HOPS when radius=0 (interpreted as unlimited per spec)
      • ⚠️ Does not update route record metrics; caller responsible for hop tracking DEVICE SCOPE: Coordinator, routers (N/A), end devices (N/A)

      Parameters

      • radius: number

        Current radius value

      Returns number

      Decremented radius (minimum 1)

    • Revert allowing joins (keeps allowRejoinsWithWellKnownKey=true).

      SPEC COMPLIANCE:

      • ✅ Clears timer correctly
      • ✅ Updates Trust Center allowJoins policy
      • ✅ Maintains allowRejoinsWithWellKnownKey for rejoins
      • ✅ Sets associationPermit flag for MAC layer DEVICE SCOPE: Trust Center

      Returns void

    • Handle device disassociation (leave)

      SPEC COMPLIANCE:

      • ✅ Removes from device table
      • ✅ Removes from address mappings (16↔64)
      • ✅ Cleans up indirect transmissions
      • ✅ Removes from source route table
      • ✅ Cleans up pending associations
      • ✅ Clears MAC NO_ACK counters
      • ✅ Removes routes using device as relay
      • ✅ Triggers onDeviceLeft callback
      • ✅ Forces state save
      • ✅ Handles both address16 and address64 resolution

      THOROUGH CLEANUP: All device-related state properly removed DEVICE SCOPE: Coordinator, routers (N/A)

      Parameters

      • source16: number | undefined
      • source64: bigint | undefined

      Returns Promise<void>

    • 05-3474-23 #4.4.11 (Trust Center link/app keys)

      SPEC COMPLIANCE NOTES:

      • ✅ Retrieves stored application/link key using canonicalized IEEE pair
      • ✅ Returns undefined when pair missing, allowing caller to trigger key negotiation per spec
      • ⚠️ Does not validate key freshness; higher layers manage key attributes DEVICE SCOPE: Trust Center

      Parameters

      • deviceA: bigint
      • deviceB: bigint

      Returns Buffer<ArrayBufferLike> | undefined

    • 05-3474-23 #4.7.6 (Trust Center start-up procedure)

      Load state from file system if exists, else save "initial" state. Afterwards, various keys are pre-hashed and descriptors pre-encoded.

      SPEC COMPLIANCE NOTES:

      • ✅ Restores network parameters, device table, and link keys before enabling stack operations
      • ✅ Recomputes hashed keys for LINK/NWK/TRANSPORT/LOAD usage as required for secure processing
      • ✅ Initializes coordinator descriptors per Zigbee Device Objects defaults
      • ⚠️ Missing persistence for per-device incoming NWK frame counters (TODO noted)
      • ⚠️ Creates initial save file when none exists to align with spec initialization sequence DEVICE SCOPE: Trust Center

      Returns Promise<void>

    • IEEE 802.15.4-2015 #10.2.1 (Link Quality Indication)

      Apply logistic curve on standard mapping to LQI range [0..255]

      • Silabs EFR32: the RSSI range of [-100..-36] is mapped to an LQI range [0..255]
      • TI zstack: LQI = (MAC_SPEC_ED_MAX * (RSSIdbm - ED_RF_POWER_MIN_DBM)) / (ED_RF_POWER_MAX_DBM - ED_RF_POWER_MIN_DBM); where MAC_SPEC_ED_MAX = 255, ED_RF_POWER_MIN_DBM = -87, ED_RF_POWER_MAX_DBM = -10
      • Nordic: RSSI accuracy valid range -90 to -20 dBm

      SPEC COMPLIANCE NOTES:

      • ✅ Produces LQI values in mandated 0-255 range
      • ✅ Clamps RSSI to implementation-defined sensitivity window before scaling
      • ✅ Applies monotonic mapping to preserve relative ordering (spec leaves exact curve implementation-defined)
      • ⚠️ Logistic curve tuned to typical 2.4 GHz radios; may require calibration per PHY
      • ⚠️ rssiMin/rssiMax derived from runtime observation rather than PHY constants DEVICE SCOPE: Coordinator, routers (N/A), end devices (N/A)

      Parameters

      • rssi: number

      Returns number

    • Get next network key frame counter. HOT PATH: Optimized counter increment

      Returns number

      Incremented network key frame counter (wraps at 0xffffffff)

    • Get next Trust Center key frame counter. HOT PATH: Optimized counter increment

      Returns number

      Incremented TC key frame counter (wraps at 0xffffffff)

    • 05-3474-23 #4.7.6 (Trust Center persistent data)

      Read the current network state in the save file, if any present.

      SPEC COMPLIANCE NOTES:

      • ✅ Reads TLV state blob and validates version before applying
      • ✅ Logs metadata (PAN ID, channel) for diagnostics per spec recommendations
      • ⚠️ Unknown future versions are attempted with warning rather than hard fail (best effort) DEVICE SCOPE: Trust Center

      Returns Promise<ParsedState | undefined>

    • 05-3474-23 #4.5.1 (Install Code lifecycle)

      SPEC COMPLIANCE NOTES:

      • ✅ Removes stored install code metadata upon revocation
      • ⚠️ Leaves derived link key intact (spec allows retention for existing secure links) DEVICE SCOPE: Trust Center

      Parameters

      • device64: bigint

      Returns void

    • 05-3474-23 #4.7.6 (Trust Center maintenance)

      SPEC COMPLIANCE NOTES:

      • ✅ Persists state at configured interval while refreshing timer to maintain cadence
      • ⚠️ Interval configurable via CONFIG_SAVE_STATE_TIME (60s default) DEVICE SCOPE: Trust Center

      Returns Promise<void>

    • 05-3474-23 #4.7.6 (Trust Center persistent data)

      Save state to file system in TLV format.

      SPEC COMPLIANCE NOTES:

      • ✅ Persists Trust Center datasets (network parameters, device table, link keys) between restarts
      • ✅ Adds frame-counter jump offset when storing to meet anti-replay requirements after reboot
      • ✅ Serializes TLV records for extensibility and backward compatibility
      • ⚠️ Format version tracked locally; interoperability with other implementations requires converter
      • ⚠️ Application link key attributes not currently stored (keys only) DEVICE SCOPE: Trust Center

      Format version 1:

      • VERSION tag
      • Network parameter tags (EUI64, PAN_ID, etc.)
      • DEVICE_ENTRY tags (each containing nested TLV device data)
      • END_MARKER

      Returns Promise<void>

    • 05-3474-23 #4.4.11.1 (Application Link Key establishment)

      SPEC COMPLIANCE NOTES:

      • ✅ Stores link/application keys using sorted IEEE tuple to match spec requirement for unordered pairs
      • ✅ Keeps full 16-byte key material intact for subsequent APS ENCRYPT operations
      • ⚠️ Does not persist key attributes (VERIFIED/PROVISIONAL) – tracked elsewhere DEVICE SCOPE: Trust Center

      Parameters

      • deviceA: bigint
      • deviceB: bigint
      • key: Buffer

      Returns void

    • 05-3474-23 #2.3.2.3 (Node Descriptor)

      Set the manufacturer code in the pre-encoded node descriptor

      SPEC COMPLIANCE NOTES:

      • ✅ Writes manufacturer code at fixed offset within pre-encoded ZDO node descriptor response
      • ⚠️ Assumes descriptor already generated via encodeCoordinatorDescriptors DEVICE SCOPE: Coordinator, routers (N/A), end devices (N/A)

      Parameters

      • code: number

        Manufacturer code assigned by CSA

      Returns void

    • 05-3474-23 #4.4.11.2 (Network Key transport)

      Store a pending network key that will become active once a matching SWITCH_KEY is received.

      SPEC COMPLIANCE NOTES:

      • ✅ Stages pending network key and associated sequence number per TRANSPORT_KEY requirements
      • ✅ Normalizes sequence to 8-bit value to mirror Zigbee NWK field size
      • ✅ Copies key material to avoid caller mutations (spec mandates immutable staging)
      • ⚠️ Does not persist staged key to disk; relies on immediate SWITCH_KEY follow-up (acceptable for coordinator uptime) DEVICE SCOPE: Trust Center

      Parameters

      • key: Buffer

        Raw network key bytes (16 bytes)

      • sequenceNumber: number

        Sequence number advertised for the pending key

      Returns void

    • 05-3474-23 #4.7.6 (Trust Center maintenance)

      SPEC COMPLIANCE NOTES:

      • ✅ Schedules periodic state persistence while stack is running
      • ✅ Immediately saves state to ensure on-disk snapshot reflects startup values
      • ⚠️ Additional periodic tasks (key rotation, metrics) remain TODO DEVICE SCOPE: Trust Center

      Returns Promise<void>

    • 05-3474-23 #4.7.6 (Trust Center maintenance)

      SPEC COMPLIANCE NOTES:

      • ✅ Cancels pending timers and ensures join window closed on shutdown
      • ✅ Mirrors spec recommendation to revoke permit-join when TC inactive DEVICE SCOPE: Trust Center

      Returns void

    • 05-3474-23 #3.6.1.11 / Table 3-54 (End Device Timeout)

      Update the stored end device timeout metadata for a device.

      SPEC COMPLIANCE NOTES:

      • ✅ Validates timeout index against Table 3-54 mapping (0-14)
      • ✅ Stores absolute expiration timestamp for NLME-ED-TIMEOUT enforcement
      • ✅ Persists last requested index to reuse during retransmission handling
      • ⚠️ Does not enforce parent capability bits; assumes MAC handler already vetted support
      • ⚠️ Lifetime not persisted to disk (cleared on restart per spec allowance) DEVICE SCOPE: Coordinator, routers (N/A)

      Parameters

      • address64: bigint

        IEEE address of the end device

      • timeoutIndex: number

        Requested timeout index (0-14)

      • now: number = ...

        Optional timestamp override (for testing)

      Returns
          | {
              expiresAt: number;
              lastUpdated: number;
              timeoutIndex: number;
              timeoutMs: number;
          }
          | undefined

      Updated timeout metadata or undefined if device/index invalid

    • 05-3474-23 #3.7.3 (NWK security) / IEEE 802.15.4-2015 #9.4.2

      Update and validate the incoming NWK security frame counter for a device.

      SPEC COMPLIANCE NOTES:

      • ✅ Rejects replayed NWK security frames when counter does not strictly increase
      • ✅ Handles counter wrap from 0xffffffff → 0 per Zigbee PRO requirement
      • ✅ Stores last accepted counter per IEEE address for subsequent validation
      • ⚠️ Devices without stored state (e.g., unknown IEEE) default to allowing frame (per spec recommendation)
      • ⚠️ Persistence across restarts not implemented (TODO noted) DEVICE SCOPE: Coordinator, routers (N/A), end devices (N/A)

      Parameters

      • address64: bigint | undefined
      • frameCounter: number

      Returns boolean

      false if the provided counter is a replay (<= stored value, excluding wrap).