Skip to content

Getting started: the device side

This page builds a Matter bridge with one on/off light, pairs it, and walks through what each part of the program does. The program is examples/quickstart-device/main.go; its test builds it, starts the node on loopback, stops it and starts it again on the same database.

node/ or bridge/?

Embed node/ unless you have a reason not to. node.New performs the whole bring-up the reference daemon used to do by hand: the stores, the root and Aggregator endpoints, PASE and CASE, the subscription engine, the commissioning window, the fabric hooks, and every port of bridge/ in its documented order. You configure it with one node.Config and add devices to its Aggregator.

Use the facade with your own topology when you already map your own device model onto endpoints: set Config.Snapshotter to your bridge.Snapshotter. The facade then builds no assembler of its own, and everything else (stores, root servers, sessions, group state) stays the facade's. The topology your snapshotter returns must come from an endpoint.Assembler over your endpoint.Specs — "your own assembler" means your own Spec producer, not your own endpoint.Topology. Endpoint and Topology are read-only to a host: the per-cluster DataVersions, the Identify and Groups servers, a written NodeLabel and the scene tables live in state only the assembler fills, so a hand-built topology loses them on every Reassemble.

Use bridge/ directly only if you need to replace one of the collaborators the facade wires. bridge.New installs a no-op for every port you do not attach, so a half-wired bridge binds its socket, publishes mDNS and answers datagrams wrongly. The ports guide lists every port, what skipping it costs, and whether the failure is visible. Node.Bridge() gives you the bridge for a port the facade does not cover without leaving the facade.

Source: node/doc.go (package doc), node/config.go (Config.Snapshotter), bridge/bridge.go (package doc, Bring-up sequence), node/node.go (Node.Bridge).

The program

// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2026 SukramJ.

// Command quickstart-device is the smallest Matter bridge on go-fabric: one
// on/off light under the node's Aggregator, its state in one SQLite file,
// advertised over DNS-SD. It names the facade only — node, device,
// contract and the light's cluster definition; the node opens the store
// and builds its own advertiser. docs/getting-started/device.md walks
// through it. It pairs with the CSA test identity and is not a product.
package main

import (
    "context"
    "crypto/rand"
    "fmt"
    "log/slog"
    "os"
    "os/signal"
    "slices"
    "syscall"

    onoffdef "thingfabric.dev/go-fabric/cluster/spec/onoff"
    "thingfabric.dev/go-fabric/contract"
    "thingfabric.dev/go-fabric/device"
    "thingfabric.dev/go-fabric/node"
)

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    err := run(ctx)
    stop()
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

func run(ctx context.Context) error {
    // The zero Network listens on :5540 and advertises over DNS-SD: a nil
    // Config.Advertiser is the node's own mDNS responder, which answers
    // every commissioner's discriminator browse.
    n, err := newNode(ctx, "quickstart-device.db", node.Network{})
    if err != nil {
        return err
    }
    payload, err := n.SetupPayload()
    if err != nil {
        _ = n.Stop(context.WithoutCancel(ctx))
        return err
    }
    fmt.Printf("QR code: %s\nManual code: %s\n", payload.QR, payload.Manual)
    return n.Run(ctx) // Start, wait for ctx, Stop
}

// randomSalt is a SPAKE2+ salt drawn at random at each start, never a
// constant every copy of this example shares (R2-P6-sec-2615): the salt
// reaches a commissioner inside PASE only, so nothing needs it kept.
func randomSalt() []byte {
    salt := make([]byte, node.PBKDFSaltMax)
    _, _ = rand.Read(salt) // crypto/rand.Read does not fail
    return salt
}

// newNode builds the node on the SQLite file at path — the node opens it
// (foreign keys on, a new file created 0600), applies the schemas and
// closes it on Stop — and adds the light, unstarted.
func newNode(ctx context.Context, path string, network node.Network) (*node.Node, error) {
    n, err := node.New(ctx, node.Config{
        Network: network,
        Commissioning: node.Commissioning{ // change the passcode and discriminator for anything real
            Passcode: 20202021, Discriminator: 3840,
            PBKDFIterations: 1000, Salt: randomSalt(),
        },
        ProductDescription: node.ProductDescription{VendorID: 0xFFF1, ProductID: 0x8001}, // CSA test vendor
        BasicInformation: node.BasicInformation{
            VendorName: "quickstart", ProductName: "quickstart-device",
            NodeLabel: "Quickstart bridge", SerialNumber: "QUICKSTART-0001",
        },
        Store: node.Store{Path: path},
    })
    if err != nil {
        return nil, err
    }
    light, err := device.NewOnOffLight(device.Options{StableKey: device.StringKey("light-1"), Name: "Desk lamp"})
    if err == nil {
        light.OnOff().OnChanged(func(s onoffdef.State, c contract.Change) {
            if slices.Contains(c.Attributes, onoffdef.AttrOnOff) {
                slog.Info("light", slog.Bool("on", s.OnOff)) // drive the real lamp here
            }
        })
        err = n.Aggregator().Add(ctx, light)
    }
    if err != nil {
        _ = n.Stop(context.WithoutCancel(ctx))
        return nil, err
    }
    return n, nil
}

Run it, scan the QR code or enter the manual code in a commissioner, and the light appears under the bridge:

go run ./examples/quickstart-device

It listens on UDP port 5540 and needs IPv6 and multicast on the LAN, like any Matter device. A commissioner that filters by discriminator, which is what Apple Home, Google Home and chip-tool do for a QR or manual code, finds the device through the _L<discriminator>._sub subtype record, which the node's own mDNS responder publishes with the rest of the record set when Config.Advertiser is nil. A host's advertiser without subtype records lists the instance under _matterc._udp, but the discriminator subtype query gets no answer. The program names no package below the facade: the node opens the SQLite file (Store.Path), the key is device.StringKey, and the light's changes arrive typed through OnOff().OnChanged.

Source: examples/quickstart-device/main.go, examples/quickstart-device/main_test.go, node/mdns.go (defaultAdvertiser), node/store_path.go.

Configuration

node.New calls Config.Validate first and refuses the whole configuration with node.ErrInvalidConfig when any check fails. It checks:

  • the discriminator fits 12 bits;
  • the passcode is in range and not on the trivially-guessable list;
  • the PBKDF iteration count and salt length are what SPAKE2+ accepts;
  • VendorID and ProductID are set, and ProductDescription.DeviceType, when set, is a device type of the schema;
  • a store is given — Store.Path, Store.DB, or both Store.Credentials and Store.Endpoints (see below) — and not both Store.Path and Store.DB;
  • Attestation.Provider is not combined with Files, Chain or the CD, Attestation.Files is not combined with Chain or the CD, and BlockCommissioningOnError comes with Files;
  • BootReason is a BootReasonEnum value;
  • Health.Interval and Network.InterfaceCheck are not below 1 s when positive (Health.Interval not negative; a negative InterfaceCheck turns the check off);
  • Limits.SupportedFabrics is at most 254, and a deprecated Config.SupportedFabrics or Config.MaxPathsPerInvoke set beside its Limits field equals it;
  • Network takes GATT or the deprecated BLE, not both;
  • the advertised device name (ProductDescription.Name, else BasicInformation.NodeLabel) is at most 32 bytes, and Network.MDNS's settings are not combined with an own Advertiser;
  • UniqueID is at most 32 bytes, and every BasicInformation string (VendorName, ProductName, ProductLabel, NodeLabel, SerialNumber, HardwareVersionString, SoftwareVersionString) is inside its attribute's constraint in the generated definition — a SerialNumber longer than 32 bytes in UTF-8 fails, as matter.js counts string lengths since #4995;
  • LocationCapability is a valid regulatory location (zero is IndoorOutdoor, matter.js's default), and IndoorOnly comes with no other value;
  • Network.WiFi, when set, has its Driver, its Reporter or both;
  • Network.TCP.MaxInboundConnections is not negative;
  • every name in Network.MDNS.Interfaces is non-empty and named once, and Network.MDNS.HostName, when set, is one DNS label of at most 40 bytes;
  • OTA.Dir is set when OTA is, and OTA.HTTPSMaxImageSize, HTTPSIdleTimeout and AnnouncedUpdateQueryDelay are not negative;
  • TLS.CertificatePort is set when TLS is, and each TLS capacity is inside its bound;
  • EndpointState is not combined with the deprecated EndpointPersistence;
  • DeviceTypeValidation is one of warn, strict and off;
  • every Limits field is inside its bound and the Sessions intervals are valid;
  • TimeSynchronization.Config is not combined with TimeSynchronization.Off;
  • ICD, when set, is a valid ICD configuration.

Config.Validate in node/config.go is the authority; this list follows it.

The quickstart uses the CSA test vendor 0xFFF1. With no Attestation set, the node serves the CSA test attestation chain and test Certification Declaration for the configured vendor and product. Every commissioner accepts that chain through its test PAA, and a product must not ship with it. A product sets Config.Attestation to its own DAC, PAI and CD.

Defaults worth knowing:

Field Zero value means
Network.Listen :5540
Advertiser the node's own mdns.Responder (mdns.NewResponder); Network.MDNS.Off makes it mdns.NewNoop(), and nothing can discover the node
Network.MDNS the mDNS responder, SRV target from the interface's MAC (on macOS the OS host name instead when mDNSResponder serves it for this host, otherwise the MAC-derived name as everywhere — by_design.md L7-D03), every record 120 s, announced on matter.js's broadcast schedule (1 s doubling to 90 s, until a CASE connection or two days); Off publishes nothing, HostName sets an SRV target whose address records the OS responder publishes, Interfaces restricts it to the named host interfaces (the container filter still applies)
Store.Path unused; set, the node opens that SQLite file (modernc.org/sqlite, foreign keys on, 5 s busy timeout) and Stop closes it
Attestation.Files unused; set, New loads the vendor chain and fails when it does not load (files naming nothing keep the test chain); with BlockCommissioningOnError it runs on the test chain instead, commissioning refused, the error in Node.AttestationError
Health nil runs no probe; set, it runs from Start to Stop every Interval (0 is 30 s), Node.OnHealthSample receives every verdict, Node.Health returns the last one
DeviceTypeValidation matter.js's warn mode
Limits.SupportedFabrics 5 (matter.js defaults to 254)
BootReason Unspecified, matter.js's default; a start into the version the node's own OTA requestor recorded as its update in progress reports SoftwareUpdateCompleted whatever this states
Commissioning.LocationCapability IndoorOutdoor, matter.js's default; Commissioning.IndoorOnly states Indoor
OTAProvider.GrantFabric with OTAProvider set: the provider's ACL entry is written into no fabric — the fabric's administrator grants the access, or the host returns true for the fabrics it opens the provider to. A grant only adds: an entry written while a grant stood, or by a version that wrote it into every fabric, stays when the grant goes, until the fabric's administrator writes the ACL without it
WebRTCRequestor.GrantFabric the ACL entry that lets a camera reach a WebRtcTransportRequestor the topology serves is written into no fabric — the fabric's administrator grants the access, or the host returns true for the fabrics its cameras signal on. A grant only adds: an entry written while a grant stood, or by a version that wrote it into the first fabric, stays when the grant goes, until the fabric's administrator writes the ACL without it
BasicInformation.NodeLabel BasicInformation.ProductName
ProductDescription.Name BasicInformation.NodeLabel
ProductDescription.DeviceType inferred for the commissionable advertisement (DT, _T<id>) when the node advertises, as matter.js's ProductDescriptionServer infers it: the first device type of the first endpoint of a simple device type — or of a device type outside the schema snapshot, which matter.js also treats as simple — below the root and the Aggregator (a bridged device's type); the first type found stays; RootNode (0x0016) while no such endpoint is served
BasicInformation.UniqueID derived on the first boot and pinned in the store
Locales en-US alone
TimeFormat 24-hour, Gregorian, Gregorian the only calendar listed; set (node.TimeFormatConfig), the root TimeFormatLocalization starts at its HourFormat and ActiveCalendarType (nil: the first of SupportedCalendarTypes) and lists SupportedCalendarTypes (empty: the active calendar alone), or serves HourFormat alone without the CalendarFormat feature with NoFeatures; a start the server refuses fails node.New with core.ErrLocalizationConfig — the node adds no default of its own
Logger slog.Default()
Client nil runs no client stack; set, the node opens its client socket and peers for its Binding entries
Network.WiFi nil is an Ethernet-attached node, with no Wi-Fi cluster; set, its Driver mounts NetworkCommissioning with the Wi-Fi feature and its Reporter serves WiFiNetworkDiagnostics — one of the two is required
Faults nil serves no fault list; set (contract.FaultSource), the root GeneralDiagnostics serves ActiveHardwareFaults, ActiveRadioFaults and ActiveNetworkFaults from it and emits HardwareFaultChange, RadioFaultChange and NetworkFaultChange with the current and the previous list each time the source notifies a change of a list, as matter.js's registerHardwareFault and clearHardwareFault do; a value listed twice is served once
Sessions the Matter MRP intervals (500 ms idle, 300 ms active, 4000 ms active threshold); set, the PASE and CASE session parameters and the operational record carry the node's own (node.SessionIntervals, whole milliseconds, the threshold at most 65535 ms); Node.SessionParameters returns what the node reports (Limits)
Limits.BDXAdditionalMrpDelay no margin; set, the exchange of every inbound BDX transfer (an OTA requestor's download) adds it to the peer's MRP base interval, as matter.js's bdxAdditionalMrpDelay does
TimeSynchronization mounted, UTCTime, Granularity and TimeSource of the node's UTC; Off leaves it off the root — the node then has no UTC, and Aggregator.Add and Replace refuse a Valve with TimeSync —, Config serves the TZ, NTPC, NTPS and TSC features it names, after connectedhomeip (Time synchronization)
TLS no TLS servers; set, TlsCertificateManagement and TlsClientManagement mount on endpoint 0 (node.TLSConfig: the CertificatePort, per-fabric maxima defaulting to chip's 5, the stores defaulting to the node's) and every camera's PushAvStreamTransport without its own TLS lookups validates against them (Camera)

Source: node/config.go (Config, Commissioning, ProductDescription, BasicInformation, Config.Validate), node/node.go (New).

The node's own name

BasicInformation.NodeLabel is the label the node serves on its first boot; empty, it is BasicInformation.ProductName, as matter.js defaults it. Node.SetNodeLabel(ctx, label) changes it at run time with a controller's write semantics: a label over 32 bytes is refused with CONSTRAINT_ERROR (an im.StatusCodeError), and an accepted one is persisted where a controller's written label is — a store failure fails the call with nothing changed and nothing reported — and then reported to every subscription that covers it and to Observers.OnAttributeChanged with contract.OriginHostSet. Before Start the label is configuration: it is the one the node serves when it starts and it is persisted, but no subscription exists yet and the observers are not told. node.New restores the persisted label — the host's or a controller's, whichever wrote last — over the configured one without reporting a change, and a controller's later write wins and reaches the observers with contract.OriginControllerWrite. UniqueID does not follow the label. A bridged device's NodeLabel is Device.Rename's (The Aggregator).

Source: node/node_label.go, cluster/core/basic_information.go (SetNodeLabel, RestoreNodeLabel, MatterWrite), node/persist.go (restoreRoot).

Devices

The device/ package has one constructor per Matter device type in scope: device.NewOnOffLight, device.NewDimmableLight, device.NewThermostat and so on. They are generated from the matter.js model. A constructor mounts every server cluster the device type mandates, with a default server: the module's own server where one runs on its own state — OnOff, LevelControl, ColorControl, Binding, EcosystemInformation, the alarm, BooleanStateConfiguration, ThermostatUserInterfaceConfiguration and energy servers, and Switch, DoorLock, WindowCovering, Thermostat, the filter monitors and LaundryWasherControls for a feature selection their server serves (device/defaults.go lists them) — otherwise the generated spec.Server, whose commands are unimplemented until you handle them. A NewDimmableLight therefore dims: a controller's MoveToLevel moves its level, and the "with On/Off" commands switch its OnOff. A generated server starts where matter.js's state starts: every attribute it lists holds the type's default, the host's Initial, or the fallback matter.js's SelectDefaultValue gives — null when nullable, 0 for a number or bitmap, false, an empty list — and what matter.js's default server sets in its initialize (FanControl's FanMode Off, SmokeCoAlarm's alarm states Normal). OccupancySensing has a self-held server of the module's: the sensor type follows its detector features, each change of Occupancy emits OccupancyChanged when the selection has OccupancyEvent, and a declaration that serves HoldTime gets chip's hold timer — a cleared Occupancy holds for HoldTime. A TemperatureSensor therefore answers MeasuredValue null until you set a reading. An enum or a string has no fallback in matter.js either, and a struct only an empty placeholder (SelectDefaultValue.ts:19, :167-171); all three stay yours to state (the test TestEveryListedAttributeHasAValue names them). The endpoint assembler mounts Descriptor, Identify, BridgedDeviceBasicInformation, Groups and ScenesManagement; the device layer never does. To make the device blink, declare identifydef.Declare{HandleIdentify: …, HandleTriggerEffect: …} — the assembler's Identify server runs your handler before it counts IdentifyTime, and an error refuses the command — or install them at run time with light.Identify().HandleIdentify(fn). An Identify declaration takes these two handlers only; the assembler keeps IdentifyTime. The Identify handler runs while the server holds its IdentifyTime queue, so it must not set IdentifyTime on the same endpoint from inside the call — that request would wait for the handler's own return — and it should return promptly (Host ports, IdentifyHandler).

device.Options identifies the device:

  • StableKey is required and unique. The assembler keeps the endpoint number under it, so the same key gets the same endpoint number after a restart. The quickstart's test checks this.
  • Name becomes the bridged device's NodeLabel. Vendor is its manufacturer.
  • DeviceAddress and ChannelAddress are your own addresses of the physical device and of this function of it, carried through verbatim.
  • Logger receives the device kit's diagnostics; nil is slog.Default().
  • Conditions are the device-type conditions you state for the endpoint.
  • DeviceTypes lists further device types in the endpoint's Descriptor DeviceTypeList, after the device's own and before Bridged Node, each once and with the schema's revision — matter.js's bridge test instance lists Power Source on its composed device this way. A listed type's mandatory clusters are then required of the endpoint, and an id the schema does not know is refused.
  • Tags are the semantic tags the endpoint's Descriptor serves in TagList (device.SemanticTag); they tell sibling parts of one device type apart, as CommonNumberTag One and Two do on matter.js's composed device. Without tags the Descriptor serves no TagList and its FeatureMap no TAGLIST bit — the default, because Apple Home rejects a Descriptor that serves it.
  • Surface are the surface policies the device is composed under; a node refuses a device composed under policies other than its own.

A device starts reachable; Device.SetReachable(ctx, ok) reports a change.

Declarations passed after Options change what the device serves. A cluster is declared with <cluster>def.Declare of its generated package (thingfabric.dev/go-fabric/cluster/spec/<cluster>, imported as <cluster>def), the one form for everything about it:

Declare field Effect
Initial initial state over the device type's defaults; an optional attribute with a value is served
Features the cluster's feature selection (zero is the default: the device type's mandated features and the ones matter.js's default server enables — ChangeEvent on BooleanState)
OnWrite a veto on a controller's write
Handle<Command> your handler in place of the server's own (an optional command is then accepted)
a host port (Sink, LevelSource, Mover, …) the device the kit's server drives
HostServer your own server for the cluster, replacing the kit's

The declaration is construction; the typed server's setters of the same name (Server.OnWrite, Server.Handle<Command>) are the change at run time, for a host that installs or removes a hook after the device runs.

Declaring an optional cluster of the device type mounts it, even an empty <cluster>def.Declare{}; Groups and ScenesManagement are then the assembler's. A sensor's measurement cluster is declared the same way — temperaturemeasurementdef.Declare{Initial: …} — and your reading reaches it through the accessor's Set. Which clusters each device type mandates, with the features and attribute constraints it requires, is listed in the device-type reference; go doc thingfabric.dev/go-fabric/device lists every typed cluster package.

The device's other options:

Option Effect
HostServer(srv) your own server for any cluster, when your servers are a list: the cluster's Declare{HostServer: srv} where it has a package, the mount where it has none; a port, an Initial or a feature selection still takes the typed Declare
Measurement(src) the clusters a classified host source materialises (contract.MeasurementSource, one class per data point; a battery rides as the device's PowerSource), for a host whose sensors are data rather than per-type code
WithChangeNotifier(n) tells the bridge your model changed state its servers read
WithClientClusters(ids...) client clusters beyond the mandatory ones

Two directions of state

A device's state moves both ways, and the two directions use different calls:

  • Controller to device. Device.OnChanged(clusterID, fn) calls fn with the change — the attribute ids and its origin — and the typed light.OnOff().OnChanged(fn) with the new state and the change. OnChangedAsync is the same, run on the device's own goroutine instead of the caller's. The quickstart uses OnChanged to log the light's new state. Both fire for every change, whoever made it; change.Origin tells your own Set (contract.OriginHostSet) from a controller's attribute write (OriginControllerWrite) and a command (OriginCommand). Only a controller reaches the declaration's three hooks: OnWrite, a veto on a controller's write; Handle<Command> (HandleOn, HandleToggle, …), your handler in place of the server's own; and a host port, the device the server drives. To refuse a command, for example when the physical lamp did not switch, declare the light's switch: onoffdef.Declare{Sink: relay}. An error from the sink answers FAILURE and stores nothing. A hook, a port or a host server that wants another status returns (or wraps) a contract.StatusError{Status: …, ClusterStatus: …}: the controller receives that status, as matter.js answers a StatusResponseError — contract.StatusTimeout for an answer the device could not give in time, 0x87 for a value it refuses, 0x01 with a cluster status for a cluster-specific one. A status error naming Success answers FAILURE.
  • Device to controller. When the lamp is switched at the wall, call light.OnOff().Set(onoffdef.Patch{OnOff: new(on)}) (onoffdef is thingfabric.dev/go-fabric/cluster/spec/onoff). The value is stored and reported to subscribers, and the sink is not called. An attribute Matter marks quieter — LevelControl's CurrentLevel, ColorControl's current colour — is reported at most once a second with its latest value, at once from or to null, as matter.js throttles it; a read, the cluster's DataVersion and OnChanged see every change at once. Set is safe from any goroutine, including from inside the sink.

Source: device/doc_gen.go, device/defaults.go, device/options.go (Options, HostServer, WithChangeNotifier, WithClientClusters), device/hostserver_gen.go, device/measurement.go (Measurement), device/device.go, cluster/spec/onoff/server_gen.go (Declare, OnChanged, OnChangedAsync), contract/ (Change, Origin), cluster/onoff/server.go (Set, SetAttributes, Handle).

Composite device types

VideoDoorbell and FloodlightCamera are composites: their requirements are device types only (a Camera and a Doorbell; an OnOffLight and a Camera). matter.js generates them with no behaviours of their own and counts a component on an endpoint below the composite, never on the composite's endpoint itself (DeviceTypeConformance.ts:596-613 at db021da0). Their constructors take the components and add them as parts:

camera, _ := device.NewCamera(device.Options{StableKey: endpoint.StringKey("door/cam")}, camDecls...)
bell, _ := device.NewDoorbell(device.Options{StableKey: endpoint.StringKey("door/bell")})
door, err := device.NewVideoDoorbell(device.Options{StableKey: endpoint.StringKey("door")}, camera, bell)
// door.Camera(), door.Doorbell(); err wraps device.ErrComposition without a component

Each endpoint keeps one device type in its DeviceTypeList unless Options.DeviceTypes lists more; the node's device-type validation accepts the composition with its parts and reports the two instanceCount violations matter.js pins for a composite without them.

The Aggregator

Node.Aggregator() is the Aggregator endpoint's set of bridged devices.

  • Before Start, Add and Remove only change the set. The first assembly happens at Start.
  • After Start, each Add and Remove reassembles the running bridge.
  • An endpoint without a StableKey is refused with ErrNoStableKey. A second endpoint with the same key is refused with ErrDuplicateKey.

Each stable key keeps its endpoint number. Remove drops a device from the set but reserves its number, and its parts' numbers, for the key's return, across restarts too: an Add of the same key gets them back, and no other device is given them, as a closed matter.js endpoint keeps its number. Forget(ctx, key) frees them — the device is gone for good, and an Add of the key later is numbered like a new device. It erases the values the node stored for the key too (the nonvolatile attributes the module holds, the UserLabel list), so that Add starts from the device's declaration; Remove keeps them.

A device a previous run served and this run has not added yet keeps its stored number too, however long the host's model takes to load: the node never drops a number because its device is absent, as matter.js keeps every stored number until its endpoint is deleted. Forget is the one call that frees a number.

Once a device is added, it has a lifecycle of its own: Device.SetReachable(ctx, false) reports it unreachable (the bridged device's Reachable attribute and its ReachableChanged event), Device.Rename(ctx, name) changes the NodeLabel a controller sees, and Device.EndpointNumber returns the endpoint the node gave it. SetReachable, Rename and Device.Update return an error: device.ErrNotBridged on a part, whose node serves no reachability or label of its own, and from Rename the store's refusal to persist the label, which is then not served. Node.Topology() is what the node serves: the Aggregator's endpoint and every bridged device with its key, endpoint, device type, name and reachability. The host's view walks through a program that uses each. Node.Endpoints() is the same tree as a controller sees it: every endpoint — the root and the Aggregator included — by number, with its parent and the PartsList, DeviceTypeList and ServerList its Descriptor serves.

Source: node/aggregator.go (Aggregator), device/lifecycle.go, node/ (Topology, BridgeTopology, Endpoints), examples/reference-bridge/fleet_node.go (attachNodeProviders, endpointByKey).

Commissioning

Node.SetupPayload returns the QR payload and the 11-digit manual code for the configured passcode and discriminator. When Start loads no fabric from the store, it opens the node's own commissioning window. A commissioned node opens a window only when a controller asks for one through AdministratorCommissioning, when you call Node.OpenBasicWindow with fresh credentials, or when you call Node.OpenOwnWindow with the configured ones (a timeout of 0 is 15 minutes once the node has a fabric).

Node.SetCommissioningBlocked(ctx, err) refuses every new commissioning while err is non-nil and ends one under way (its PASE sessions close, the fail-safe armed over PASE expires, an open window is revoked), and controllers that are already paired keep working. A host calls it before Start when, for example, it cannot serve its configured attestation chain.

Source: node/inspect.go (Node.SetupPayload), node/node.go (Node.Start), node/commissioning.go (Node.OpenBasicWindow), node/node.go (Node.SetCommissioningBlocked).

Time synchronization

The root's TimeSynchronization serves the node's UTC: UTCTime, Granularity and TimeSource. Config.TimeSynchronization.Config adds the features after connectedhomeip (TimeSynchronizationCluster.cpp at 6170af84; matter.js's server is the generated behaviour):

Feature Attributes and commands What the host supplies
TZ TimeZone (one default entry, offset 0), DSTOffset, LocalTime (UTC plus the zone's and the DST offset in effect, null without a DST list), TimeZoneDatabase, the two list sizes (2); SetTimeZone with SetTimeZoneResponse, SetDSTOffset; the events DSTTableEmpty, DSTStatus and TimeZoneStatus TimeZoneDatabase (nil is None) and, with a database, DSTOffsetsFor, which answers SetTimeZone with the zone's DST offsets
NTPC DefaultNTP, SupportsDNSResolve; SetDefaultNTP (an IPv6 address, or a domain when SupportsDNSResolve) SupportsDNSResolve
NTPS NTPServerAvailable NTPServerAvailable, changed later with SetNTPServerAvailable
TSC TrustedTimeSource; SetTrustedTimeSource (null emits MissingTrustedTimeSource); the time client reads the source's UTCTime Config.Client (the node reads the source over its client stack) or a PeerReader; a removed fabric's source is cleared

The node persists TrustedTimeSource, DefaultNTP, TimeZone and DSTOffset in its store. The node's UTC is Config.Clock plus an offset; the host clock is never set:

  • The host clock is the time source until something sets the offset: MillisecondsGranularity and TimeSource MixedNTP while it reads a time past the Matter epoch, as chip's default delegate reports it. PlatformTime says otherwise — a GNSS-disciplined host names its source and granularity, a host whose clock is not trustworthy returns NoTimeGranularity, and UTCTime is then null until a source answers.
  • SetUTCTime sets the offset with chip's checks (HandleSetUTCTime, :1110-1136): INVALID_COMMAND for a granularity or time source outside its enum; TimeNotAccepted for NoTimeGranularity, for a granularity coarser than the current one while the node has a time, or for a time past 32-bit epoch seconds; otherwise SUCCESS, the request's granularity and TimeSource Admin.
  • The time client runs from Node.Start while the node has no time, and again whenever a trusted time source is set then (chip's AttemptToGetTime, :541-593): it reads UTCTime and Granularity from the trusted time source's root endpoint and adopts the time with TimeSource NodeTimeCluster and seconds (minutes for a source of seconds or minutes), for the network delay; failing that it asks DefaultNTP through the host's NTPClient (the module ships none) and adopts the answer with milliseconds and NonMatterSNTP; failing that it emits TimeFailure.

The offset lives in memory: after a restart the node serves its host clock again, where chip's node keeps the time its system clock was set to. GeneralDiagnostics' TimeSnapshot reads the same UTC. The reference daemon turns no feature on.

The node's UTC is also the Matter time of the Thermostat's suggestions (TSUGGEST) and the Valve's AutoCloseTime (TS): the node hands it to them as their endpoints join the topology (AttachMatterTime) and tells them whenever it adopts a time — a valve still counting down sets AutoCloseTime anew, the Thermostat re-evaluates its suggestions. A move of the host clock or of PlatformTime tells nobody. With TimeSynchronization.Off the node has no UTC: suggestions answer INVALID_IN_STATE, and Aggregator.Add and Replace refuse a Valve with TimeSync, naming the endpoint and the cluster, as connectedhomeip's valve refuses TimeSync without the cluster. Other device-side timestamps (event EpochTimestamp, ResourceMonitoring's LastChangedTime, DiagnosticLogs, the energy servers) still read the host clock (issue 445).

Persistence

Config.Store.Path names a SQLite file the node opens itself with modernc.org/sqlite, the pure-Go driver the module already depends on, and closes on Stop — what the reference daemon does. Config.Store.DB is a *sql.DB that you open instead, with a driver of your choice; the store packages import none. node.New applies both schemas (fabrics, credentials, ACL, groups, subscriptions, settings, and endpoint numbers) to the database on every boot; both scripts are idempotent.

Opening a handle yourself, put _pragma=foreign_keys(1) in the DSN. The fabric tables cascade-delete through foreign keys, and SQLite ignores those silently with the pragma off. The pragma must be in the DSN, not in a statement, so that every pooled connection gets it.

The persistence guide lists every table and settings key.

Source: node/config.go (Store), node/store_path.go, node/node.go (openStores, closeOwnedDB).

Stopping

Node.Run(ctx) starts the node, waits for ctx to end, and stops it with a 5-second budget. Node.Stop runs the shutdown in a fixed order:

  1. the OTA requestor stops;
  2. the operational time is stored and the ShutDown event is emitted;
  3. the bindings and client stack close;
  4. PASE, the commissioning window and the CASE reaper stop;
  5. the subscription engine, the group sender, BDX and the health probe stop;
  6. the bridge stops (what each subscription owes is reported, the ShutDown event among it, then the sessions are closed with a CloseSession to each peer, then the socket closes and the mDNS records are withdrawn);
  7. the advertiser closes, and the store the node opened for Store.Path.

Stop is idempotent and safe without Start. A stopped node does not restart: Start after Stop returns node.ErrStopped, and so do OpenOwnWindow, OpenBasicWindow and CloseWindow from the moment Stop begins. To restart, build a new node on the same store. The bridge under it is single-run in the same way: bridge.Bridge.Start after Stop returns bridge.ErrStopped.

New opens the store (and, with Config.Client, the client socket) and starts no goroutine of its own; the subscription engine and the session reapers start in Start. Call Stop on every node that New returned, including one you never started: it releases what New opened. The quickstart does this on its error paths.

Source: node/node.go (ErrStopped), node/node.go (Node.Stop, Node.Run), node/node.go (the Node struct, New), bridge/bridge.go (Bridge.Stop).

What the reference daemon adds

examples/reference-bridge is the facade plus the host's own pieces, each of which is something a product would also decide:

  • Flags for the listen address, TCP, passcode, discriminator, PBKDF parameters, label and log level. Each flag is checked before the node is built.
  • A vendor attestation chain read from a directory instead of the test chain (Attestation.Files).
  • The OTA requestor with an applier that validates and keeps the image. This is the host's OtaApplier.
  • An Actions server on the Aggregator, root FixedLabels and two locales.
  • A fleet of simulated devices, one per surface the module serves, each built from its clusters' declarations (<cluster>def.Declare): the initial state, the features, and the ports the simulated device implements — a valve's StateSource, a washer's CommandHandler, a lock's AuthStore on the node's store. Three clusters are still mounted as a HostServer: the charger's EnergyEvse, whose delegate is not a declared port yet, EcosystemInformation (node.NewEcosystemInformation) and, with --media-messages, Messages. The blind's position is persisted in the settings table.
  • Testing-only flags for certification runs: the app pipe, the TestEventTrigger key, the OTA provider and its ledger check, the simulated Wi-Fi link and the media devices. None of these belongs in a product.

Source: examples/reference-bridge/main.go (parseFlags, checkFlags, run, nodeConfig), examples/reference-bridge/attestation.go, examples/reference-bridge/persist.go.