Getting started: the controller side¶
The controller role pairs Matter nodes onto a fabric this module owns. It
then reads, writes, invokes and subscribes on those nodes. It entered the
module in stages under ADR 0020
and lives under controller/. This page builds the stack, pairs a node and
uses it. The program is examples/quickstart-controller/main.go. The
complete tool, with every command, is examples/reference-controller.
The stack¶
controller.New(ctx, controller.Config{…}) builds the controller in one
call. It is the role's composition root (ADR 0026 principle 2): it
applies the database schemas and assembles the nine parts in the order
the reference controller's openStack builds them:
| Step | Package | What it is |
|---|---|---|
| Database | store, controller/client/sqlstore |
the settings table and the client images; both schemas applied |
| Certificate authority | controller/ca |
the fabric's root of trust; issues our NOC and every node's |
| Fabric | controller/commissioner (NewFabric) |
our operational identity on the fabric |
| Socket | transport/udp, client/exchange |
one UDP socket; sessions and exchanges with MRP |
| DNS-SD | client/discovery |
the browser for commissionable and operational records |
| Peers | client/peer |
the nodes of our fabrics, with CASE on demand |
| Subscriptions | client/interaction |
the registry of client subscriptions |
| Commissioner | controller/commissioner (New) |
PASE, attestation, CSR, NOC, CommissioningComplete |
| Registry | controller/client |
one image per remote node, persisted |
Controller.Close tears the stack down in reverse; the database stays
the host's. Once Close has begun, the controller's methods answer
closed: Pair, PairDiscovered, Discover, VendorInfo and SetGroupKey return an
error wrapping ErrConfiguration, the accessors (Registry, Nodes,
Peers, Commissioner, …) their zero result; Fabric, Clock, TCP,
Addr and TCPAddr keep their values, and a second Close waits for
the first. Config takes:
DB(required):controller.OpenDB(path)opens a SQLite file with the module's own pure-Go driver (foreign keys on, a 5 s busy timeout, the write-ahead log), so the program imports no driver; a host may open the database itself with the driver of its choice.Attestation(required): the PAA trust store. There is no default, so a controller never trusts the test PAAs by accident.attestation.TestStore()is for development devices;controller.ProductionTrust()is the production set of the DCL snapshot embedded in the module, without the test roots and without a network; a controller that also asks the online ledger layers adcl.CertificateStoreover it withattestation.Trust.Listen,VendorID(0 is the test vendor 0xFFF1),Label,Logger,Node(every client node'sclient.Config).ManualStart: false starts the commissioned nodes, as matter.js's controller connects them on start. A program that only pairs or reads once sets it.ClockandListener: the stack's time source (nil is the system clock) and a UDP socket to serve on in place of openingListen. A test passes both (on a loopback siteListenin place of the socket):fabrictest.Site.ControllerConfig(opts)returns aConfigwired to the site — its network, its DNS-SD answers, its fake clock and a database of its own — so the program's owncontroller.Newruns on the site (see testing in process).CAKey: the certificate authority's root key held outside the database, a P-256crypto.Signer(a key file throughcontroller/ca/keyfile, an HSM, a KMS). nil keeps the root key in the database; with it, a stored root private key leaves the database.
Controller.Registry, Controller.Commissioner, Controller.Fabric and
Controller.Peers are the role's seams
(advanced seams). The reference controller
builds on controller.New: it composes its trust set
(attestation.Trust over the DCL snapshot and the online ledger) into
Attestation, opens its CA key file into CAKey and its socket into
Listener, and pairs through Controller.Pair, over BLE with
PairOptions.BLE. It runs no second node: its group commands send as
the controller's own identity (Controller.Groups) and ota serve serves
images from the controller's own tree (Config.OTA), both under
Fabric().RootNodeID — the "own node" of earlier releases was retired
in v0.18.0.
Source: controller/controller.go, controller/open.go, fabrictest/controller_config.go, examples/reference-controller/cli/stack.go (openStack), examples/reference-controller/cli/self.go, examples/reference-controller/cli/group.go (Controller.Groups), examples/reference-controller/cli/pair.go (cmdPair), examples/quickstart-controller/main.go.
The program¶
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2026 SukramJ.
// Command quickstart-controller is the smallest Matter controller on
// go-fabric: it keeps one fabric in a SQLite file, pairs a node by its QR or
// manual code, reads its NodeLabel, toggles its endpoint 1 OnOff and prints
// the OnOff reports of a subscription until Ctrl-C.
// docs/getting-started/controller.md walks through it; the reference
// controller (examples/reference-controller) is the complete tool.
package main
import (
"context"
"database/sql"
"errors"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"syscall"
"time"
basicinfo "thingfabric.dev/go-fabric/cluster/spec/basicinformation"
onoffdef "thingfabric.dev/go-fabric/cluster/spec/onoff"
"thingfabric.dev/go-fabric/controller"
"thingfabric.dev/go-fabric/controller/attestation"
"thingfabric.dev/go-fabric/controller/client"
)
func main() {
dbPath := flag.String("db", "quickstart-controller.db", "the SQLite file holding the fabric and the paired nodes")
code := flag.String("code", "", "pair the node with this QR (MT:…) or manual code first")
flag.Parse()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
err := run(ctx, *dbPath, *code, nil)
stop()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
// run opens the controller, pairs the node code names — and then uses
// that node — or, without a code, uses the first node an earlier run
// paired. edit, when set, changes the controller's configuration (a test
// injects its DNS-SD cache); the program passes nil.
func run(ctx context.Context, dbPath, code string, edit func(*controller.Config)) error {
db, err := openDB(dbPath)
if err != nil {
return err
}
defer func() { _ = db.Close() }()
c, err := open(ctx, db, "[::]:0", slog.Default(), edit)
if err != nil {
return err
}
defer func() { _ = c.Close(context.WithoutCancel(ctx)) }()
if code != "" {
noSubscribe := false // this program exits; a resident host keeps the default subscription
paired, err := c.Pair(ctx, code, controller.PairOptions{AutoSubscribe: &noSubscribe})
if err != nil {
return err
}
return use(ctx, paired)
}
nodes := c.Nodes()
if len(nodes) == 0 {
return errors.New("no paired node: pass -code")
}
fmt.Printf("Using node %s, the first one paired before\n", nodes[0].ID())
return use(ctx, nodes[0])
}
// openDB opens the SQLite file the controller keeps its fabric in, with
// the module's own driver.
func openDB(path string) (*sql.DB, error) { return controller.OpenDB(path) }
// open builds the controller over the database: the fabric (created on the
// first run, loaded afterwards), the socket, DNS-SD, peers, commissioner,
// registry — one call. The trust store is the CSA's test PAAs, for
// development devices; a production controller passes a DCL-backed one.
// A nil Config.Names opens the DNS-SD cache on the network; edit, when
// set, changes the configuration first.
func open(ctx context.Context, db *sql.DB, listen string, log *slog.Logger, edit func(*controller.Config)) (*controller.Controller, error) {
cfg := controller.Config{
DB: db,
Attestation: attestation.TestStore(),
Listen: listen,
Label: "quickstart",
Logger: log,
ManualStart: true, // the program reads and subscribes itself
}
if edit != nil {
edit(&cfg)
}
return controller.New(ctx, cfg)
}
// use reads, invokes and subscribes through the node's client image.
func use(ctx context.Context, n *client.Node) error {
var read client.ReadRequest
read.Attributes = []client.AttributePath{client.ClusterAt(0, basicinfo.ClusterID)}
if _, err := n.Read(ctx, read); err != nil {
return err
}
// The typed read: the image's values as the generated State.
if info, _ := basicinfo.StateFrom(n.Endpoint(0).Cluster(basicinfo.ClusterID)); info.NodeLabel != "" {
fmt.Printf("NodeLabel: %s\n", info.NodeLabel)
}
toggle := client.CommandAt(1, onoffdef.ClusterID, onoffdef.CmdToggle)
if _, err := n.Invoke(ctx, toggle, onoffdef.ToggleRequest{}, client.InvokeOptions{}); err != nil {
return err
}
sub, err := n.Subscribe(ctx, client.SubscribeRequest{SubscribeRequest: client.SubscribePaths{
Attributes: []client.AttributePath{client.AttributeAt(1, onoffdef.ClusterID, onoffdef.AttrOnOff)},
MaxIntervalCeiling: client.Interval(time.Minute),
Updated: func(r *client.Report) error { // keep it short: it runs on the report's exchange
if _, ok := r.Value(1, onoffdef.ClusterID, onoffdef.AttrOnOff); ok {
st, _ := onoffdef.StateFrom(r.Values(1, onoffdef.ClusterID))
fmt.Printf("OnOff: %v\n", st.OnOff)
}
return nil
},
}})
if err != nil {
return err
}
defer sub.Close()
select {
case <-ctx.Done():
case <-sub.Done():
}
return nil
}
go run ./examples/quickstart-controller -code MT:-24J0AFN00KA0648G00
go run ./examples/quickstart-controller # the same node, next run
With -code the program uses the node Pair returned — on a database
that already holds nodes too, so a second device is not mistaken for the
first; without it, it uses the first node an earlier run paired and says
which.
The test opens the controller twice on one database and checks that the
second run is the same fabric. It also checks that a malformed code is
refused and that a valid code that no device answers ends at the deadline
with controller.ErrNoDevice. It hands the controller a DNS-SD cache on
which nothing answers through controller.Config.Names, the field a nil
value of which opens the cache on the network.
Source: examples/quickstart-controller/main_test.go.
The fabric¶
ca.New with a store keeps the root key and the certificate counter. The
CA saves after every certificate it issues, so serial numbers do not repeat
after a restart. commissioner.NewFabric with a store loads the stored
fabric record (fabric id, our node id, IPK, index, label, key and NOC). It
mints and saves a new record only when the store has none.
controller.New rotates the operational key on every start, as
matter.js's controller does for a fabric it keeps itself
(commissioner.FabricAuthority.DefaultFabric with rotation): a new key
pair and a new NOC from the same CA, under the same fabric id, node id and
CASE Authenticated Tags, saved over the old record. The peers trust the
new NOC as they trusted the old one. An authority rotates a fabric once;
FabricAuthority.CreateFabric mints a new fabric and OnFabricAdded
reports it.
A stored record wins over the configuration. A non-zero FabricID or
RootNodeID that differs from the stored record is ErrFabricMismatch.
That is why controller.New sets both fields to zero once a record exists.
ca.SettingStore keeps the CA under the settings key controller.ca and
the fabric under controller.ca.fabric.
The database therefore holds the fabric's private keys. Anyone with the file controls every node paired to it.
Source: controller/ca/doc.go (package doc), controller/commissioner/fabric.go (FabricConfig), controller/commissioner/fabricauthority.go, controller/ca/persist.go (SettingStore, DefaultSettingKey), examples/reference-controller/README.md (The database).
Pairing¶
Controller.Pair(ctx, code, controller.PairOptions{}) runs the four steps
below. Its OnAttestationFailure defaults to attestation.Reject(), and
AutoSubscribe overrides the registry's default subscription. With a
context without a deadline the search for the device ends after
controller.DefaultPairTimeout (one minute) with ErrNoDevice; the
commissioning of a device that was found is not bounded by it, only by
the commissioner's own budgets and the context — and by
PairOptions.CommissionTimeout when set, which bounds the commissioning
after the search on its own (its end is an error that is
context.DeadlineExceeded).
- Decode the code.
setup.DecodeQRCodereads anMT:payload and gives the long discriminator.setup.DecodeManualCodereads 11 or 21 digits and gives the short discriminator. Both give the passcode. - Find the device.
discovery.NewScanner(names).FindCommissionablecalls back for each device that matches the discriminator. - Make a node.
Registry.ForDevicereturns the registry's node for the discovered device, creating one when needed. - Commission.
Registry.Commissionruns PASE to the device's addresses, then the commissioning flow: ArmFailSafe, device attestation, CSR, NOC, the operational CASE connection, and CommissioningComplete. The record and settings are saved, and the node starts.
Controller.PairDiscovered(ctx, dev, passcode, controller.PairOptions{})
commissions a device a discovery found (Controller.Discover, a
client.Device) with its setup passcode, for a host that has the device
and the passcode but no onboarding code. It runs Pair's pipeline from
step 3: the same attestation policy (OnAttestationFailure, the zero value
rejects), the same progress reports with Discovery 2.1 skipped, the same
diagnostic trace and pair.failures. The device names how it is reached,
so PairOptions.BLE and PairOptions.Address are ErrConfiguration, as
is a device without an address.
CommissionOptions decides the rest:
NodeID: 0 draws a random operational node id that no peer of the fabric has.AutoSubscribe: nil or true keeps the node live through one sustained wildcard subscription. The quickstart turns it off because it exits. It is the default subscription, narrowed byDefaultSubscription(client.SubscribeOptions);Node.Subscribeis a custom one beside it — the default for a host that wants the node's whole image kept,Node.Subscribefor paths of its own with its ownUpdated, or both. Both together needDefaultSubscription.KeepSubscriptions: without it the default subscription asks the node to drop the controller's other subscriptions each time it is (re-)established, and a custom one established withReplaceSubscriptionsdrops the default.NoInitialRead: skips the initial read after commissioning.
PairOptions.Progress (a func(controller.PairingStep)) follows the
pairing step by step: each step is reported PairingStarted, then
PairingSucceeded, PairingFailed with the error, or PairingSkipped.
The steps carry matter.js's numbers and names
(ControllerCommissioningFlow.ts): GetInitialData 0.1,
GeneralCommissioning.ArmFailsafe 7.1,
GeneralCommissioning.ConfigureRegulatoryInformation 8.1,
TimeSynchronization.SynchronizeTime 8.2,
OperationalCredentials.DeviceAttestation 10.1,
OperationalCredentials.Certificates 11.1, AccessControl 15.1,
NetworkCommissioning.Validate, .Wifi and .Thread 16.1 to 16.3 (BLE
or a given network only), Reconnect 18.1 (the operational CASE
connection), GeneralCommissioning.Complete 20.1 and
OperationalCredentials.UpdateFabricLabel 98.1. matter.js names no step
for what comes before its flow; Discovery 2.1 (DNS-SD or BLE, skipped
with PairOptions.Address and by PairDiscovered) and PASE 2.2 are this module's names, and
they are reported first. Subscribe 21.1, also this module's, is
reported last: the node's start, its initial read and default
subscription. A failed step is the last report. The callback runs on Pair's goroutine and must
not block. commissioner.Options.Progress is the same hook one layer
down.
_, err := c.Pair(ctx, code, controller.PairOptions{
Progress: func(s controller.PairingStep) {
log.Printf("%d.%d %s %s %v", s.Number, s.Sub, s.Name, s.Phase, s.Err)
},
})
A Pair or Commission whose context ends — cancelled, or past its
deadline — after the PASE session was established does not leave the
device armed: the device arms its fail-safe when the PASE session is
established, and the commissioner sends ArmFailSafe with expiry 0
over the session the commissioning still has (PASE, or CASE after
Reconnect), on a context of its own for at most 10 s, and returns the
failed step's error as it is. A step that stopped at the ended context
returns an error that matches the context's with errors.Is —
context.Canceled or context.DeadlineExceeded — and is not always
identical to it: a context that ends while Reconnect waits for the
operational connection returns that step's
*commissioner.CommissioningError of kind ErrOperativeConnectionFailed,
which names the device's last report when the device gave one and has
the context's error as its Cause, so both
errors.Is(err, commissioner.ErrOperativeConnectionFailed) and
errors.Is(err, context.DeadlineExceeded) hold. A device left armed
would refuse a new commissioning until the fail-safe ran out. The disarm
does not wait for the device to have answered the ArmFailSafe: a context
that ends while the first one, or a later extension, is still under way
is followed by the disarm too, since the request may have armed the
device (one that holds no fail-safe answers the disarm with success and
nothing happens).
Nothing is sent once the device has confirmed CommissioningComplete, or
on a closed session; a disarm that fails is logged
(matter.controller.commissioning.reset_failsafe_failed) and the
fail-safe then expires on the device by itself. matter.js's flow has no
abort signal; the behaviour follows connectedhomeip's StopPairing
(Ahead of matter.js, BD-chip-Commissioner-AbortDisarmsFailSafe).
A commissioning that fails for any other reason after the PASE session
was established — the device's terms not acknowledged, its attestation
refused, a refused or unanswered command, a node id claim lost to
another candidate — disarms the same way, bounded by the caller's
context and the exchange's response timeout, so cancelling the context
ends the disarm too, or, when that context has already ended, by the
same 10 s as after an abort: the device ends its PASE
session with the fail-safe, and while that session exists it accepts no
new PASE, so without the disarm the next Pair would be refused until
the fail-safe ran out. Nothing is sent when the commissioning channel
dropped or the device stopped responding; a re-arm already sent is
awaited first, and the ArmFailSafeResponse is checked. matter.js ends the
fail-safe the same way after every step failure, once it knows a
fail-safe end, that is once an ArmFailSafe of its own was answered
(#expireFailsafe, mirrored since pin lift b25ed960, P3-D); the disarm
before that answer is this module's;
connectedhomeip disarms after any failure before its network setup.
A PASE session the commissioner does not keep is disarmed before it is
closed as well: one established on a candidate after another candidate
won the connection (an aborted connection returns only once those are
disarmed), and one that EstablishPASE's ContinueAfterPASE refuses.
Source: controller/commissioner/flow.go (execute, callerAborted, disarmAfterAbort, disarmAfterFailure), controller/commissioner/commissioner.go (disarmPASE, giveUpPASE, EstablishPASE), controller/commissioner/connection.go (launch).
A second Commission of a commissioned node is ErrAlreadyCommissioned.
A commission or decommission already running for that node is
ErrFabricOperationInProgress. Registry.Decommission sends RemoveFabric
to the node and then deletes it. If the node refused the removal, or the
removal was not confirmed, Decommission returns that error and keeps the
node.
Registry.UpdateOperationalCertificate replaces a commissioned node's
operational certificate (NOC) with one for a new key pair, as matter.js's
ClientNode.updateOperationalCertificate: under a fail-safe
(CertificateUpdateOptions.Failsafe, 30 s to 0xFFFF s, one minute by
default) the controller verifies the NOC the node reports, has it generate
a CSR, issues the new NOC from the fabric's CA with the node's CASE
Authenticated Tags, sends UpdateNOC and completes the fail-safe on a new
CASE session. It is a fabric operation like Commission and
Decommission: one at a time per node, the others answer
ErrFabricOperationInProgress. A failure is a
*commissioner.CertificateUpdateError: Outcome says whether the node
kept its previous certificate, reverted to it, has the new one in place,
or whether that is unknown (the node then reverts when its fail-safe
expires, unless the fail-safe was completed), and FabricIndexOnPeer the
fabric index the node reported; errors.Is matches
ErrCertificateUpdateBusy (the node's fail-safe may be in use: retry
later) and ErrCertificateUpdateRefused. ctx bounds the waits for a
CASE session and the decision to recover; the commands themselves run to
their response timeouts.
Source: controller/client/fabricops.go (Registry.UpdateOperationalCertificate), controller/commissioner/noc_update.go (Commissioner.UpdateOperationalCertificate, CertificateUpdateError).
A Wi-Fi or Thread device out of the box is found over BLE instead
(ADR 0024):
ble.NewScanner(central).Find matches its advertisement by the same
discriminator, ble.Dial opens the BTP channel, and Registry.Commission
with Options.Channel runs PASE over it, then the network steps with
Options.WiFiNetwork or ThreadNetwork; operational discovery finds the
device over DNS-SD for CASE. While the Reconnect step waits for it, a
device that keeps its commissioning session open (concurrent connection)
is asked over that session what its network state is — its last
networking status, whether its network is connected, its Thread role,
network name and channel, the addresses of its operational interfaces —
first two seconds into the step, then every ten seconds. A change is
logged at Info (matter.controller.commissioning.reconnect_probe); the
routable addresses it reports (not link-local, not Thread mesh-local:
inside its mesh-local prefix or a routing or anycast locator) are
attempted over CASE at port 5540, each once, beside what discovery
delivers
(matter.controller.peer.address_hinted), so a Thread node whose border
router never publishes its operational record is still reached. The
report is the device's own statement and nothing verifies the addresses
in it, so what is taken from it is bounded: 8 operational interfaces —
NetworkInterfaces' list bound — with their at most 8 IPv6 and 4 IPv4
addresses, only addresses that name one other host (no loopback,
unspecified, multicast or IPv4 broadcast address), and at most
peer.MaxHintedAddresses (96, the product) hinted addresses per
connection process however many probes report new ones. A device may
list more than 8 interfaces, loopback and virtual ones among them, so
the 8 are chosen before they are counted: the interfaces with an
address the connection can use (routable as above) come first, in the
device's order, and only the slots they leave go to the others, whose
addresses are logged and not attempted. One address in the report is
more than the device's statement — the one the commissioning session
itself runs on, when the session runs over IP and the address is
routable: the interface that names it is taken before any other, and it
is the first address handed to the connection. What is passed over is
logged: usable interfaces past the eighth with a changed report
(matter.controller.commissioning.reconnect_probe_interfaces_dropped),
addresses past the bound once per connection process
(matter.controller.peer.address_hint_limit).
A Reconnect that fails names the device's last report, for example
the device reports Thread role=Unassigned …, last networking
status=NetworkNotFound. A device that does not answer the probe
changes nothing. The central on Linux is
thingfabric.dev/go-fabric/ble/bluez, a module of its own so the main
module never pulls its D-Bus dependency; the reference controller's BLE
build is its cmd/reference-controller (pair --ble, rights and BlueZ
version in the reference controller's README).
Source: examples/reference-controller/cli/pair.go (parseCode, networkOptions, cmdPair), ble/bluez/doc.go (package doc), controller/client/fabricops.go (CommissionOptions, Registry.Commission, Registry.Decommission), controller/commissioner/commissioner.go (Options), controller/commissioner/doc.go (package doc), controller/commissioner/progress.go, controller/client/registry.go (Registry.allocateIDLocked), controller/commissioner/reconnect_probe.go, client/peer/hint.go.
Attestation and the DCL¶
The commissioner checks the device's attestation against a trust store:
attestation.TestStore()(the quickstart's choice) holds the CSA test PAAs and accepts test certificates, which trusts the Matter test CD signer. It accepts the test devices that the reference bridge and chip-tool present.- A nil store checks without one, as matter.js does without its DCL service.
dcl.OpenCertificateStoreis the opt-in trust store from the CSA Distributed Compliance Ledger. Nothing incontroller/dclreaches the network unless you construct adcl.Clientand hand it over. The ledger then learns the key identifiers of the PAAs, PAIs and CD signers of the devices you attest; no device identity, passcode or fabric key is sent.
The snapshot also names the vendors offline: snapshot.Vendors() and
snapshot.Vendor(id) are the ledger's vendor records it was built with,
over matter.js's static vendors (the test vendors 0xFFF1–0xFFF4 and Nabu
Casa), so a vendor id resolves to a name without the network.
make update-dcl-snapshot refreshes them with the certificates (or alone,
go run ./script/dclsnapshot -vendors-only).
Controller.VendorInfo(ctx) is the vendor information service of a
running controller, matter.js's DclVendorInfoService: seeded from the
snapshot's vendors, refreshed from the ledger at once and daily, the
static vendors under every id the ledger does not name.
InfoFor(vendorID), Vendors() and ProductInfoFor(ctx, vid, pid) (the
ledger's device model as a UI shows it; absent for a product the ledger
does not have) answer; Observe reports every refresh. Config.DCL
(controller.DCLConfig) sets the ledger URL, a dcl.Store that keeps the
fetched vendors, the refresh period, and Offline, which keeps the
service off the network: it then serves the stored, seeded and static
vendors and answers every product as absent. dcl.NewVendorInfoService
builds one without a controller.
What the validator refuses follows matter.js and chip. The DAC and the
PAI must meet their certificate profile (Matter Core §6.2.2.3,
§6.2.2.4): version 3, basic constraints and key usage present and
critical, a PAI a CA with pathLen 0 and key usage keyCertSign and
cRLSign, a DAC no CA with digitalSignature alone; a VendorID or ProductID
attribute in the subject or issuer is exactly four uppercase hex digits
and appears once (the Mvid:/Mpid: commonName is read only when
neither attribute is present). A violation is
PaiFormatInvalid or DacFormatInvalid. The Certification Declaration
must meet its CMS envelope, format_version 1 and a defined
certification type (CertificationDeclarationFormatInvalid), and its
signer must be a CD signer: the CSA signing keys 001–005 and the Matter
test CD signer are built in (attestation.KnownCDSigner); a
dcl.CertificateStore answers for a further signer only with a certificate
the CSA "Matter Certification and Testing CA" issued, which it fetches and
checks (attestation.VerifyCDSignerCertificate), while an
attestation.StaticStore answers with the CD signer keys its host put
there, unverified. A signer neither built in nor known to the store is
CdSignerUnknown. A CD signed by the test
signer under a store that refuses test certificates is a
TrustedAsTestCertificate finding, and an official CD signed by it is
OfficialCdSignedByTestSigner.
PQC Phase 1 — ML-DSA-44 and ML-DSA-65 keys in a PAA and a PAI, ML-DSA
signatures on any attestation certificate, the DAC key on EC P-256 — is
implemented in controller/attestation over the standard library's
crypto/mldsa, but off, as in matter.js: an ML-DSA attestation
certificate is refused with attestation.ErrMLDSAAttestationDisabled
until a released Matter revision carries the feature. Operational
certificates stay EC P-256 either way.
The policy decides what a finding does:
| Policy | Effect on a finding |
|---|---|
attestation.Accept() |
proceeds; each finding is logged |
attestation.Reject() |
rejects the commissioning |
Policy{Decide: …} |
your function decides alone |
zero value Policy{} |
proceeds, with a warning per finding |
The zero value proceeds because matter.js does the same for backward
compatibility. Set the policy explicitly. (controller.Pair sets
attestation.Reject() when its options leave the policy unset.)
A rejection matches commissioner.ErrAttestationRejected through
errors.Is, besides commissioner.ErrCommissioning, so a host tells a
refused device from a network failure.
Source: controller/attestation/doc.go (package doc), controller/attestation/store.go (TestStore), controller/attestation/profile.go, controller/attestation/cdsigners.go, controller/attestation/validate.go, controller/attestation/policy.go (Policy), controller/commissioner/commissioner.go (Context.Attestation), controller/dcl/doc.go (package doc), examples/reference-controller/cli/stack.go (openSnapshot, openTrust, attestationPolicy).
The registry and the device view¶
The client.Registry restores every node its store holds when it is built.
Registry.Start starts the commissioned, enabled nodes only when
RegistryConfig.AutoStart is set. Use these calls to find a node:
| Call | Returns |
|---|---|
Get(id) |
the node with a local id (peer1, peer2, …) |
GetByAddress(fabric.AddressOf(nodeID)) |
the node with a node id |
Commissioned() |
every commissioned node |
A client.Node is the controller's image of the remote node. The
controller has no device model of its own: the remote node's Descriptor
decides the endpoints and the generated cluster definitions decide each
cluster's shape.
| Call | Returns |
|---|---|
Endpoints(), Endpoint(n) |
the image's endpoints |
Endpoint.DeviceType(), Endpoint.Device() |
the device type id, and its definition when known |
Endpoint.Clusters(), Endpoint.Cluster(id) |
the clusters |
<cluster>def.StateFrom(Endpoint.Cluster(id)) |
the cluster's typed State, and the attributes the image lacks |
Cluster.Decoded(attr) |
one attribute value, untyped: a struct as its generated type, any other value at its widest Go type (a uint8 as uint64) |
Cluster.Value(attr) |
the raw TLV tree |
The typed read is the generated StateFrom of each <cluster>def
package. It fills the same State the device side's typed server reads,
through the same generated code, so a value has its attribute's own type.
It takes any spec.Values: a cluster of the image, or one cluster of a
report (Report.Values(endpoint, cluster)).
The image is persisted with controller/client/sqlstore, so a later run
starts from what the last one saw.
Source: controller/client/doc.go (package doc, The data model), controller/client/registry.go (RegistryConfig, NewRegistry, Registry.Start), controller/client/endpoint.go (Endpoint), controller/client/cluster.go (Cluster, Cluster.Decoded, Cluster.Value), examples/reference-controller/cli/pair.go (printDevice).
Read, write, invoke, subscribe¶
All four go through the node and its CASE session. The peer set
establishes CASE when no session is live. Their types are
controller/client's own: AttributePath, CommandPath, EventPath
(built with client.AttributeAt, client.ClusterAt, client.CommandAt,
client.EventAt), ReadRequest, SubscribeRequest, Report,
WriteRequest, InvokeOptions, Result and StatusError. Each type's
doc comment names the fields a host sets.
- Read.
Node.Readapplies the report to the image and returns it. Its paths are promoted fields (req.Attributes = …). UnlessIncludeKnownVersionsis set, the cached data versions go along as filters, so the peer sends only clusters that changed. - Write.
Node.Writetakesclient.WriteRequests, each a path and a value. The value is a generated struct or request, aspec.List, or a scalarspec.Value:spec.Int16(2250),spec.Uint8(20),spec.Uint(onoffdef.StartUpOnOffToggle),spec.Null[uint16]().DataVersionmakes a write conditional. The write goes to the peer only, and the image follows when the peer reports the new value. A write that does not fit one message goes in chunks, each answered by its own WriteResponse, the statuses concatenated; a timed write must fit one. - Invoke.
Node.Invoketakes the command path and the generated request type (onoffdef.ToggleRequest{}).InvokeOptions{Timed: true}sends a TimedRequest first. - Subscribe.
Node.Subscribetakes aclient.SubscribeRequest, which embeds the paths asReadRequestdoes (req.Attributes = …, orclient.SubscribeRequest{SubscribeRequest: client.SubscribePaths{…}});IncludeKnownVersionskeeps the cached versions out of the first and every later request. It applies each report to the image beforeUpdatedsees it.Updatedruns on the goroutine that reads the report, inside the report's exchange, so keep it short. The reference controller hands each report to a channel.Sustainre-establishes a subscription that was lost.Subscription.Closeends it, and so do the node'sCloseandDisable;Doneis closed then. A subscription given up while the peer primes it is answeredINVALID_SUBSCRIPTION, so the device keeps none for it.
Source: controller/client/surface.go, controller/client/interact.go (ReadRequest, Node.Read, Node.Subscribe), cluster/spec/value.go, client/interaction/subscribe.go (SubscribeRequest), client/interaction/handler.go (Subscriptions.handleReport), examples/reference-controller/cli/interact.go (cmdSubscribe).
More of the facade¶
The calls below cover what a resident controller program (a daemon that serves other clients) needs beyond pairing and the four interactions. Each names its matter.js counterpart in its doc comment.
Hooks per node¶
Config.Node.Hooks is one set of hooks for every node.
Config.HooksFor(id) returns the hooks of the node with that local id
instead, so a host attributes a report, an event or a subscription signal
to its node, as matter.js gives each paired node its own events.
The hooks of a subscription report run on the node's ordered job queue,
after the report's StatusResponse, so a hook may block without holding the
peer's exchange. Node.Stop and Node.Close (and with them
Registry.Stop, Decommission, Forget and Close) drain that queue
within their context, so a hook must not call them. A hook still blocked
when the context ends makes them return the context's error: the node is
offline and its flush timer stopped, and the queue runs its jobs to their
end and then the store's final flush as its last job — the stop completes
by itself when the hook returns. A second Node.Stop, Node.Close,
Registry.Stop or Registry.Close waits for it within its own context
and returns nil once it is complete. A database closed before the hook
returned loses that final flush; the write is refused once and not
retried. A node whose stop failed is not erased and stays in the
registry. Node.Start and Node.SetDefaultSubscription wait for the
queue as well, before the cache adopts a fabric filter, and within their
context: a Start that returns the context's error has not started the
node, a SetDefaultSubscription that does has not replaced the default
subscription — the one a started node held has ended — and either call
can be made again.
Source: controller/client/config.go (Hooks), controller/client/node.go (Node.Stop), controller/client/jobs.go.
JSON values¶
A host that speaks JSON to its own clients reads and builds values
without a TLV type. client.Value is the decoded tree the role hands out
(an attribute value, an event's data, a command response's fields);
client.Encodable is what a write or an invoke takes. The type comes from
the generated cluster definitions:
| Call | The type of |
|---|---|
client.AttributeField(cluster, attribute) |
an attribute's value (a global attribute for any cluster) |
client.CommandField(cluster, command) |
a request command's fields |
client.ResponseField(cluster, command) |
a response command's fields |
client.EventField(cluster, event) |
an event's data |
client.DecodeJSON(field, value, form) renders a value in the forms of
matterjs-server's WebSocket API: client.TagBased keys a struct by its
field ids ({"0": true}, the attribute form), client.NameBased by its
camelCase names ({"newPosition": 1}, the form of command fields and
event data); bytes are standard base64, integers JSON numbers (64-bit ones
in full), lists arrays, null a nullable value's null; a member the model
does not name is left out. client.EncodeJSON(field, raw) reads either
key form (names compared without regard to case, or decimal ids) and
base64 bytes; null for an optional member that is not nullable counts as
left out, and a mandatory member a command's fields leave out takes the
specification's fallback, as matter.js's MandatoryDefaultValue computes
it (0, false, empty; an enum stays required). A value of an element no
definition names is untyped: a struct keyed by its context tags. A value
that does not fit is client.ErrJSONValue. Every cluster of the Matter
1.6.1 model has a definition, AccessControl, OperationalCredentials and
GroupKeyManagement included (their servers are hand-written; their
packages carry the definition and the typed state only), so an ACL entry
or a fabric list reads and writes typed. The JSON is written as
JavaScript's JSON.stringify writes it: <, > and & are not escaped,
and there is no trailing newline.
Discovery¶
Controller.Discover(ctx, id, timeout) searches DNS-SD for the
commissionable devices a discovery.Identifier selects
(ByLongDiscriminator, ByShortDiscriminator, ByVendor,
ByVendorProduct, ByDeviceType, ByInstanceID) until the timeout passes
on the controller's clock (0 is 15 minutes, matter.js's default), and
returns every device found, each once. The end of the search is no error.
Controller.DiscoverWith(ctx, id, timeout, controller.DiscoverOptions{First:
true}) returns the first device that answers with an address instead, as
soon as it answers — matter.js's Peers.locate; none before the timeout is
an empty result. The reference controller's discover --first uses it.
Both run on a discovery session of client/discovery, the shape of
matter.js's controller discovery: discovery.FindAll (ContinuousDiscovery:
every device until the timeout, Stop or the context ends; a callback per
device), discovery.FindInstance (InstanceDiscovery: the first device),
and the PASE races discovery.Race, discovery.CommissioningRace and
discovery.PASERace (ParallelPaseDiscovery, CommissioningDiscovery,
PaseDiscovery): every device found gets an attempt, one second apart while
one runs and at most 16 s after it was found, at most 16 at once — a later
one takes the place of the oldest attempt whose device has not answered PASE
yet (discovery.AttemptAnswered) — and the first to establish PASE wins;
the others are cancelled. A session runs
on discovery.Transports — discovery.IPTransport over DNS-SD,
ble.Transport over a BLE scanner — selected by the payload's discovery
capabilities (discovery.SelectTransports: the IP network always, BLE where
the payload names it). Session.Cancel(reason) and the end of the
context interrupt it, Session.Stop ends the search with the result it
has, Session.Wait returns the outcome once every attempt has finished. A
session that ends without a result reports why: ErrDeviceNotDiscovered,
ErrDiscoveryIncomplete (found, but no attempt won and none failed),
ErrNoDiscoveryTransport, or an *AggregateError of the transports' or
the attempts' own errors.
Pairing by address¶
PairOptions.Address (a *net.UDPAddr) pairs a device at that address
without DNS-SD: no advertisement is needed, the code supplies the passcode
and its discriminator is not checked. controller.DeviceAt(addr) is the
client.Device of an address alone — no instance id, no TXT record — and
a supported input of Registry.ForDevice, which creates a new node for
it, as matter.js commissions a knownAddress. Address with BLE is
controller.ErrConfiguration.
Terms and conditions¶
A device that serves GeneralCommissioning's TermsAndConditions feature
refuses CommissioningComplete until the commissioner acknowledged its
terms. PairOptions.TermsAndConditions (a
*commissioner.TermsAndConditionsAcknowledgement{Version, Acknowledgements})
carries the user's acknowledgement; the commissioning sends it with
SetTCAcknowledgements after the regulatory configuration. The information
step reads the device's requirement — TCMinRequiredVersion,
TCAcknowledgementsRequired and TCUpdateDeadline — and when the device holds
no satisfying acceptance and the option is absent or names a lower
version, Pair fails right after that step, before the commissioner arms
the fail-safe or sends AddNOC — it only expires the fail-safe the device
armed with the PASE session, so the next Pair is accepted at once —
with a *commissioner.TermsRequiredError: Version is the
version to acknowledge, Deadline the TCUpdateDeadline in Matter epoch
seconds (nil when null). The error names no acknowledgement bits: a device
serves no attribute naming the bits it requires, so they come from the
terms the host shows. A host shows the terms and pairs again
with the acknowledgement:
_, err := c.Pair(ctx, code, controller.PairOptions{})
var terms *commissioner.TermsRequiredError
if errors.As(err, &terms) {
// show the vendor's terms of version terms.Version, then
_, err = c.Pair(ctx, code, controller.PairOptions{
TermsAndConditions: &commissioner.TermsAndConditionsAcknowledgement{Version: terms.Version, Acknowledgements: accepted},
})
}
Every GeneralCommissioning command the device refuses — ArmFailSafe,
SetRegulatoryConfig, SetTCAcknowledgements, CommissioningComplete — is a
*commissioner.GeneralCommissioningError with the Command and the
device's Code (RequiredTcNotAccepted for a missing bit). Both errors
match commissioner.ErrCommissioning. matter.js and connectedhomeip read
no terms requirement; the early failure is this module's (Ahead of
matter.js, BD-Matter-Commissioner-TermsRequirementRead).
Source: controller/controller.go (PairOptions.TermsAndConditions), controller/commissioner/flow.go (readTerms, checkTerms), controller/commissioner/errors.go (TermsRequiredError, GeneralCommissioningError).
Pairing codes¶
controller.ParsePairingCode(code) decodes a QR code (MT:…) or a manual
code with matter.js's validation: Manual, Version, VendorID,
ProductID, Flow, Capabilities (the discovery bitmap), Discriminator
(the long one of a QR code, the short one of a manual code), Passcode and
HasExtra (the QR code carries TLV data). PairingCode.Identifier() is
the discovery selector. A code it refuses is controller.ErrPairingCode,
and Pair returns the same error for the same code.
The onboarding code inventory¶
A device's QR code or manual pairing code is needed again after a factory reset, and it cannot be read from a commissioned device: the device holds a verifier, not the passcode. The controller can keep the code instead.
Config.KeepOnboardingCodeskeeps the code of every commissioningPaircompletes (client.OnboardingPaired). It is off by default. A code is kept only when the device advertised Basic commissioning mode (CM=1): the code of an Enhanced Commissioning Window (CM=2) was minted by the administrator that opened the window and ends with it, and a pairing byPairOptions.Addresssees no advertisement, so the module cannot tell the two apart — attach that code afterwards.Node.SetOnboardingCode(code)attaches the code printed on a device that is already commissioned — typed, scanned or decoded from a photograph by the host; the module takes the text. The code is validated like a pairing code (client.ErrOnboardingCode) and compared with the node: vendor and product id with its Basic Information (or what it advertised), the discriminator with the one it advertised (a manual code's four bits with the upper four) when it was last seen commissionable in Basic mode — not after an Enhanced Commissioning Window, whose discriminator is the window's, and not for a node paired by address. A difference isclient.ErrOnboardingMismatchand nothing is stored; a side the node does not know is skipped, andOnboardingCode.Checksnames the checks that ran (vendor, product, discriminator — each its own bit). No check proves the passcode — a commissioned device offers no way to test one — so an attached code isclient.OnboardingAttached; attaching the very code the node was paired with leaves it as paired. Nor does a check prove the unit: the code of another device of the same product with the same discriminator passes all three.Node.OnboardingCode()reads it,Node.ClearOnboardingCode()removes it; it is deleted with the node (Forget,Decommission,Erase).Controller.Inventory()lists every commissioned node with its node id, NodeLabel, vendor and product name, serial number and the two forms to show or print:QRCode(MT:…) andManualCode. A stored QR code yields both; a stored manual code yields itself and no QR code, because it carries four of the discriminator's twelve bits and no commissioning flow. Both areclient.SecretCodevalues:Reveal()returns the text. Drawing the QR image is the host's.
The code is a secret: with it and physical access to the device (a factory
reset) anyone can commission it. It is stored in the controller database
beside the fabric's keys and held as a client.SecretCode, which renders
as redacted under every fmt verb, in a log record, in encoding/json
and wherever a TextMarshaler is taken — also inside a host's own struct.
Reveal() is the one way to the text; what a host does with the result
(an export, an API response) needs the protection the database has. See
the security model.
Source: controller/client/onboarding.go, controller/inventory.go,
controller/controller.go (Config.KeepOnboardingCodes),
controller/client/fabricops.go (CommissionOptions.OnboardingCode).
The commissioning window¶
Node.OpenCommissioningWindow(ctx, timeout, client.WindowOptions{}) opens
an enhanced commissioning window on a paired node so another administrator
can add it, as matter.js's openEnhancedCommissioningWindow does: a window
open before is revoked, a random discriminator and passcode are drawn, the
PAKE verifier is derived over a random 32-byte salt at 1000 iterations, and
OpenCommissioningWindow is sent (timed). The client.CommissioningWindow
it returns carries the manual code, the QR code, the passcode, the long
discriminator, the node's vendor and product id and the timeout (0 is
client.DefaultWindowTimeout, 900 s). WindowOptions{Basic: true} opens a
basic window, in which the node takes its own passcode; a node without the
Basic feature is client.ErrNoBasicWindow.
Node.RevokeCommissioningWindow(ctx) closes a window and reports whether
one was open.
Batched invokes¶
Node.Invoke batches by itself when the peer takes more than one path per
InvokeRequest (its MaxPathsPerInvoke): single commands invoked within one
batch window share an InvokeRequest, numbered by CommandRef, and each
caller gets its own answer — matter.js's batcher. The window is
InvokeOptions.BatchDuration; 0 is matter.js's default, the commands
invoked concurrently. Batches form per network profile and go one after
the other; a command for endpoint 0, or one with its own options (timed,
suppressed response, expected processing time, extended fail-safe
timeout, MRP delay, Large Message, NoBatch) goes on its own and at once.
Two commands for one path go into different batches. Cancelling a
command's context abandons that command only; the batch's exchange stops
once every command in it is abandoned.
Node.InvokeBatch(ctx, []client.CommandRequest, opts) sends several
commands and returns one Result per command, in their order. The
commands go in batches of the peer's Node.MaxPathsPerInvoke() (its
session parameters; 1 when it reported none), each batch on an exchange of
its own, in parallel, as matter.js splits an invoke. A command's own status
is its Result.Status — NoCommandResponse for a command the peer did not
answer — and not an error; the error is an exchange that failed.
OTA push¶
controller.Config.OTA (controller.OTAConfig) runs matter.js's
software-update manager: Controller.SoftwareUpdates() is a
softwareupdate.Manager — AddUpdateConsent queues a node's update and
announces the provider to it, ForceUpdate announces at once,
RemoveConsent cancels, QueryUpdates and CheckForUpdates look for
updates in the softwareupdate.Images store and the DCL ledgers (a product
whose check fails is passed over; its failure joins the returned error
as a *softwareupdate.ProductCheckError naming the product and its nodes,
which softwareupdate.ProductCheckErrors lists; the error is nil only when
every product's check succeeded, while the updates found for the others are
still returned), QueuedUpdates shows the queue. The provider is the controller itself: the
OTA provider server sits at controller.OTAProviderEndpoint of the
controller's own endpoint tree, served as RootNodeID over the sessions the
controller holds (matter.js's provider on the controller's node), and the
announced provider is that identity; Controller.BDX() is its transfer
responder. The update needs the node's default subscription: the manager
judges a node on current data only.
Manager.Observe(fn) reports the manager's state as it moves, as a
softwareupdate.UpdateEvent with the peer, the target and, where it
applies, an error. UpdateAvailable, UpdateApplying, UpdateDone and
UpdateFailed are matter.js's updateAvailable, updateApplying,
updateDone and updateFailed. UpdateConsentChanged (a consent added,
removed or expired, or dropped with its node), UpdateCheckFinished (a check's end, with the nodes it
found an update for), UpdateQueued (an update entered the queue) and
UpdateTransferStarted (the node began downloading it, once per update,
not again for a retry) are this module's own. One update reports queued,
transfer started, applying, then done or failed. A failed update carries
ErrNotApplied or ErrUpdateCancelled. Events arrive in order on a
goroutine of the manager's that holds none of its locks, so fn may call
back into the manager. The returned function unsubscribes and is
idempotent. The OTAConfig.OnUpdate… callbacks remain.
The queue follows matter.js's phases: an update is queued, announcing,
announced or in progress; a failed update stays queued. An announcement the node does not answer is aborted
after 15 minutes, and a failed one is retried by the queue run every five
minutes. A failed update keeps its consent and its queue entry for 24
hours and is not announced again; QueuedUpdates does not list it, and
UpdateFailed is reported once per consent. After the 24 hours, or when
the node is deleted, the update ends without an event. AddUpdateConsent
and ForceUpdate answer ErrNoNode (an ErrNotApplicable) for an
address no node has. With AllowTestImages off the update check reports
and QueryImage offers stored production images only.
Source: controller/softwareupdate/manager.go (updatePhase, unlock, runAnnouncement), controller/softwareupdate/images.go (applicable).
images := softwareupdate.NewImages(softwareupdate.ImagesConfig{})
c, err := controller.New(ctx, controller.Config{ /* … */
OTA: &controller.OTAConfig{Images: images, AllowTestImages: true},
})
_, _ = images.Store(ctx, image, softwareupdate.ModeLocal, nil)
_, err = c.SoftwareUpdates().AddUpdateConsent(ctx, peer, softwareupdate.Target{
VendorID: 0xFFF1, ProductID: 0x8000, TargetSoftwareVersion: 2,
})
A store without a ledger offers stored images only. ImagesConfig.Ledger
(a dcl.OTAVersions with a dcl.Client for the production ledger, the
test-net ledger or both) turns the ledger lookups and the downloads on:
DownloadUpdate fetches the image a ledger record names, or the one a URL
names after UpdateInfoFromURL has read its header (only the header: that
download ends once the header is in), into memory, verified before it
is stored — unless the store's Blobs type itself implements
softwareupdate.BlobStreamer (MemoryBlobs does not): DownloadUpdate then
writes the image into the backend as it arrives, verifies it by reading it
back, removes it when a check fails, and serves BDX transfers from the
backend in place; the image is offered to no node before its checks pass. No download passes dcl.OTAVersions.MaxImageSize — 0 is
dcl.DefaultMaxImageSize, 256 MiB. The size a ledger record announces is
the vendor's statement and does not raise the bound: a record that
announces more is refused before the request, an answer longer than its
announcement is cut there, and an answer without an announced size is cut
at the bound. All three refusals are a *dcl.OTAError that names the
bound (the cut at the announcement names the announced size too) and
matches dcl.ErrOTAImageTooLarge (and softwareupdate.ErrOTA from the
store). matter.js has no such bound; it streams the answer to storage.
images := softwareupdate.NewImages(softwareupdate.ImagesConfig{
Ledger: &dcl.OTAVersions{
Client: dcl.NewClient(dcl.ProductionURL),
MaxImageSize: 64 << 20, // this host's products ship smaller images
},
})
Where an image comes from decides how it is fetched and checked. A ledger
record's image is fetched over https: only and, unless the dcl.Client
carries the host's own HTTPClient, from a public address only: a
loopback, private, link-local, unspecified or multicast destination is
refused when it is dialled, for the URL and each redirect hop
(dcl.Client.AllowPrivateDestinations admits them for a lab; a test-net
record is downloaded through the ledger's TestClient, so that client's
HTTPClient and switch apply). The environment's proxy stays in use: a URL
or redirect hop whose host is localhost or an IP address of those classes
is refused before it is handed to the proxy (the host as net/http sends it,
an IPv4 address in any inet_aton-style spelling included), and a host name
sent through the proxy is the proxy's to resolve and connect to. A ledger image must
also be bound to the record's whole-file checksum: DownloadUpdate refuses
a record without one — production or test-net ledger — with
softwareupdate.ErrOTA and the warning dcl.ota.no_checksum before it
downloads anything. The store keeps each stored image's provenance (a
.origin record beside it: the host, or the ledger with the checksum the
image was checked against), and a stored prod or test image that is not
bound to a checksum — stored from a record without one, or stored before
the store kept provenance — is not offered by CheckForUpdate, reused by
DownloadUpdate or opened for a transfer; the file is kept. Such an image
without a record is bound, without a new download, the first time a ledger
update with the checksum reuses it. ImagesConfig.AllowUnverifiedLedgerImages
admits these images and logs each admission
(dcl.ota.no_checksum_admitted). An image the host supplies itself —
UpdateInfoFromURL (dcl.OTAVersions.DownloadHostURL),
UpdateInfoFromImage, a local image, or Images.Store without a ledger
record — may come over http: from any address and needs no checksum.
Source: controller/dcl/ota.go (OTAVersions.Download, OTAVersions.DownloadHostURL), controller/dcl/client.go (Client.AllowPrivateDestinations, newGuardedClient), controller/softwareupdate/images.go (Images.DownloadUpdate, Images.UpdateInfoFromURL, ImagesConfig.AllowUnverifiedLedgerImages).
TCP¶
controller.Config.TCP turns the TCP initiator on (Outgoing) and a TCP
listener (Incoming): a peer that advertises a TCP server and accepts TCP
in its session parameters is reached over TCP when the controller prefers
it (Config.TransportPreference) or an interaction carries a large message
(ClientRequest.LargeMessage; an invoke that leaves it nil sets it when one
of its commands has matter.js's Large Message quality, as
schema.CommandLargeMessage reports it); the sessions of a dropped connection close. Controller.TCPAddr() is the listener's
address. TCPConfig.MaxInboundConnections bounds the connections the
listener holds in all (zero is 256; a negative value is
ErrConfiguration): at the bound a new connection takes the place of the
held one idle longest past the 5-minute grace, or is closed
(Limits).
Network profiles¶
controller.Config.Networks sets the network profiles a peer's
connections, exchanges and address probes are throttled by, per medium
(peer.DefaultTemplates: fast, wifi, thread, conservative, unknown,
unlimited, icdLit), and
OwnNetworkProfile the MRP margin our own messages carry. A peer of
unknown medium gets the conservative limits; an await-mode LIT ICD goes on
the unthrottled icdLit profile.
The commissioner advertisement¶
controller.Config.Advertise (controller.Advertise{Name, DeviceType,
VendorID, ProductID, PrivacyMasked}) publishes the controller's
_matterd._udp record, so a device's commissioner discovery finds it.
Completing a commissioning¶
Registry.CompleteCommissioning(ctx, nodeID, client.CompleteOptions{…})
finishes a commissioning another commissioner ran up to its operational
hand-off (commissioner.Options.FinalizeCommissioning): the node is
created on the shared fabric, started, and sent CommissioningComplete; any
failure before an Ok deletes it.
The fabric label¶
Registry.SetFabricLabel(ctx, label) renames our fabric at run time:
the label (at most 32 characters, else commissioner.ErrLabel) is saved
with the fabric record (commissioner.Fabric.SetLabel), and every
connected node gets UpdateFabricLabel at once; a node that is not
connected gets it at its next start. A node that refuses the name because
another of its fabrics carries it is commissioner.ErrFabricLabelConflict;
the errors of the nodes not updated are joined. Fabric.CurrentLabel()
reads the label.
The default subscription per node¶
Node.SetAutoSubscribe(ctx, on) switches a node's sustained default
subscription on or off and stores the choice with the node's settings: a
started node establishes or closes the subscription at once, a stopped one
follows the choice at its next start, as matter.js's autoSubscribe state
does. Node.AutoSubscribe() reads it.
The specification version¶
Node.Properties().Specification() decodes the node's BasicInformation
SpecificationVersion into a client.SpecVersion (Major, Minor,
Patch, Reserved); String() renders it as "1.4.0", Uint32()
gives the attribute value back for comparisons, and client.SpecVersionOf
decodes a value a host holds. An unknown or zero version reports false.
Pairing over BLE¶
PairOptions.BLE is a Bluetooth LE central (ble/bluez on Linux,
ble/esphome through ESPHome Bluetooth proxies — guide —,
controller/ble/bletest in a test): Pair then searches over BLE and
DNS-SD at once — BLE where the code names it (a QR code's discovery
capabilities) or names nothing (a manual code) — and commissions the
first device to establish PASE, over whichever transport it was found
on; the other attempt is cancelled (matter.js's parallel PASE race). Over
BLE it runs PASE over BTP, and the network steps provision
PairOptions.WiFi or PairOptions.Thread before CASE finds the device on
the network. A device on BLE has no network yet, so one of the two is
required. PairOptions.WiFi and Thread also provision a device found
over DNS-SD that advertises Wi-Fi or Thread. While both transports search,
PairOptions.Progress reports the sub-steps Discovery.IP and
Discovery.BLE of Discovery 2.1: each started, then the winner's
succeeded and the other's skipped (or failed with its search's error).
Thread datasets¶
thread.DecodeDataset(b) (package thread) reads a Thread
operational dataset, as matter.js's OperationalDataset.decode does:
NetworkName, ExtPANID, Channel, PANID and every other MeshCoP TLV;
DecodeDatasetHex takes hex, and Redact drops the secrets for a log
line. The commissioner provisions the dataset as bytes
(commissioner.ThreadNetwork).
Diagnostics¶
Controller.SessionDiagnostics() is a snapshot of the controller's
sessions and peers (each peer's connection state, address, DNS-SD names,
ICD Check-Ins and session ids), Controller.DiagnosticEvents() and
Controller.OnDiagnosticEvent(fn) its bounded trace (pairing, session,
discovery, reachability, icd, ota, camera; Config.Diagnostics sizes it),
and Controller.DiagnoseMDNS() its DNS-SD findings, among them
no_operational_names when the browse gets no answer.
Config.Metrics takes the contract.Metrics port. The shapes are package
diag's, the ones the node serves; the
observability guide
describes each.
Source: controller/controller.go, controller/code.go, controller/client/window.go, controller/client/interact.go, controller/client/label.go, controller/commissioner/fabric.go, client/interaction/invoke_batch.go, controller/facade_test.go, controller/diagnostics.go, controller/metrics.go.
What is not here yet¶
BLE on macOS and Windows (ADR 0024 decision 6) is outside the current
stages. Group messages and OTA images come from the controller's own
identity (Controller.Groups, Controller.SetGroupKey, Config.OTA); the
reference controller's group and ota commands use them.
Source: controller/ota.go, controller/tcp.go, controller/advertise.go, controller/softwareupdate, controller/ota_provider.go, controller/groups.go, controller/serve.go, client/peer/network.go, controller/client/complete.go, examples/reference-controller/README.md (The controller's own identity).