Documentation
¶
Overview ¶
Package client is the controller's image of a remote node (ADR 0020, stage 4, first half): what the node reports, kept as endpoints and clusters, cached and persisted, and kept live by one sustained subscription. It is the port of matter.js packages/node/src/ at 0ceb202d: node/ClientNode.ts and node/ClientNodeLifecycle.ts (the node and its connection state), node/client/ClientStructure.ts (the tree the peer's Descriptor describes), node/client/PeerBehavior.ts (the shape of a cluster), node/client/ClientNodeInteraction.ts (read, subscribe, write and invoke through the image), node/client/ClientEventEmitter.ts (events), the subscription and connection-state half of behavior/system/network/NetworkClient.ts, storage/client/ (the cache and its persistence) and node/NodePhysicalProperties.ts with protocol/src/peer/PhysicalDeviceProperties.ts (the physical properties and the subscription interval bounds).
The data model ¶
ADR 0020 decision 6: the controller has no device model of its own. A Node knows nothing of a remote node but what the node reports — the Descriptor's DeviceTypeList, ServerList and PartsList decide the tree, a cluster's global attributes decide its shape — and its typed side is the module's one data model: the generated cluster/spec definitions and the schema/ tables. matter.js builds a TypeScript class per discovered cluster shape (PeerBehavior.ts:105-139); Go has no run-time types, so a Cluster carries the analysis of that shape (PeerBehavior.ts:422-467) and its values stay spec.Node, decoded on access through the definition (Cluster.Decoded, spec.DecodeValue).
A cluster is known when spec.Lookup has its definition (this package links every generated definition), named when only schema.ClusterName has it — it carries its name and untyped values — and unknown otherwise, named "Cluster$<hex>" as matter.js names it (PeerBehavior.ts:399-401, :426-427).
The registry ¶
Registry is matter.js Peers (node/client/Peers.ts) with the per-node half of CommissioningClient and NetworkClient's fabric-label reconciliation: it restores every node a Store holds, allocates the local ids, finds or creates a node for a discovered device (Registry.ForDevice) or a peer address (Registry.ForAddress), commissions and decommissions through the node one fabric operation at a time, culls expired commissionable nodes and addresses, and reacts to the peer's BasicInformation leave, shutDown and startUp. A node's commissioning record (Record) is stored beside its settings. controller/client/sqlstore is a durable Store. Each node the registry holds has an ICDClient (Node.ICD): the controller's Check-In registration on an ICD peer, its receipt of the peer's Check-Ins, the key refresh and the peer's wakefulness.
Not here ¶
Groups, split commissioning, matter.js's discovery runners (the host runs discovery.Scanner and hands the registry a device), TCP and the transport preference, matter.js's remote API (applyWireChanges), writes through the cache (RemoteWriter.ts) and generated client behaviour types. Writes go to the peer; the image follows when the peer reports the new value.
Index ¶
- Constants
- Variables
- func AssertSingleAdmin(vendorIDs, ignored []uint16, allowMultiAdmin bool) error
- func DecodeJSON(f Field, v Value, form Form) (json.RawMessage, error)
- func HoldUntilICDPeerAwake(ctx context.Context, w *icd.PeerWakefulness, peer PeerAddress, ...) error
- func Interval(d time.Duration) *time.Duration
- func WithICDAwaitTimeout(ctx context.Context, d time.Duration) context.Context
- type AdvertisedIntervals
- type AttributeData
- type AttributePath
- type AttributeStatus
- type CertificateUpdateOptions
- type Cluster
- func (c *Cluster) AcceptedCommands() []uint32
- func (c *Cluster) AttributeList() []uint32
- func (c *Cluster) AttributeListReported() bool
- func (c *Cluster) Decoded(attr uint32) (any, error)
- func (c *Cluster) Definition() *spec.Cluster
- func (c *Cluster) Extra() (attrs, cmds []uint32)
- func (c *Cluster) FeatureMap() uint32
- func (c *Cluster) Features() []string
- func (c *Cluster) GeneratedCommands() []uint32
- func (c *Cluster) ID() uint32
- func (c *Cluster) Name() string
- func (c *Cluster) Ready() bool
- func (c *Cluster) Revision() uint16
- func (c *Cluster) Supports(attr uint32) bool
- func (c *Cluster) SupportsCommand(cmd uint32) bool
- func (c *Cluster) Value(attr uint32) (spec.Node, bool)
- func (c *Cluster) Version() (version uint32, ok bool)
- type CommandPath
- type CommandRequest
- type CommissionOptions
- type CommissioningWindow
- type CompleteOptions
- type Config
- type ConformanceReport
- type ConformanceStatus
- type ConnectionState
- type DataVersionFilter
- type Device
- type DeviceTypeViolation
- type Encodable
- type Endpoint
- func (e *Endpoint) Classification() string
- func (e *Endpoint) Cluster(id uint32) *Cluster
- func (e *Endpoint) Clusters() []*Cluster
- func (e *Endpoint) Conformance() ConformanceReport
- func (e *Endpoint) Device() *fabricdevice.Type
- func (e *Endpoint) DeviceRevision() (revision uint16, ok bool)
- func (e *Endpoint) DeviceType() uint32
- func (e *Endpoint) Installed() bool
- func (e *Endpoint) Name() string
- func (e *Endpoint) Number() uint16
- func (e *Endpoint) Owner() *Endpoint
- func (e *Endpoint) Parts() []*Endpoint
- type EventData
- type EventMinimumNumber
- type EventPath
- type EventStatus
- type Field
- type Form
- type Hooks
- type ICDCheckIn
- type ICDClient
- func (c *ICDClient) Available() bool
- func (c *ICDClient) Awake() bool
- func (c *ICDClient) Forget(ctx context.Context) error
- func (c *ICDClient) LastCheckInAt() (time.Time, bool)
- func (c *ICDClient) NextExpectedCheckIn() (time.Time, bool)
- func (c *ICDClient) OnAvailableChanged(fn func(bool)) func()
- func (c *ICDClient) OnCheckIn(fn func(ICDCheckIn)) func()
- func (c *ICDClient) OnCheckInMissed(fn func()) func()
- func (c *ICDClient) OnKeyRefreshed(fn func()) func()
- func (c *ICDClient) OnRegistered(fn func()) func()
- func (c *ICDClient) OnUnregistered(fn func()) func()
- func (c *ICDClient) PeerSupportsLIT() bool
- func (c *ICDClient) Register(ctx context.Context, opts ICDRegisterOptions) error
- func (c *ICDClient) Registered() bool
- func (c *ICDClient) Registration() (ICDRegistration, bool)
- func (c *ICDClient) StayActive(ctx context.Context, d time.Duration) (time.Duration, error)
- func (c *ICDClient) Unregister(ctx context.Context) error
- func (c *ICDClient) Wakefulness() *icd.PeerWakefulness
- type ICDMultiAdminError
- type ICDPeerAsleepError
- type ICDRegisterOptions
- type ICDRegistration
- type InvokeOptions
- type MemoryStore
- func (m *MemoryStore) EraseCluster(nodeID string, ep uint16, cluster uint32) error
- func (m *MemoryStore) EraseEndpoint(nodeID string, ep uint16) error
- func (m *MemoryStore) EraseNode(nodeID string) error
- func (m *MemoryStore) Load(nodeID string) ([]StoredEndpoint, error)
- func (m *MemoryStore) NodeIDs() ([]string, error)
- func (m *MemoryStore) Save(nodeID string, ep uint16, cluster uint32, values map[uint32][]byte, ...) error
- type NetworkAddress
- type Node
- func (n *Node) AutoSubscribe() bool
- func (n *Node) ClearOnboardingCode() error
- func (n *Node) Close(ctx context.Context) error
- func (n *Node) ConnectionState() ConnectionState
- func (n *Node) DefaultSubscription() *SubscribeOptions
- func (n *Node) Disable(ctx context.Context) error
- func (n *Node) Disabled() bool
- func (n *Node) Enable(ctx context.Context) error
- func (n *Node) Endpoint(number uint16) *Endpoint
- func (n *Node) Endpoints() []*Endpoint
- func (n *Node) Erase(ctx context.Context) error
- func (n *Node) EventHistory(since uint64, limit int) []RecordedEvent
- func (n *Node) ICD() *ICDClient
- func (n *Node) ID() string
- func (n *Node) IntervalBounds(floor, ceiling *time.Duration) (minFloor, maxCeiling time.Duration)
- func (n *Node) Invoke(ctx context.Context, path CommandPath, fields spec.Encodable, ...) (Result, error)
- func (n *Node) InvokeBatch(ctx context.Context, cmds []CommandRequest, opts InvokeOptions) ([]Result, error)
- func (n *Node) IsCommissioned() bool
- func (n *Node) LITSupported() bool
- func (n *Node) LoadError() error
- func (n *Node) MaxPathsPerInvoke() int
- func (n *Node) OnboardingCode() (code OnboardingCode, ok bool)
- func (n *Node) OpenCommissioningWindow(ctx context.Context, timeout time.Duration, opts WindowOptions) (CommissioningWindow, error)
- func (n *Node) PeerAddress() (addr PeerAddress, ok bool)
- func (n *Node) PingAddress(ctx context.Context, addr netip.AddrPort) (time.Duration, error)
- func (n *Node) Properties() Properties
- func (n *Node) Read(ctx context.Context, req ReadRequest) (*Report, error)
- func (n *Node) Record() Record
- func (n *Node) RevokeCommissioningWindow(ctx context.Context) (open bool, err error)
- func (n *Node) Seeded() bool
- func (n *Node) SetAutoSubscribe(ctx context.Context, on bool) error
- func (n *Node) SetDefaultSubscription(ctx context.Context, o *SubscribeOptions) error
- func (n *Node) SetOnboardingCode(code string) (OnboardingCode, error)
- func (n *Node) Start(ctx context.Context) error
- func (n *Node) Stop(ctx context.Context) error
- func (n *Node) Subscribe(ctx context.Context, sr SubscribeRequest) (*Subscription, error)
- func (n *Node) SubscriptionActive() bool
- func (n *Node) Write(ctx context.Context, writes []WriteRequest, opts WriteOptions) (WriteStatuses, error)
- type OnboardingChecks
- type OnboardingCode
- type OnboardingMismatchError
- type OnboardingSource
- type PeerAddress
- type Properties
- type ReadPaths
- type ReadRequest
- type Record
- type RecordedEvent
- type Registry
- func (r *Registry) Close(ctx context.Context) error
- func (r *Registry) Commission(ctx context.Context, n *Node, o CommissionOptions) error
- func (r *Registry) Commissioned() []*Node
- func (r *Registry) CompleteCommissioning(ctx context.Context, nodeID uint64, o CompleteOptions) (*Node, error)
- func (r *Registry) Decommission(ctx context.Context, n *Node) error
- func (r *Registry) Erase(ctx context.Context)
- func (r *Registry) ForAddress(addr PeerAddress, id string) (*Node, error)
- func (r *Registry) ForDevice(ctx context.Context, d Device, id string) (*Node, error)
- func (r *Registry) Forget(ctx context.Context, n *Node) error
- func (r *Registry) Get(id string) *Node
- func (r *Registry) GetByAddress(addr PeerAddress) *Node
- func (r *Registry) Nodes() []*Node
- func (r *Registry) SetFabricLabel(ctx context.Context, label string) error
- func (r *Registry) Size() int
- func (r *Registry) Start(ctx context.Context) error
- func (r *Registry) Stop(ctx context.Context) error
- func (r *Registry) UpdateOperationalCertificate(ctx context.Context, n *Node, o CertificateUpdateOptions) error
- type RegistryConfig
- type Report
- type Result
- type SecretCode
- type SessionParameters
- type SpecVersion
- type StatusError
- type Store
- type StoredCluster
- type StoredEndpoint
- type SubscribeOptions
- type SubscribePaths
- type SubscribeRequest
- type Subscription
- type SupportedTransports
- type Timing
- type Value
- type WindowOptions
- type WriteOptions
- type WriteRequest
- type WriteStatus
- type WriteStatuses
Constants ¶
const ( // DefaultTTL is the lifespan of a discovered address or node whose // TTL is unknown (DEFAULT_TTL, Peers.ts:73). DefaultTTL = 15 * time.Minute // ExpirationInterval is the period of the cull (EXPIRATION_INTERVAL, // Peers.ts:74). ExpirationInterval = time.Minute )
The address book's lifespans — node/client/Peers.ts:78-79 at db021da0.
const DefaultEventHistory = 100
DefaultEventHistory is the number of events a node keeps (Node.EventHistory) when Config.EventHistory is 0.
const DefaultMaxImageBytesPerNode = 32 << 20
DefaultMaxImageBytesPerNode is the image quota of a node when none is configured (RegistryConfig.MaxImageBytesPerNode): the bytes one node's image is charged — its attribute values in their stored form and, for each endpoint, cluster, attribute and TLV element, what the entry holds in memory (imageEndpointBytes and its siblings) — so that it bounds the image's heap and its store's rows, not only the values' bytes. Module's own (review II, R2-P3-ctl-dev-02, owner decision 54; R2-P3-dr-ctl-02): matter.js bounds neither what a peer's reports store nor their sum (ClientStructure.ts:568-610, :1147-1193 at db021da0). The value is chosen (decision 59), sixteen times the 2 MiB report bound of then; since decision 220 interaction.DefaultMaxReportBytesPerSession is 16 MiB of charged memory, half of this quota.
const ( // DefaultWindowTimeout is the window a [Node.OpenCommissioningWindow] // of timeout 0 opens: openEnhancedCommissioningWindow's and // openBasicCommissioningWindow's Seconds(900) // (packages/node/src/behavior/system/commissioning/CommissioningClient.ts:486, :508). DefaultWindowTimeout = 900 * time.Second )
Commissioning window parameters, as matter.js chooses them at 862ad75f.
const MinLITSpecificationVersion uint32 = 0x0104_0000
MinLITSpecificationVersion is the lowest Matter specification version (BasicInformation SpecificationVersion, 0xMMmmpprr) a peer must report for its LIT support to be trusted: 1.4.0. Mirrors matter.js IcdClient.ts:961 (MIN_LIT_SPECIFICATION_VERSION).
const UnknownDeviceType uint32 = math.MaxUint32
UnknownDeviceType is the device type of an endpoint whose Descriptor has not named one — matter.js EndpointType.UNKNOWN_DEVICE_TYPE, DeviceTypeId(-1) (node/src/endpoint/type/EndpointType.ts:43 at b25ed960).
Variables ¶
var ( // ErrUntyped: the value has no type to decode it by — an attribute of a // named or unknown cluster, or one the definition does not know. The // node comes with it. ErrUntyped = spec.ErrUntyped // ErrNoValue: the image holds no value of the attribute. ErrNoValue = errors.New("client: no value") )
Errors of Cluster.Decoded.
var ( // ErrDisabled: Start of a disabled node — matter.js // ClientNetworkRuntime throws (ClientNetworkRuntime.ts:38-43). ErrDisabled = errors.New("client: node is disabled") // ErrClosed: the node was closed. ErrClosed = errors.New("client: node is closed") // ErrConfig: an invalid Config. ErrConfig = errors.New("client: invalid config") // ErrLoadFailed: a stored node that failed to load — [Node.LoadError] // and its Start; the registry keeps it so its id stays visible // (Peers.ts:144-161 at db021da0). ErrLoadFailed = errors.New("client: node is unavailable because it failed to load") )
Errors of a Node.
var ( // ErrPeerLeft: the peer left the fabric — the cause its sessions are // given up with after a decommission or a leave event. ErrPeerLeft = errors.New("client: peer has left the fabric") // ErrPeerShutdown: the peer reported a shutdown. It is transient // (errors.Is against exchange.ErrTransient), as matter.js's class // extends TransientPeerCommunicationError. ErrPeerShutdown error = peerShutdownError{} // ErrFabricRemoved: this node is no longer a member of the session's // fabric — matter.js FabricRemovedError // (protocol/src/peer/PeerCommunicationError.ts:96-103 at db021da0), the // cause Fabric.delete force-closes the fabric's sessions with // (protocol/src/fabric/Fabric.ts:484-488). A host that drops its fabric // closes the peers' sessions with it (peer.Peer.Disconnect); a // RemoveFabric that fails with it counts as delivered. ErrFabricRemoved = errors.New("client: this node is no longer a member of the fabric") )
Peer-loss causes of the registry — matter.js PeerLeftError and PeerShutdownError (protocol/src/peer/PeerCommunicationError.ts:90-94, :72-76 at db021da0), which client/peer and client/exchange do not declare. The cause an operational certificate update force-closes the peer's sessions with, matter.js FabricChangedError, is commissioner.ErrFabricChanged: the commissioner runs the update and cannot import this package.
var ( // ErrICDOperation: an ICD client call its state refuses — matter.js's // ImplementationError of IcdClient (a registration exists, another // operation runs, no subscription, the peer offline or without CIP). ErrICDOperation = errors.New("client: ICD operation refused") // ErrICDAbandoned: an ICD operation another one, decommission or // shutdown abandoned — matter.js's AbortedError. ErrICDAbandoned = errors.New("client: ICD operation abandoned") )
Errors of the ICD client.
var ( // ErrRequestTooLarge is a request that does not fit one message where // it must: a timed or response-suppressed write, or one value that // fits no message — the client machinery's // [interaction.ErrRequestTooLarge]. ErrRequestTooLarge = interaction.ErrRequestTooLarge // ErrMalformedRequest is a request the controller does not formulate, // such as a timed one with a negative TimedTimeout — the client // machinery's [interaction.ErrMalformedRequest]. ErrMalformedRequest = interaction.ErrMalformedRequest )
The errors of a request the controller refuses before it sends anything: the request is the caller's to fix, not a failure of the node (issue 544).
var ( // ErrOnboardingCode is a code [Node.SetOnboardingCode] cannot read: // neither a QR code nor a manual pairing code, or one whose checksum // or passcode is invalid. ErrOnboardingCode = errors.New("client: onboarding code") // ErrOnboardingMismatch is a readable code that names another device: // its vendor, product or discriminator differs from the node's. The // error [Node.SetOnboardingCode] returns is an // [*OnboardingMismatchError], which names the field and both values. ErrOnboardingMismatch = errors.New("client: onboarding code names another device") )
var ( // ErrNoSession is a node holding no operational session to run the // exchange on — the client machinery's [interaction.ErrNoSession]. ErrNoSession = interaction.ErrNoSession // ErrUnreachable is an address that did not answer [Node.PingAddress]. ErrUnreachable = errors.New("client: address unreachable") )
var ( // ErrFabricOperationInProgress: a commission, decommission or // certificate update of the node is already running — matter.js // FabricOperationInProgressError (packages/node/src/node/client/Peers.ts:88-92, // :642-647 at b25ed960). ErrFabricOperationInProgress = errors.New("client: a commission, decommission or certificate update of the node is already in progress") // ErrNotCommissioned: the node has no peer address // (CommissioningClient.ts:343-345); an unbound node's interactions // fail with it too. ErrNotCommissioned = errors.New("client: node is not commissioned") // ErrAlreadyCommissioned: a commission of a node with a peer address // (CommissioningClient.ts:173-175). ErrAlreadyCommissioned = errors.New("client: node is already commissioned") // ErrNotLocated: a commission without an address // (CommissioningClient.ts:220-223). ErrNotLocated = errors.New("client: node has not been located") // ErrForeignFabric: a peer address of a fabric we do not belong to // (Peers.ts:446-448). ErrForeignFabric = errors.New("client: peer address of a fabric we do not belong to") )
Errors of a Registry.
var ErrJSONValue = errors.New("client: JSON value does not fit its type")
ErrJSONValue is a JSON value that does not fit its type; the message says where and why.
var ErrNoBasicWindow = errors.New("client: the node does not support the basic commissioning method")
ErrNoBasicWindow is WindowOptions.Basic on a node whose AdministratorCommissioning lacks the Basic (BC) feature — matter.js's ImplementationError of openBasicCommissioningWindow (CommissioningClient.ts:487-489 at db021da0).
var TrustedEcosystemVendors = []uint16{0x1384, 0x110a, 0x134b}
TrustedEcosystemVendors are the administrators an ICD registration's single-admin guard ignores by default: Apple (0x1384, whose keychain does not subscribe), Samsung SmartThings (0x110a) and the Open Home Foundation / Home Assistant (0x134b). Mirrors matter.js packages/node/src/behavior/system/icd/IcdMultiAdminError.ts:37-41 (TRUSTED_ECOSYSTEM_VENDORS).
Functions ¶
func AssertSingleAdmin ¶ added in v0.12.0
AssertSingleAdmin refuses more than one administrator of vendors outside ignored unless allowMultiAdmin. Mirrors IcdMultiAdminError.ts:56-73.
func DecodeJSON ¶ added in v0.12.1
DecodeJSON renders v, a value of f, as JSON in form: a struct keyed by field id (TagBased) or camelCase name (NameBased), the members the model does not name left out; bytes standard base64; numbers as JSON numbers (a 64-bit integer in full); a list an array; null for TLV null. A value whose shape does not match f, and any value of an untyped f, is rendered untyped: a struct as an object keyed by its context tags, bytes base64, lists arrays.
func HoldUntilICDPeerAwake ¶ added in v0.12.0
func HoldUntilICDPeerAwake(ctx context.Context, w *icd.PeerWakefulness, peer PeerAddress, timeout time.Duration, log *slog.Logger) error
HoldUntilICDPeerAwake waits, for a peer that needs awaiting and sleeps, until w reports it awake: at most timeout (0: w's NextCheckInWithin, the time to the peer's next Check-In) on w's clock. A peer without a wakefulness, or awake, passes at once. A peer that does not wake in time is an *ICDPeerAsleepError; an ended ctx its error. Mirrors matter.js packages/node/src/behavior/system/icd/holdUntilIcdPeerAwake.ts:21-69.
func Interval ¶ added in v0.10.3
Interval is d as the pointer a SubscribeRequest's interval bounds take.
func WithICDAwaitTimeout ¶ added in v0.12.0
WithICDAwaitTimeout bounds the hold of the Read, Write or Invoke ctx carries for a sleeping LIT ICD peer to d, in place of the time to the peer's next Check-In — matter.js's per-request icdAwaitTimeout (ClientRequest.ts:50).
Types ¶
type AdvertisedIntervals ¶
AdvertisedIntervals are the session intervals a node announces in DNS-SD — CommissioningClient.AdvertisedIntervals (CommissioningClient.ts:836-845). A nil field was not announced.
type AttributeData ¶ added in v0.10.3
type AttributeData = interaction.AttributeData
AttributeData is one attribute value of a report: its Path, the cluster's DataVersion, and the Value as a TLV node — decode it with the generated <cluster>def.StateFrom over [Report.Values], or spec.DecodeAttribute.
type AttributePath ¶ added in v0.10.3
type AttributePath = im.ConcreteAttributePath
AttributePath is a concrete attribute path. Build one with AttributeAt, or ClusterAt for every attribute of a cluster; a path's Has… flags say which of its fields are set, a field left unset being a wildcard.
func AttributeAt ¶ added in v0.10.3
func AttributeAt(ep uint16, cluster, attribute uint32) AttributePath
AttributeAt is the path of one attribute of a cluster of an endpoint.
func ClusterAt ¶ added in v0.10.3
func ClusterAt(ep uint16, cluster uint32) AttributePath
ClusterAt is the path of every attribute of a cluster of an endpoint — the read a generated <cluster>def.StateFrom takes.
type AttributeStatus ¶ added in v0.10.3
type AttributeStatus = interaction.AttributeStatus
AttributeStatus is an attribute path a report answers with a status.
type CertificateUpdateOptions ¶
type CertificateUpdateOptions struct {
// Failsafe is the fail-safe armed for the whole update, including the
// CASE reconnect with the new certificate: 0 is one minute
// ([commissioner.DefaultCertificateUpdateFailsafe]); it must lie
// between 30 s and 65535 s. The node ends the fail-safe early at its
// MaxCumulativeFailsafeSeconds.
Failsafe time.Duration
}
CertificateUpdateOptions configure Registry.UpdateOperationalCertificate — matter.js CommissioningClient.OperationalCertificateUpdateOptions (packages/node/src/behavior/system/commissioning/CommissioningClient.ts:931-941 at b25ed960); the abort is the call's context.
type Cluster ¶
type Cluster struct {
// contains filtered or unexported fields
}
Cluster is one cluster of an endpoint of the image: its values, its DataVersion and its shape — the analysis matter.js's PeerBehavior makes of a discovered cluster (node/client/PeerBehavior.ts:403-467 at db021da0) from the cluster's global attributes (ClientStructure.ts:872-955). Its methods are safe for concurrent use.
func (*Cluster) AcceptedCommands ¶
AcceptedCommands is the peer's AcceptedCommandList, sorted.
func (*Cluster) AttributeList ¶
AttributeList is the peer's AttributeList, sorted — or, when AttributeListReported is false, the ids of the values received (ClientStructure.ts:779-795).
func (*Cluster) AttributeListReported ¶
AttributeListReported reports whether AttributeList is the peer's list.
func (*Cluster) Decoded ¶
Decoded returns the attribute's value decoded by its type (spec.DecodeAttribute): a global attribute by its own type, whatever the cluster (InputChunk.ts:105-110); a struct, or a list of structs, through the definition as the generated type; every other value at its widest Go type — an unsigned integer, enum or bitmap as uint64, a signed integer as int64, a list as []any, whatever the attribute's width (a uint8 attribute of 20 is uint64(20)). A value without a type — of a named or unknown cluster, or an attribute the definition does not know — is the node with ErrUntyped; TLV null is nil.
It is the untyped form, for a cluster without a definition and for one attribute at a time. The typed form is the generated package's StateFrom over the cluster (onoffdef.StateFrom(ep.Cluster(onoffdef.ClusterID))): every attribute in its field's type, and the ones the image lacks.
func (*Cluster) Definition ¶
Definition is the cluster's generated definition, nil for a named or unknown cluster.
func (*Cluster) Extra ¶
Extra returns the attribute and command ids the peer lists and the definition does not know — every id of a named or unknown cluster (PeerBehavior.ts:444-455), global attributes aside. matter.js names them "attr$<hex>" (:252-255).
func (*Cluster) FeatureMap ¶
FeatureMap is the peer's FeatureMap.
func (*Cluster) Features ¶
Features are the codes of the features the FeatureMap sets (schema.ClusterFeatureNames), nil for a cluster the snapshot does not know or whose FeatureMap sets none.
func (*Cluster) GeneratedCommands ¶
GeneratedCommands is the peer's GeneratedCommandList, sorted.
func (*Cluster) Name ¶
Name is the cluster's name: its definition's, the schema's for a named cluster, "Cluster$<hex>" for an unknown one.
func (*Cluster) Ready ¶
Ready reports whether the cluster has a shape: something useful arrived (ClientStructure.ts:810-817). A cluster that is not ready is not announced.
func (*Cluster) Revision ¶
Revision is the peer's ClusterRevision; when it reported none or one below 1 the model's — the snapshot's revision of the cluster, 1 for a cluster the snapshot does not know (PeerBehavior.ts:426-434 at b25ed960: the revision override only for a valid, differing one; PeerBehaviorTest "tolerates a peer that does not report a revision"). 0 while the cluster has no shape.
func (*Cluster) Supports ¶
Supports reports whether the peer supports the attribute: a global attribute always (PeerBehavior.ts:488-492); any other when the peer lists it — the support override of maybeOverrideSupport (:478-507), which for a named or unknown cluster the lists alone decide (:484-486) — and, for a cluster of the model, its conformance under the peer's features and revision allows it: an element the peer implements although its conformance deprecates it counts as optional (supportOverrideOf, :381-397), a disallowed one or one its features exclude before a trailing "D" stays out (PeerBehaviorTest "omits a disallowed attribute the peer reports", "omits an attribute the peer reports whose conformance before a trailing deprecation excludes it").
func (*Cluster) SupportsCommand ¶
SupportsCommand reports whether the peer accepts the command: it lists it in its AcceptedCommandList (PeerBehavior.ts:450-455, ClientBehaviorBacking.ts:37-43).
func (*Cluster) Value ¶
Value returns the attribute's value as the peer reported it; false for a nil Cluster — an Endpoint.Cluster the image does not hold — so a generated <cluster>def.StateFrom over it reports every attribute absent. It implements spec.Values.
type CommandPath ¶ added in v0.10.3
type CommandPath = im.ConcreteCommandPath
CommandPath is a concrete command path (CommandAt).
func CommandAt ¶ added in v0.10.3
func CommandAt(ep uint16, cluster, command uint32) CommandPath
CommandAt is the path of a command of a cluster of an endpoint.
type CommandRequest ¶ added in v0.12.1
type CommandRequest = interaction.CommandRequest
CommandRequest is one command of Node.InvokeBatch: its Path and its request Fields (a generated request's value, nil for none).
type CommissionOptions ¶
type CommissionOptions struct {
// Options are the commissioner's. Fabric nil is the registry's first
// fabric; Addresses nil are the node's known addresses; DiscoveryData
// nil is the node's record; CASEConnectionTiming nil is the tighter
// timing matter.js applies after a commissioning
// (defaultCaseConnectionTiming, CommissioningClient.ts:798-811 at
// db021da0).
commissioner.Options
// AutoSubscribe nil or true subscribes the node — "unless disabled
// explicitly" (CommissioningClient.ts:310-311).
AutoSubscribe *bool
// DefaultSubscription narrows the default subscription; nil is the
// wildcard (:309).
DefaultSubscription *SubscribeOptions
// NoInitialRead skips the initial read of the newly commissioned node
// (autoStateInitialize false, :312).
NoInitialRead bool
// OnboardingCode, when set, is the QR or manual pairing code the
// passcode came from; it is kept with the node when the commissioning
// succeeds ([Node.OnboardingCode], source [OnboardingPaired]) and the
// device advertised Basic commissioning mode — not for an Enhanced
// Commissioning Window, whose code ends with the window, and not
// without an advertisement. It is kept before the node starts, so
// also when Commission then returns the start's error. A plain
// string, as the passcode in Options is: it is the caller's input,
// and the stored value is a [SecretCode]. This module's; matter.js
// keeps no pairing code.
OnboardingCode string
}
CommissionOptions configure Registry.Commission — matter.js CommissioningClient.CommissioningOptions as far as the Go commissioner takes them.
type CommissioningWindow ¶ added in v0.12.1
type CommissioningWindow struct {
ManualCode string
QRCode string
Passcode uint32
// Discriminator is the 12-bit long discriminator the node advertises
// while the window is open.
Discriminator uint16
VendorID, ProductID uint16
Timeout time.Duration
}
CommissioningWindow is an open commissioning window — matter.js CommissioningClient.EnhancedCommissioningWindow (CommissioningClient.ts:820-833 at db021da0): the pairing codes, the passcode and long discriminator they encode, the node's vendor and product id, and the window's timeout. A basic window carries the timeout alone; the node's own code commissions it.
func (CommissioningWindow) Format ¶
func (w CommissioningWindow) Format(f fmt.State, _ rune)
Format renders the window as String under every fmt verb.
func (CommissioningWindow) LogValue ¶
func (w CommissioningWindow) LogValue() slog.Value
LogValue renders the window in a log record, its codes and passcode redacted.
func (CommissioningWindow) MarshalJSON ¶
func (w CommissioningWindow) MarshalJSON() ([]byte, error)
MarshalJSON renders the window for encoding/json, its codes and passcode redacted; a host that sends a window's codes to a UI copies the fields.
func (CommissioningWindow) String ¶
func (w CommissioningWindow) String() string
String renders the window with its codes and passcode redacted.
type CompleteOptions ¶ added in v0.13.0
type CompleteOptions struct {
// Fabric is the shared fabric the commissioning is finalized on — the
// one the initiating commissioner installed the device's NOC for; nil
// is the registry's first. A fabric the registry does not hold is
// [ErrForeignFabric].
Fabric *commissioner.Fabric
// DiscoveryData and SessionParameters seed the peer: what the
// initiating commissioner's FinalizeCommissioning was handed
// (commissioner.Options.FinalizeCommissioning).
DiscoveryData *discovery.Device
SessionParameters *SessionParameters
// AutoSubscribe, DefaultSubscription and NoInitialRead are a
// commission's ([CommissionOptions]).
AutoSubscribe *bool
DefaultSubscription *SubscribeOptions
NoInitialRead bool
}
CompleteOptions configures Registry.CompleteCommissioning.
type Config ¶
type Config struct {
// ID is the node's local id, the store key ("peer1"; the registry of
// nodes allocates them).
ID string
// Peer is the remote node: its address, sessions and connection
// process. Nil leaves the connection state to the subscription alone
// (NetworkClient.ts:223, a node without a peer).
Peer *peer.Peer
// Interaction is the interaction bound to Peer —
// commissioner.Commissioner.Interaction(Peer).
Interaction *interaction.Interaction
// Store persists the image; nil is a [MemoryStore] of this node's own.
Store Store
// FlushInterval batches store writes (storage/client/ClientCacheBuffer.ts:41-48);
// 0 writes through.
FlushInterval time.Duration
// AutoSubscribe starts the default subscription in Start
// (NetworkClient.ts:432-439; a newly commissioned node sets it,
// CommissioningClient.ts:308-327). It is persisted: true sets the
// node's stored setting, false keeps what the store holds.
AutoSubscribe bool
// DefaultSubscription narrows the default subscription
// (NetworkClient.ts:412-421); nil keeps the stored one, which is the
// wildcard when none was stored.
DefaultSubscription *SubscribeOptions
// NewlyCommissioned makes Start read the node once before it subscribes
// (NetworkClient.ts:137-143, Internal.isNewlyCommissioned); whoever
// commissioned the node sets it.
NewlyCommissioned bool
// NoInitialRead skips that read — autoStateInitialize false
// (NetworkClient.ts:139, :441-445).
NoInitialRead bool
// EventHistory is the number of events the node keeps for
// [Node.EventHistory], the oldest dropped first: 0 keeps
// [DefaultEventHistory], a negative value none.
EventHistory int
// Hooks are the node's callbacks.
Hooks Hooks
// Logger receives the diagnostics; nil discards them.
Logger *slog.Logger
// Clock paces the store's flush; nil is the system clock.
Clock exchange.Clock
// Rand returns the jitter draw in [0, 1) of the subscription ceiling;
// nil is math/rand/v2.Float64.
Rand func() float64
// contains filtered or unexported fields
}
Config configures a Node.
type ConformanceReport ¶
type ConformanceReport struct {
Status ConformanceStatus
// Violations are the departures of the endpoint from the server-side,
// composition and condition requirements of the device types it lists
// and of Base, as endpoint.DeviceTypeTree.Check finds them: a
// mandatory server cluster missing, a present cluster lacking a
// mandatory feature, attribute or command (judged on the cluster's
// reported FeatureMap, AttributeList and AcceptedCommandList, never on
// values).
Violations []DeviceTypeViolation
// Clients are the client cluster requirements the Descriptor's
// ClientList departs from — informational: they never make the status
// violated.
Clients []DeviceTypeViolation
// Unjudged are the server clusters the ServerList names that were not
// judged inside, in id order.
Unjudged []uint32
}
ConformanceReport is the device type validator's report for an endpoint of the image (Endpoint.Conformance).
type ConformanceStatus ¶
type ConformanceStatus int
ConformanceStatus is the verdict of a ConformanceReport.
const ( // ConformanceUnknown: nothing was judged — the endpoint is not on the // image, its Descriptor's DeviceTypeList or ServerList has not // arrived, or no device type it lists is in the model. ConformanceUnknown ConformanceStatus = iota // ConformanceIncomplete: what was judged conforms, but a server // cluster the ServerList names has no shape yet (or its FeatureMap, // AttributeList or AcceptedCommandList has not arrived): the node is // still being read. ConformanceIncomplete // ConformanceClean: every server requirement was judged and none is // violated. ConformanceClean // ConformanceViolated: a judged requirement is violated. ConformanceViolated )
Conformance statuses.
func (ConformanceStatus) String ¶
func (s ConformanceStatus) String() string
String names the status.
type ConnectionState ¶
type ConnectionState uint8
ConnectionState is a node's connection state — matter.js NodeConnectionState (ClientNodeLifecycle.ts:16-40), the same values.
const ( // Connected: the subscription is established and the peer has a // session; the data is current. Connected ConnectionState = 0 // Disconnected: disabled, stopped or not started. Disconnected ConnectionState = 1 // Reconnecting: a connection was lost and is being re-established. Reconnecting ConnectionState = 2 // WaitingForDeviceDiscovery: the peer looks offline; the node waits for // it to announce itself again. WaitingForDeviceDiscovery ConnectionState = 3 )
Connection states.
func (ConnectionState) String ¶
func (s ConnectionState) String() string
type DataVersionFilter ¶ added in v0.10.3
type DataVersionFilter = im.DataVersionFilter
DataVersionFilter skips a cluster whose DataVersion the caller holds. Node.Read and Node.Subscribe add the image's own.
type Device ¶ added in v0.10.3
Device is a commissionable node as DNS-SD reports it: its TXT data, discriminator, commissioning mode and addresses (Registry.ForDevice).
type DeviceTypeViolation ¶ added in v0.10.3
type DeviceTypeViolation = endpoint.DeviceTypeViolation
DeviceTypeViolation is one finding of a ConformanceReport.
type Encodable ¶ added in v0.12.1
Encodable is a value a write or an invoke sends: a generated request or struct, a scalar spec.Value, or what EncodeJSON returns.
func EncodeJSON ¶ added in v0.12.1
func EncodeJSON(f Field, raw json.RawMessage) (Encodable, error)
EncodeJSON encodes the JSON value raw as a value of f for a write (WriteRequest.Value) or the fields of an invoke. A struct takes its members by camelCase or model name (compared without regard to case) or by decimal field id; an unknown one is refused, and null for an optional member that is not nullable counts as left out. A mandatory member must be there, except in a command's fields (CommandField), where a mandatory member left out takes the specification's fallback as matter.js's MandatoryDefaultValue computes it (packages/model/src/logic/SelectDefaultValue.ts:79-138 at b25ed960): null when nullable, 0 for a number or bitmap, false, "", empty bytes, an empty list, a struct of its members' fallbacks; an enum has none and stays required — so {"level": 128, "transitionTime": 10} is a MoveToLevelWithOnOff with OptionsMask and OptionsOverride 0. Bytes are standard base64. An empty raw, or null, for a command's fields is the empty payload. An untyped f takes go-fabric's untyped form (spec.EncodeJSON with no field: an object is a struct keyed by context tags).
type Endpoint ¶
type Endpoint struct {
// contains filtered or unexported fields
}
Endpoint is one endpoint of the image — an endpoint of a matter.js ClientNode with its EndpointStructure (ClientStructure.ts:1607-1611). Its methods are safe for concurrent use.
func (*Endpoint) Classification ¶
Classification is the device type's classification ("simple", "utility", "node", …).
func (*Endpoint) Conformance ¶
func (e *Endpoint) Conformance() ConformanceReport
Conformance judges the endpoint's image against the device types its Descriptor lists, with the one validator the server side runs (endpoint.DeviceTypeTree over endpoint.DeviceTypeSubject — matter.js's DeviceTypeConformance over DeviceTypeFacts, packages/model/src/logic/device-types/DeviceTypeConformance.ts, DeviceTypeFacts.ts:16-69, which matter.js answers for a server node only). The whole image is the tree, so the endpoint's node scope decides its conditions.
What the image cannot tell is not judged rather than failed: a cluster without a built shape (Cluster.Ready false) or without its FeatureMap, AttributeList or AcceptedCommandList is judged present but nothing inside it (Unjudged, and the status at best incomplete); an event requirement is judged only when the peer reports an EventList; no condition is stated for a remote endpoint. CustomNetworkConfig holds for a node whose root serves no NetworkCommissioning — the only way a commissioned node without one got its network.
func (*Endpoint) Device ¶
func (e *Endpoint) Device() *fabricdevice.Type
Device is the generated device type (fabricdevice.Type) of the endpoint's device type — the one Endpoint.DeviceType reports — or nil for a device type device/ does not generate: the unknown device type, a manufacturer-specific or unknown id, and the snapshot types script/devicegen excludes (see fabricdevice.Lookup: the camera and media families and ThreadBorderRouter, NetworkInfrastructureManager, JointFabricAdministrator, OtaProvider).
matter.js gives a client endpoint its type from the model (packages/node/src/node/client/ClientStructure.ts:871-897, this.#node.matter.deviceTypes(dt.deviceType)) and installs no generated device type on it; the Go view answers the generated one beside it, so a host reads the requirements the device layer mounts a server by. Its Revision is the snapshot's; the peer's is Endpoint.DeviceRevision.
func (*Endpoint) DeviceRevision ¶
DeviceRevision is the device type's revision; ok false while unknown (EndpointType.UNKNOWN_DEVICE_REVISION).
func (*Endpoint) DeviceType ¶
DeviceType is the device type the Descriptor names — the first application device type, else the last other one (ClientStructure.ts:858-905); UnknownDeviceType while none is known.
func (*Endpoint) Name ¶
Name is the device type's name, "Unknown#<hex4>" for a device type the schema does not know, "Unknown" while none is known.
type EventData ¶ added in v0.10.3
type EventData = interaction.EventData
EventData is one event of a report: Path, Number, Priority, the timestamps, and the event's data as a TLV node (HasValue false when it carried none).
type EventMinimumNumber ¶ added in v0.10.3
type EventMinimumNumber = im.EventMinimumNumber
EventMinimumNumber asks for the events from a number on.
type EventPath ¶ added in v0.10.3
type EventPath = im.ConcreteEventPath
EventPath is a concrete event path (EventAt).
type EventStatus ¶ added in v0.10.3
type EventStatus = interaction.EventStatus
EventStatus is an event path a report answers with a status.
type Field ¶ added in v0.12.1
type Field struct {
// contains filtered or unexported fields
}
Field is the type a JSON value is a value of: an attribute's, a command's fields, a command response's or an event's data, looked up in the generated cluster definitions. The zero Field, and a Field of an element no definition names, is untyped: a struct is keyed by its context tags, bytes are base64, a number keeps the TLV's signedness.
func AttributeField ¶ added in v0.12.1
AttributeField is the type of an attribute's value: a global attribute's (FeatureMap, ClusterRevision, the id lists) for any cluster, else the cluster definition's.
func CommandField ¶ added in v0.12.1
CommandField is the type of a request command's fields: a struct of them.
func EventField ¶ added in v0.12.1
EventField is the type of an event's data: a struct of its fields.
func ResponseField ¶ added in v0.12.1
ResponseField is the type of a response command's fields (Result.Fields of its Command).
type Form ¶ added in v0.12.1
type Form uint8
Form is how DecodeJSON keys a struct.
const ( // TagBased keys a struct by its field ids in decimal ({"0": true}), // matterjs-server's form of an attribute value. A member the model // does not name is left out. TagBased Form = iota // NameBased keys a struct by its camelCase field names // ({"newPosition": 1}), matterjs-server's form of a command's fields // and an event's data. A member the model does not name is left out. NameBased )
The forms of a struct.
type Hooks ¶
type Hooks struct {
// EndpointInstalled: an endpoint joined the image under its owner. Its
// clusters come with it; no ClusterInstalled follows for them
// (ClientStructureEvents.ts:88-107).
EndpointInstalled func(ep *Endpoint)
// ClusterInstalled: a cluster joined an installed endpoint.
ClusterInstalled func(ep *Endpoint, c *Cluster)
// ClusterReplaced: an installed cluster's shape changed (its revision,
// features, attribute or command lists).
ClusterReplaced func(ep *Endpoint, c *Cluster)
// ClusterDeleted: the peer's ServerList dropped the cluster.
ClusterDeleted func(ep *Endpoint, c *Cluster)
// Changed: a read or report was applied (ClientStructure.ts:166-168,
// :1550).
Changed func()
// ConnectionStateChanged: the connection state changed
// (ClientNodeLifecycle.ts:101-107).
ConnectionStateChanged func(s ConnectionState)
// SubscriptionStatusChanged: the default subscription gained or lost
// its underlying subscription (NetworkClient.ts:181-188).
SubscriptionStatusChanged func(active bool)
// SubscriptionAlive: the default subscription delivered a report or a
// keepalive, or was established (NetworkClient.ts:157-172, :185-187).
// For a report it runs after the report's other hooks — its
// EndpointInstalled, cluster and Event hooks — as matter.js emits
// subscriptionAlive once the report's mutate has finished.
SubscriptionAlive func()
// Event: an event the peer reported, for every cluster. value is the
// payload decoded through the event's definition, the raw [spec.Node]
// when there is none, nil without a payload. Only the default
// subscription while it is current, its bootstrap read and the
// newly-commissioned read deliver here (and raise the event cursor); a
// host's own Read or Subscribe returns its events in its Report only
// (matter.js ClientStructure.ts:412, NetworkClient.ts:171-173). The
// event is in [Node.EventHistory] when the hook runs, so the hook is
// the history's change notification.
Event func(endpoint uint16, cluster, event uint32, e EventData, value any)
// Seeded: the structure is known, once — BasicInformation is present
// and every endpoint the root's PartsList names is installed, more than
// the root when no PartsList was reported (Peers.ts:760-797,
// ClientNodeLifecycle.ts:51-75).
Seeded func()
// Decommissioned: a [Registry] removed the node from its fabric, or the
// peer left it — matter.js lifecycle.decommissioned
// (node/NodeLifecycle.ts:105-110), emitted when the peer address is
// cleared (CommissioningClient.ts:637-646) and on a leave event
// (node/client/Peers.ts:827). On a leave it runs inside the
// [Registry]'s fabric operation, before the node's sessions go and it
// is deleted (Peers.ts:826-833): it must not start a fabric operation
// of the same registry (decommission, a fabric change), which waits for
// that one to end.
Decommissioned func()
// Deleted: the node left its [Registry] — [Registry.Forget],
// [Registry.Erase], a decommission, a peer's leave, the cull of an
// expired commissionable node, or a [Registry.CompleteCommissioning]
// that failed after the node was created — once it closed; the
// registry no longer holds it. matter.js's Peers carries a deleted
// observable of its own (node/client/Peers.ts:112 at db021da0). It can
// run inside the registry's fabric operation (Erase, a leave): it must
// not
// start a fabric operation of the same registry.
Deleted func()
// Commissioned: the registry commissioned the node — matter.js
// lifecycle.commissioned (CommissioningClient.ts:359 at db021da0),
// emitted after the record and settings are saved and before the node
// starts.
Commissioned func()
// ConfigurationVersionChanged: a report changed the ConfigurationVersion
// of the node's BasicInformation (ep the root) or of a bridged
// endpoint's BridgedDeviceBasicInformation — matter.js
// lifecycle.configurationVersionChanged (node/client/Peers.ts:757,
// :803-814). The first value the image takes is no change.
ConfigurationVersionChanged func(ep *Endpoint)
}
Hooks are a node's callbacks. Each is optional; they run after the node's lock is released, in the order the structure produced them (events delivered at once, the structure events, Changed, then the delayed events — ClientStructure.ts:375-379). A panic in a structure hook is logged, never raised (ClientStructureEvents.ts:138-144).
The hooks of a subscription report run on the node's ordered job queue, after the report's StatusResponse (ClientStructure.ts:417-439): a hook may block without holding the peer's exchange, but it must not call Node.Stop or Node.Close, which drain that queue, nor Node.Start on a stopped node or Node.SetDefaultSubscription, which wait for it before the cache adopts a fabric filter — all within their context: a hook still blocked when it ends makes them return its error. The hooks of a read's result run on the caller's goroutine before the read returns when no report's hooks are pending; with some pending they take their place behind them on the queue, and the read returns before they run.
type ICDCheckIn ¶ added in v0.12.0
ICDCheckIn is an accepted Check-In (IcdClient.ts:1115-1117, checkedIn).
type ICDClient ¶ added in v0.12.0
type ICDClient struct {
// contains filtered or unexported fields
}
ICDClient is a node's ICD client: the controller's Check-In registration on an ICD peer, its receipt of the peer's Check-Ins, the key refresh, the automatic registration on a LIT-operating peer with a subscription, and the peer's wakefulness, which holds interactions with a sleeping LIT peer and parks the node's sustained subscription. A registry's node has one; it is safe for concurrent use.
Mirrors matter.js packages/node/src/behavior/system/icd/IcdClient.ts:55-935 (IcdClient). matter.js runs each operation in a transaction of its own and commits under the ICD state lock; Go serialises the commits under one lock (commitMu) and an operation commits only while it still owns the registration (#commitIfOwned, :356-372).
func (*ICDClient) Available ¶ added in v0.12.0
Available reports a reachable registered peer: a subscription to it is held, or its next Check-In is not overdue; a non-LIT peer always is (IcdClient.ts:1095-1100).
func (*ICDClient) Awake ¶ added in v0.12.0
Awake reports a peer to which a message goes out now: a non-LIT or not yet registered peer reads true (IcdClient.ts:75-77).
func (*ICDClient) Forget ¶ added in v0.12.0
Forget drops this controller's registration locally, without UnregisterClient: it abandons a registration, a key refresh or an Unregister that has not cleared yet; the peer keeps a stale registration until a later Register replaces it. A no-op when nothing is registered or being registered. Mirrors matter.js IcdClient.ts:651-677.
func (*ICDClient) LastCheckInAt ¶ added in v0.12.0
LastCheckInAt is the time the last accepted Check-In arrived; ok is false before one, and after the registration was cleared.
func (*ICDClient) NextExpectedCheckIn ¶ added in v0.12.0
NextExpectedCheckIn is the deadline of the next Check-In of a registered LIT peer; ok is false with no fed peer, unregistered, not LIT, or while a subscription is held (IcdClient.ts:83-87).
func (*ICDClient) OnAvailableChanged ¶ added in v0.12.0
OnAvailableChanged registers fn for every change of Available.
func (*ICDClient) OnCheckIn ¶ added in v0.12.0
func (c *ICDClient) OnCheckIn(fn func(ICDCheckIn)) func()
OnCheckIn registers fn for every accepted Check-In.
func (*ICDClient) OnCheckInMissed ¶ added in v0.12.0
func (c *ICDClient) OnCheckInMissed(fn func()) func()
OnCheckInMissed registers fn for every missed Check-In of a registered LIT peer (IcdClient.ts:812-814).
func (*ICDClient) OnKeyRefreshed ¶ added in v0.12.0
func (c *ICDClient) OnKeyRefreshed(fn func()) func()
OnKeyRefreshed registers fn for every stored key refresh.
func (*ICDClient) OnRegistered ¶ added in v0.12.0
func (c *ICDClient) OnRegistered(fn func()) func()
OnRegistered registers fn for every stored registration.
func (*ICDClient) OnUnregistered ¶ added in v0.12.0
func (c *ICDClient) OnUnregistered(fn func()) func()
OnUnregistered registers fn for every cleared registration (Unregister, Forget, decommission).
func (*ICDClient) PeerSupportsLIT ¶ added in v0.12.0
PeerSupportsLIT is Node.LITSupported (IcdClient.ts:68-70).
func (*ICDClient) Register ¶ added in v0.12.0
func (c *ICDClient) Register(ctx context.Context, opts ICDRegisterOptions) error
Register registers this controller as a Check-In client of the peer: a 16-byte random key installed with RegisterClient, the counter baseline of the response stored, and the Check-In receive path armed. A call while a registration with the same options runs joins it. It refuses with ErrICDOperation a registration that exists or is torn down, other options in flight, no active subscription (the peer's operating mode would be stale), a peer that is not online or lacks CheckInProtocolSupport; with *ICDMultiAdminError a multi-admin peer; with ErrICDAbandoned when Unregister, Forget, decommission or Close abandoned it. Mirrors matter.js IcdClient.ts:499-592 (register, #registerOnPeer; Core §9.16.7.1).
func (*ICDClient) Registered ¶ added in v0.12.0
Registered reports a stored registration (IcdClient.ts:63-65, isRegistered).
func (*ICDClient) Registration ¶ added in v0.12.0
func (c *ICDClient) Registration() (ICDRegistration, bool)
Registration returns the stored registration; ok is false while the controller is not registered.
func (*ICDClient) StayActive ¶ added in v0.12.0
StayActive asks the peer to stay active for at least d and returns what it promised; the wakefulness keeps the peer awake that long. Mirrors matter.js IcdClient.ts:706-713 (Core §9.16.7.4).
func (*ICDClient) Unregister ¶ added in v0.12.0
Unregister removes this controller's registration from the peer: it abandons a registration or a key refresh in flight, waits for a sleeping LIT peer to wake, clears the local registration, then sends UnregisterClient with the cleared key. A no-op when not registered; a call while one runs joins it. ErrICDOperation while Forget runs; ErrICDAbandoned when Forget, decommission or Close abandoned it before the clear; *ICDPeerAsleepError when the peer did not wake (the registration stays); the peer's error when UnregisterClient failed after the clear. Mirrors matter.js IcdClient.ts:611-636 (Core §9.16.7.3).
func (*ICDClient) Wakefulness ¶ added in v0.12.0
func (c *ICDClient) Wakefulness() *icd.PeerWakefulness
Wakefulness is the fed peer's wakefulness, nil when no peer is fed (IcdClient.ts:300-303).
type ICDMultiAdminError ¶ added in v0.12.0
type ICDMultiAdminError struct {
// AdminVendorIDs are the counted vendors, each once.
AdminVendorIDs []uint16
}
ICDMultiAdminError refuses an ICD registration on a peer administered by more than one fabric of vendors not ignored: their Check-In clients would compete for the device's few slots. It is an ErrICDOperation. Mirrors matter.js IcdMultiAdminError.ts:16-27.
func (*ICDMultiAdminError) Error ¶ added in v0.12.0
func (e *ICDMultiAdminError) Error() string
func (*ICDMultiAdminError) Unwrap ¶ added in v0.12.0
func (e *ICDMultiAdminError) Unwrap() error
Unwrap makes the error an ErrICDOperation, as matter.js's is an ImplementationError.
type ICDPeerAsleepError ¶ added in v0.12.0
type ICDPeerAsleepError struct {
Peer PeerAddress
Timeout time.Duration
}
ICDPeerAsleepError is a held interaction whose LIT ICD peer did not wake in time. Mirrors matter.js IcdPeerAsleepError.ts:17-25.
func (*ICDPeerAsleepError) Error ¶ added in v0.12.0
func (e *ICDPeerAsleepError) Error() string
type ICDRegisterOptions ¶ added in v0.12.0
type ICDRegisterOptions struct {
// MonitoredSubject is the subject the peer monitors for us; nil is our
// own operational node id.
MonitoredSubject *uint64
// ClientType is Permanent (the zero value) or Ephemeral.
ClientType icddef.ClientTypeEnum
// AllowMultiAdmin registers despite other administrators.
AllowMultiAdmin bool
// IgnoredVendors are the administrators the single-admin guard does
// not count; nil is [TrustedEcosystemVendors].
IgnoredVendors []uint16
}
ICDRegisterOptions configures ICDClient.Register (IcdClient.ts:994-999).
type ICDRegistration ¶ added in v0.12.0
type ICDRegistration struct {
Key []byte
PendingKey []byte
CounterStart uint32
LastOffset uint32
MonitoredSubject uint64
ClientType icddef.ClientTypeEnum
}
ICDRegistration is the controller's Check-In registration on a peer: the key it installed, a key a refresh offered and nobody confirmed yet, the counter state Check-Ins are validated against, the monitored subject and the client type (IcdClient.ts:1039-1087).
func (ICDRegistration) Format ¶
func (r ICDRegistration) Format(f fmt.State, _ rune)
Format renders the registration as String under every fmt verb, so no verb (%x, %+v, %#v) reaches the key bytes.
func (ICDRegistration) LogValue ¶
func (r ICDRegistration) LogValue() slog.Value
LogValue renders the registration in a log record, its keys redacted.
func (ICDRegistration) MarshalJSON ¶
func (r ICDRegistration) MarshalJSON() ([]byte, error)
MarshalJSON renders the registration for encoding/json, its keys redacted. There is no UnmarshalJSON: a redacted key does not come back.
func (ICDRegistration) String ¶
func (r ICDRegistration) String() string
String renders the registration with its keys redacted.
type InvokeOptions ¶ added in v0.10.3
type InvokeOptions = interaction.InvokeOptions
InvokeOptions are an invoke's options: Timed (a TimedRequest first; a command schema.IsTimedInvoke names is timed without it), TimedTimeout, ExpectedProcessingTime, ExtendedFailSafeTimeout, SuppressResponse.
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore is a Store in memory. The zero value is ready.
func (*MemoryStore) EraseCluster ¶
func (m *MemoryStore) EraseCluster(nodeID string, ep uint16, cluster uint32) error
EraseCluster implements Store.
func (*MemoryStore) EraseEndpoint ¶
func (m *MemoryStore) EraseEndpoint(nodeID string, ep uint16) error
EraseEndpoint implements Store.
func (*MemoryStore) EraseNode ¶
func (m *MemoryStore) EraseNode(nodeID string) error
EraseNode implements Store.
func (*MemoryStore) Load ¶
func (m *MemoryStore) Load(nodeID string) ([]StoredEndpoint, error)
Load implements Store: the endpoints in number order, their clusters in id order, copies.
type NetworkAddress ¶
type NetworkAddress struct {
IP netip.Addr
Port uint16
// TTL is the address record's time to live, 0 when unknown: it then
// expires after [DefaultTTL] (Peers.ts:959-966).
TTL time.Duration
// DiscoveredAt is when the address was discovered; zero never expires
// (Peers.ts:960-965).
DiscoveredAt time.Time
}
NetworkAddress is one network address of a node with its lifespan — CommissioningClient.NetworkAddress (CommissioningClient.ts:883-920) for UDP, the only transport here.
func (NetworkAddress) String ¶
func (a NetworkAddress) String() string
String formats the address as host:port, IPv6 in brackets.
func (NetworkAddress) UDPAddr ¶
func (a NetworkAddress) UDPAddr() *net.UDPAddr
UDPAddr is the address as a *net.UDPAddr.
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node is the image of one remote node — matter.js ClientNode (node/ClientNode.ts:57-414 at db021da0) with the subscription and connection-state half of NetworkClient. It is safe for concurrent use.
func New ¶
New builds the node cfg describes and loads its image from the store. Mirrors ClientNode.initialize (ClientNode.ts:105-133): synchronous, nothing installed but the image. Config.AutoSubscribe true and a Config.DefaultSubscription replace the stored settings.
func (*Node) AutoSubscribe ¶ added in v0.12.1
AutoSubscribe reports whether the node keeps the default subscription (Node.SetAutoSubscribe).
func (*Node) ClearOnboardingCode ¶
ClearOnboardingCode removes the node's stored onboarding code — from the store also when the stored one could not be read. Like storeOnboarding it writes the store under the node's lock, which Node.Erase does not: the write has to be ordered against the erase, or a code stored late would outlive its node.
func (*Node) Close ¶
Close stops the node and releases it; it is idempotent. Events that arrive meanwhile are dropped. A Close that returns its context's error has closed the node — it starts no more, and its ICD client is released — and left the stop to the node's queue as Node.Stop describes; a second Close waits for it.
func (*Node) ConnectionState ¶
func (n *Node) ConnectionState() ConnectionState
ConnectionState is the node's connection state (ClientNodeLifecycle.ts:80-82).
func (*Node) DefaultSubscription ¶
func (n *Node) DefaultSubscription() *SubscribeOptions
DefaultSubscription is the node's default subscription as set, nil for the default (Node.SetDefaultSubscription).
func (*Node) Disable ¶
Disable takes the node offline and keeps it so, persisted (NetworkClient.ts:344-349) — ClientNode.disable (ClientNode.ts:236-250).
func (*Node) Enable ¶
Enable lifts Disable and starts the node — ClientNode.enable (ClientNode.ts:257-264).
func (*Node) Endpoints ¶
Endpoints are the image's installed endpoints in number order, endpoint 0 first.
func (*Node) Erase ¶
Erase stops the node and forgets its image, its store included — ClientNode.erase (ClientNode.ts:230-232, :269-274 at db021da0). A store that fails to erase the node's rows is returned: the image is gone, the rows stay, and an Erase again retries them (review II).
func (*Node) EventHistory ¶
func (n *Node) EventHistory(since uint64, limit int) []RecordedEvent
EventHistory returns the events the node delivered to Hooks.Event — the default subscription's, its bootstrap read's and the newly-commissioned read's — whose number is since or later, oldest first; with limit > 0 only the newest limit of them. The history holds the newest Config.EventHistory events (DefaultEventHistory when 0, none when negative), in memory only: it starts empty with every New and Node.Erase clears it. A host's own Read or Subscribe does not reach it. The result is a copy the caller may keep.
matter.js's ClientNode keeps no event history (ClientEventEmitter.ts:45-75 at b25ed960): this is the module's (by_design.md BD-Matter-ClientNodeEventHistory), so a UI's event log and a server's diagnostics read one source.
func (*Node) IntervalBounds ¶
IntervalBounds are the reporting interval bounds of a subscription to the node, the caller's floor and ceiling (nil for the node's default) adjusted to its physical properties — PhysicalDeviceProperties.subscriptionIntervalBoundsFor (PhysicalDeviceProperties.ts:64-164), as ClientNodeInteraction.subscribe applies it (ClientNodeInteraction.ts:129-133).
func (*Node) Invoke ¶
func (n *Node) Invoke(ctx context.Context, path CommandPath, fields spec.Encodable, opts InvokeOptions) (Result, error)
Invoke invokes a command on the peer — ClientNodeInteraction.invoke (ClientNodeInteraction.ts:197-224).
func (*Node) InvokeBatch ¶ added in v0.12.1
func (n *Node) InvokeBatch(ctx context.Context, cmds []CommandRequest, opts InvokeOptions) ([]Result, error)
InvokeBatch invokes several commands on the peer and returns one Result per command, in their order, a command's own status in its Result (NoCommandResponse for one the peer did not answer). The commands go in batches of the peer's Node.MaxPathsPerInvoke, each batch on an exchange of its own, in parallel — matter.js ClientInteraction.invoke with #invokeWithSplitting (packages/protocol/src/action/client/ClientInteraction.ts:654-737 at db021da0) behind ClientNodeInteraction.invoke (packages/node/src/node/client/ClientNodeInteraction.ts). A batch's exchange failure is the error; the Results of the other batches stand.
func (*Node) IsCommissioned ¶
IsCommissioned reports whether the node is commissioned: it loaded and its record has a peer address. Mirrors matter.js packages/node/src/node/NodeLifecycle.ts:94-96 at b25ed960 (lifecycle.isCommissioned): false at construction (:23), set by the initialized, commissioned and decommissioned events (:38-46), which the commissioning state emits, when the node's parts are ready, with whether it holds a peerAddress, and when the peerAddress changes (packages/node/src/behavior/system/commissioning/CommissioningClient.ts :193, :698-712, :762-771 at b25ed960). A node that failed to load is not commissioned, though Node.PeerAddress answers its stored address — PeersLoadFailureTest.ts:123-125 at b25ed960 leaves such a peer out of peers.commissioned (the orphaned-fabric case).
func (*Node) LITSupported ¶ added in v0.12.0
LITSupported is matter.js IcdClient.litSupported (IcdClient.ts:967-974): the peer's IcdManagement has LongIdleTimeSupport and its BasicInformation reports specification 1.4.0 or later.
func (*Node) LoadError ¶ added in v0.13.0
LoadError is why a stored node failed to load (ErrLoadFailed with the cause), nil for a node that loaded — matter.js's construction error of a peer kept unavailable (Peers.ts:144-161 at db021da0).
func (*Node) MaxPathsPerInvoke ¶ added in v0.12.1
MaxPathsPerInvoke is the number of commands the peer takes in one InvokeRequest: the MaxPathsPerInvoke of its session parameters, 1 when it reported none or the node has no peer — matter.js PeerExchangeProvider.maxPathsPerInvoke (packages/protocol/src/peer/PeerExchangeProvider.ts:30-32 at db021da0) and ClientInteraction's fallback of 1 (ClientInteraction.ts:721).
func (*Node) OnboardingCode ¶
func (n *Node) OnboardingCode() (code OnboardingCode, ok bool)
OnboardingCode is the node's stored onboarding code; ok is false when it has none.
func (*Node) OpenCommissioningWindow ¶ added in v0.12.1
func (n *Node) OpenCommissioningWindow(ctx context.Context, timeout time.Duration, opts WindowOptions) (CommissioningWindow, error)
OpenCommissioningWindow opens a commissioning window on the peer so another administrator can commission it for timeout (0 is DefaultWindowTimeout; at most 65535 s): a window open before is revoked first, a WindowNotOpen answer accepted; then OpenCommissioningWindow with a random discriminator and passcode and the PAKE verifier derived from them over a random 32-byte salt at 1000 PBKDF2 iterations — CommissioningClient.openEnhancedCommissioningWindow (CommissioningClient.ts:507-567 at db021da0) with PaseClient's generateRandomDiscriminator, generateRandomPasscode and generatePakePasscodeVerifier (PaseClient.ts:50-71). The codes it returns are the manual code of the Standard flow and the QR code of version 0, Standard flow, discovery on the IP network, with the vendor and product id of the peer's BasicInformation.
matter.js takes those ids from the node's seeded state and refuses an unseeded node; a node whose image lacks them reads them first. With opts.Basic it is openBasicCommissioningWindow (:486-497): the Basic feature of the image's AdministratorCommissioning (read when the image lacks it), the stale window revoked, OpenBasicCommissioningWindow. AdministratorCommissioning's commands are timed.
func (*Node) PeerAddress ¶
func (n *Node) PeerAddress() (addr PeerAddress, ok bool)
PeerAddress is the node's address on our fabric: its record's, or, for a node that failed to load (Node.LoadError), the address its stored record names; ok is false when there is none — a node not commissioned, or a failed node whose stored record names no address. An address is not a commissioned node: ask Node.IsCommissioned for that.
Mirrors matter.js packages/node/src/node/ClientNode.ts:388-421 at b25ed960 (ClientNode.peerAddress): a loaded commissioning state is authoritative, set or cleared (:397-402); a state that did not load answers from storage (:408-418). Its cache (:404-406) answers a state unloaded after a load and repeats the storage answer (:412); a Node keeps a loaded record until Erase, and storedAddr is the stored answer.
func (*Node) PingAddress ¶
PingAddress probes one operational address of the node over the session it holds and returns the round trip, measured on the node's clock. It is matter.js ClientInteraction.probe with addressOverride (packages/protocol/src/action/client/ClientInteraction.ts:352-412 at db021da0), called as PeerAddressMonitor probes an alternate address (packages/protocol/src/peer/PeerAddressMonitor.ts:202-211, :229-237): an empty read on the existing session sent to addr, on the peer network's probe profile, with suppressed peer loss and at most PROBE_MAX_RETRANSMISSIONS transmissions. Unlike the monitor it never migrates: the session keeps its address, the record its addresses, and a failed ping does not count as a lost peer.
Its purpose is per-address reachability in a host — go-fabric-ui's ping measures each address of Record.Addresses with it. addr must be one of them: any other is refused with ErrConfig and nothing is sent, so a host that takes the address from outside — a UI client's request — cannot make the controller send session traffic to any host:port (review II, R2-P6-sec-2361, owner decision 236; the references' callers probe only a peer's discovered addresses — a module rule, not a mirrored one). An address that does not answer is ErrUnreachable, naming addr; a node not yet commissioned is ErrNotCommissioned, one without a session ErrNoSession, a closed one ErrClosed; the end of ctx is ctx's error. A ping waits for no ICD to wake: it is matter.js's protocol-level probe, not a ClientNodeInteraction call, and a sleeping LIT ICD fails it.
func (*Node) Properties ¶
func (n *Node) Properties() Properties
Properties are the node's physical properties, computed from the image after each change and frozen while the node is stopped — matter.js ClientNodePhysicalProperties (node/client/ClientNodePhysicalProperties.ts:18-133).
func (*Node) Read ¶
Read reads from the peer and applies the report to the image — ClientNodeInteraction.read (ClientNodeInteraction.ts:91-112): unless IncludeKnownVersions, and when the read has the default subscription's fabric filter (:103-106), the cached versions go along as filters, none for a cluster with a changes-omitted attribute (:107) and none for a cluster the caller filters ([structure.withKnownVersions]). The caller gets the report as the peer sent it, its chunks merged.
A host's read returns its events in the Report only: they reach neither Hooks.Event nor the persisted event cursor — matter.js ClientNodeInteraction.ts:97-98 passes the request's own emitEvents, which a plain read leaves unset (ClientStructure.ts:412).
func (*Node) RevokeCommissioningWindow ¶ added in v0.12.1
RevokeCommissioningWindow closes the peer's commissioning window with RevokeCommissioning (timed); open is false when the peer answered WindowNotOpen (Failure with that cluster status), which is no error — CommissioningClient.#revokeStaleCommissioningWindow (CommissioningClient.ts:570-582 at db021da0).
func (*Node) Seeded ¶
Seeded reports whether the node's structure is known (Hooks.Seeded; ClientNodeLifecycle.ts:51-57).
func (*Node) SetAutoSubscribe ¶ added in v0.12.1
SetAutoSubscribe switches the node's default subscription on or off and persists the choice with the node's settings: a started node establishes the sustained default subscription at once (reading first when newly commissioned) or closes it; a stopped one follows the choice at its next start — matter.js NetworkClient's autoSubscribe state, whose change runs #syncAutoSubscribe (NetworkClient.ts:46, :114-116, :131-238 at db021da0). An unchanged choice is nothing.
func (*Node) SetDefaultSubscription ¶
func (n *Node) SetDefaultSubscription(ctx context.Context, o *SubscribeOptions) error
SetDefaultSubscription replaces the node's default subscription and persists it with the node's settings; nil is the default (every attribute, every event urgent, fabric filtered). The held default subscription ends, the cache adopts the new request's fabric filter ([Node.adoptDefaultFabricFilter]) and, when the node is started and keeps a default subscription, the new one is established — matter.js NetworkClient.#handleDefaultSubscriptionChange (packages/node/src/behavior/system/network/NetworkClient.ts:118-129 at db021da0), a reaction to the defaultSubscription state that runs one at a time with Start and Node.SetAutoSubscribe (:114-116, :93-98). An unchanged request is nothing.
The adoption waits, within ctx, for the node's queued report jobs — their store writes and hooks (Hooks) — so a hook must not call SetDefaultSubscription. When ctx ends while jobs are still queued — a hook that blocks — it returns ctx's error and the request is not replaced: the settings, stored ones included, name the default subscription they named before, and the cache keeps its fabric filter, so the two agree. The default subscription a started node held has ended, as after an establishment that failed; the same call again makes the change and establishes the new one.
The same holds for the initial read of a newly commissioned node, which runs before the held subscription ends: when it fails, the error is returned and the request is not replaced — the settings, stored ones included, name the previous request, the held subscription stands and the cache keeps its filter. Every error therefore means "not replaced". matter.js runs the same steps in the same order as a state reaction with no caller to tell (NetworkClient.ts:118-128, :131-162 at db021da0); the uniform error contract is this method's own.
func (*Node) SetOnboardingCode ¶
func (n *Node) SetOnboardingCode(code string) (OnboardingCode, error)
SetOnboardingCode attaches the code printed on the device to a commissioned node — typed, scanned or read from a photograph by the host — and replaces a stored one. The code is validated as a pairing code (ErrOnboardingCode) and compared with what the node is known to be (ErrOnboardingMismatch, nothing is stored):
- the vendor and product ids of a QR code or a 21-digit manual code with the node's Basic Information, or the ids it advertised;
- the discriminator with the one the node advertised — a manual code's four bits with that one's upper four. This check runs only when the node was last seen commissionable in Basic mode: in an Enhanced Commissioning Window the advertised discriminator is the window's, and a node paired by address advertised none.
A side the node does not know is skipped; the result's Checks name the checks that ran. No check proves the passcode: a commissioned device offers no way to test one, so the code is OnboardingAttached — unless it is the very code the node was paired with, which stays as it is. Nor does a check prove the unit: the code of another device of the same product with the same discriminator passes every one of them. A node that is not commissioned is ErrNotCommissioned.
func (*Node) Start ¶
Start brings the node online — ClientNode start through NetworkClient.startup (NetworkClient.ts:60-102): the peer's signals are bound (:79-83), the default subscription established when AutoSubscribe (:88, a newly commissioned node reading first), and the connection state recomputed (:98). A disabled node does not start: ErrDisabled (ClientNetworkRuntime.ts:41-43). An error of the initial read is returned; the node stays started.
Before anything else Start waits, within ctx, for the node's queued report jobs — their store writes and hooks (Hooks) — which the cache's adoption of the default subscription's fabric filter follows, so a hook must not call it on a stopped node. When ctx ends while jobs are still queued — a hook that blocks, the one a Node.Stop that timed out left behind included — Start returns ctx's error and nothing has begun: the node is not started, the cache keeps its fabric filter, and a later Start starts it.
func (*Node) Stop ¶
Stop takes the node offline: the default subscription closes and, when it was reported subscribed, Hooks.SubscriptionStatusChanged gets false, the peer's signals are released, the properties freeze, the store is flushed (ClientCacheBuffer.ts:94-101) and the connection state is recomputed. It waits, within ctx, for the subscription to end and for the node's queued report jobs — their store writes and hooks (Hooks) — to drain, so a hook must not call it.
Whatever ctx does, the node is offline when Stop returns and the store's flush timer is stopped: a stopped node arms none, so nothing of it writes to the store on a timer until Node.Start.
When ctx ends while jobs are still queued — a hook that blocks, on the host's own I/O or on a lock the caller of Stop holds — Stop returns ctx's error and hands the rest of the stop to the queue. What it leaves behind: the queue's goroutine, which runs the jobs to their end, hooks included, and then the store's final flush as its last job (it follows the drain, so no queued write lands behind it); a flush the timer had already started; and, until that last job has run, the cache's unflushed changes. A final flush the store refuses — the host closed its database meanwhile — is logged and not retried. The stop completes by itself when the hook returns. Stop is safe to call again: a second Stop (or Close) waits within its own ctx for the queue and the final flush and returns nil once the stop is complete. Erase and the registry's delete stop first and do nothing after a Stop that failed.
func (*Node) Subscribe ¶
func (n *Node) Subscribe(ctx context.Context, sr SubscribeRequest) (*Subscription, error)
Subscribe subscribes through the node — ClientNodeInteraction.subscribe (ClientNodeInteraction.ts:119-182 at db021da0): the cached versions go along as filters (:123-124, :136, no changes-omitted refresh), as for a read none for a cluster the caller filters and none with the other fabric filter than the cache's ([structure.withKnownVersions]); the interval bounds are the node's for the request's (:137-141); each report is applied to the image before req.Updated sees it (:147-159), its store writes and hooks on the node's job queue, off the report's exchange (ClientStructure.ts:417-439); a sustained subscription's re-subscriptions send the versions then current (:161-168) and the event minimum past the highest event it delivered itself, the request's own event filters until then (SustainedSubscription.ts:379-384).
A sustained subscription's re-subscription starts from the caller's own filters, runs the caller's RefreshRequest on them, then injects the versions, and its reports are applied by the scope of the request that produced them. Mirrors matter.js packages/node/src/node/client/ClientNodeInteraction.ts:119-182 at db021da0 (callerRefresh :125, sent :129-132, refreshRequest :162-168). With IncludeKnownVersions no version goes along, in the first request nor in a re-subscription's (withKnownVersions, :123-124).
A host's subscription returns its events in its reports only (see Read); only the default subscription emits them.
func (*Node) SubscriptionActive ¶
SubscriptionActive reports whether the default subscription holds an established subscription (NetworkClient.ts:203-209).
func (*Node) Write ¶
func (n *Node) Write(ctx context.Context, writes []WriteRequest, opts WriteOptions) (WriteStatuses, error)
Write writes to the peer — ClientNodeInteraction.write (ClientNodeInteraction.ts:175-186). The image changes when the peer reports the new value, not through the write (matter.js's RemoteWriter settles the values the peer accepts in the cache, and a declined attribute rolls the transaction back, RemoteWriteParticipant.ts:59-110; BD-Matter-ClientNode-WriteNotThroughCache).
type OnboardingChecks ¶
type OnboardingChecks uint8
OnboardingChecks are the identity checks an attached code passed. A check runs only when the node's side of it is known.
const ( // OnboardingCheckedVendor says the code's vendor id equals the node's. OnboardingCheckedVendor OnboardingChecks = 1 << iota // OnboardingCheckedDiscriminator says the code's discriminator equals // the one the node advertised while it was commissionable. OnboardingCheckedDiscriminator // OnboardingCheckedProduct says the code's product id equals the // node's. It is compared only together with the vendor id. OnboardingCheckedProduct )
type OnboardingCode ¶
type OnboardingCode struct {
// Code is the code as entered, normalised: a QR code's "MT:…" text, or
// a manual pairing code's 11 or 21 digits. It is a secret:
// [SecretCode.Reveal] reads it.
Code SecretCode
// Source tells whether the device accepted the code or it was attached
// afterwards.
Source OnboardingSource
// StoredAt is when the code was stored.
StoredAt time.Time
// Checks are the identity checks an attached code passed; 0 for a
// paired one, which needs none, and for an attached one whose node
// had nothing to compare with.
Checks OnboardingChecks
}
OnboardingCode is a node's stored onboarding code.
func (OnboardingCode) Codes ¶
func (c OnboardingCode) Codes() (qr, manual SecretCode, err error)
Codes are the two forms to show or print: the QR code's text and the manual pairing code. A stored QR code yields both — the manual code is the short form, or the 21-digit form with the vendor and product ids when the code's commissioning flow is not Standard, as connectedhomeip generates it (src/setup_payload/ManualSetupPayloadGenerator.cpp:116 at 6170af84). A stored manual code yields itself and no QR code: it carries four of the discriminator's twelve bits and neither the commissioning flow nor the discovery capabilities, and none of those is made up.
func (OnboardingCode) GoString ¶
func (c OnboardingCode) GoString() string
GoString keeps the code out of a %#v.
func (OnboardingCode) LogValue ¶
func (c OnboardingCode) LogValue() slog.Value
LogValue keeps the code out of a log record.
func (OnboardingCode) String ¶
func (c OnboardingCode) String() string
String keeps the code out of a formatted value.
type OnboardingMismatchError ¶
type OnboardingMismatchError struct {
// Field is the identity field that differs: one of
// [OnboardingCheckedVendor], [OnboardingCheckedProduct] and
// [OnboardingCheckedDiscriminator].
Field OnboardingChecks
// Code is the code's value of the field.
Code uint16
// Node is the node's value: its vendor or product id, or the
// discriminator it advertised — shifted to the code's 4 bits when the
// code is a manual one, as compared.
Node uint16
}
OnboardingMismatchError is the mismatch Node.SetOnboardingCode reports: the code names another device. errors.Is(err, ErrOnboardingMismatch) holds for it. None of its values is a secret: vendor and product ids are public, the discriminator is advertised.
func (*OnboardingMismatchError) Error ¶
func (e *OnboardingMismatchError) Error() string
Error is the mismatch in words.
func (*OnboardingMismatchError) Is ¶
func (e *OnboardingMismatchError) Is(target error) bool
Is reports target as ErrOnboardingMismatch.
type OnboardingSource ¶
type OnboardingSource uint8
OnboardingSource tells how a node's onboarding code came to be stored.
const ( // OnboardingPaired is the code the node was commissioned with: the // device accepted its passcode. OnboardingPaired OnboardingSource = 1 // OnboardingAttached is a code added after commissioning // ([Node.SetOnboardingCode]). Its passcode is unproven: a commissioned // device offers no way to test one. OnboardingAttached OnboardingSource = 2 )
type PeerAddress ¶ added in v0.10.3
type PeerAddress = handshake.PeerAddress
PeerAddress is a node on a fabric: the fabric's index and the node's id.
type Properties ¶
type Properties struct {
SupportsThread, SupportsWifi, SupportsEthernet bool
// RootEndpointServerList is the root endpoint's ServerList.
RootEndpointServerList []uint32
MainsPowered bool
BatteryPowered bool
// IntermittentlyConnected: the root serves IcdManagement.
IntermittentlyConnected bool
// LongIdleTimeOperating: an ICD in Long Idle Time mode.
LongIdleTimeOperating bool
// IdleModeDuration is IcdManagement's IdleModeDuration.
IdleModeDuration *time.Duration
ThreadSleepyEndDevice bool
// SpecificationVersion is BasicInformation's SpecificationVersion.
SpecificationVersion *uint32
// DeviceTypes are the device types of every endpoint, in id order.
DeviceTypes []uint32
ThreadActive, WifiActive, EthernetActive *bool
ThreadPan *uint64
ThreadChannel *uint16
}
Properties are a node's physical properties — matter.js PhysicalDeviceProperties (packages/protocol/src/peer/PhysicalDeviceProperties.ts:32-61 at db021da0) as NodePhysicalProperties computes them from the image (packages/node/src/node/NodePhysicalProperties.ts:30-194). A pointer field is nil while unknown.
func (Properties) Medium ¶ added in v0.13.0
func (p Properties) Medium() peer.Medium
Medium is the part of the properties a peer's network profile is selected by (client/peer.NetworkProfiles.ForPeer, NetworkProfile.ts:184-221 at b25ed960).
func (Properties) Specification ¶ added in v0.12.1
func (p Properties) Specification() (SpecVersion, bool)
Specification is the node's specification version, decoded from Properties.SpecificationVersion; false while it is unknown or zero (absent before BasicInformation revision 3, the specification says).
type ReadPaths ¶ added in v0.10.3
type ReadPaths = interaction.ReadRequest
ReadPaths are the paths and filters of a read, the part of ReadRequest the read sends: Attributes (the attribute paths, wildcards allowed), Events (the event paths), EventFilters, DataVersionFilters, and NoFabricFilter (true reads fabric-scoped lists unfiltered). A ReadRequest's fields are promoted:
var req client.ReadRequest
req.Attributes = []client.AttributePath{client.ClusterAt(1, onoffdef.ClusterID)}
type ReadRequest ¶
type ReadRequest struct {
interaction.ReadRequest
// IncludeKnownVersions skips the version filters, so the peer sends
// every value (ClientRead.ts:12).
IncludeKnownVersions bool
}
ReadRequest is a read through the node — matter.js ClientRead (packages/protocol/src/action/client/ClientRead.ts:15 at b25ed960): the paths and filters it sends (ReadPaths, embedded as ReadRequest, its fields promoted) and IncludeKnownVersions.
type Record ¶
type Record struct {
// PeerAddress is our fabric index and the node's node id; nil while
// the node is not commissioned (:928-932).
PeerAddress *PeerAddress
// Addresses are the node's known network addresses; nil when the node
// has not been located (:942-947).
Addresses []NetworkAddress
// Hostname is the host the commissionable advertisement's SRV record
// named (:949-959).
Hostname string
// OperationalHost is the operational SRV target that owned the
// node's address (Addresses' first) when it was last reached —
// peer.Descriptor.OperationalHost, saved and restored with the peer;
// empty when unknown, and in a record stored before it existed. Not
// Hostname, the commissionable advertisement's host. This module's:
// matter.js keeps the operational address only.
OperationalHost string
// DiscoveredAt is when the node was discovered (:961-965); stored in
// milliseconds.
DiscoveredAt time.Time
// CommissionedAt is when the node was commissioned, zero when it is
// not (:979-983); stored in milliseconds.
CommissionedAt time.Time
// FabricIndexOnPeer is the fabric index the node assigned us, 0 when
// unknown (:985-993) — not PeerAddress.FabricIndex, which is ours.
FabricIndexOnPeer uint8
// TTL is the discovery record's time to live, 0 when unknown
// (:995-999); stored in seconds. An unknown TTL expires after
// [DefaultTTL] (Peers.ts:959-966).
TTL time.Duration
// DeviceIdentifier is the commissionable instance id (:1001-1005).
DeviceIdentifier string
// Discriminator is the long discriminator, nil when unknown
// (:1007-1011).
Discriminator *uint16
// CommissioningMode is the last known commissioning mode (:1013-1017).
CommissioningMode uint8
// VendorID and ProductID are the announced ids, nil when unknown or
// announced as 0 (:1019-1029, RemoteDescriptor.ts:214-221).
VendorID, ProductID *uint16
// AttestedVendorID and AttestedProductID are the attested ids: the
// BasicInformation VendorID and ProductID the node reported when it
// was commissioned, which device attestation validated against the
// node's Certification Declaration (the declaration's vendor_id is
// that VendorID and its product_id_array holds that ProductID). They
// are set together or not at all, and only when the DAC chain was
// verified up to a production root, the declaration is not the Matter
// test CD signer's and no error finding stands; nil when unknown — a node
// commissioned before the field existed, one whose attestation ran
// without a trust store, failed or had an error finding the policy
// accepted, one not commissioned (a decommission clears them). They are not the announced VendorID and ProductID
// above, and not the DAC's ids, which a white-label product's
// declaration may name as dac_origin_vendor_id/product_id instead.
// Added by review II decision 105, for the OTA provider's identity
// check (controller/softwareupdate).
AttestedVendorID, AttestedProductID *uint16
// DeviceType is the announced device type, nil when unknown
// (:1031-1035).
DeviceType *uint32
// DeviceName is the announced device name (:1037-1041).
DeviceName string
// RotatingIdentifier is the announced rotating id (:1043-1047).
RotatingIdentifier string
// PairingHint is the announced pairing hint, nil when unknown
// (:1049-1053).
PairingHint *uint32
// PairingInstructions are the announced pairing instructions
// (:1055-1059).
PairingInstructions string
// ReportedSessionParameters are the session parameters the node
// reported in its most recent session, nil when none (:1061-1065).
ReportedSessionParameters *SessionParameters
// AdvertisedIntervals are the SII, SAI and SAT the node announced, nil
// when it announced none (:1067-1071).
AdvertisedIntervals *AdvertisedIntervals
// TCPUnsupported is set when a TCP session reported no TCP server
// support (CommissioningClient.ts:1108-1113): the peer's descriptor flag,
// saved with it (:737, :761 at db021da0).
TCPUnsupported bool
// TCPSupport is the announced transports bitmap (T), nil when unknown
// (:1080-1084).
TCPSupport *SupportedTransports
// LongIdleTimeOperatingMode is the announced ICD mode, nil when
// unknown (:1086-1090).
LongIdleTimeOperatingMode *bool
}
Record is a node's commissioning record: who the node is on our fabric, where it was found and what it announced. It is matter.js CommissioningClient.State's nonvolatile part (CommissioningClient.ts:927-1091); onlineAt and offlineAt (:967-977) are not persisted there and not kept here. A zero value is unknown.
type RecordedEvent ¶
RecordedEvent is one event a node's history holds: the event as the peer reported it and Decoded, its payload decoded through the event's definition — what Hooks.Event receives as value: the raw spec.Node when the cluster or event has no definition, nil without a payload.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry is the controller's set of client nodes — matter.js Peers (node/client/Peers.ts:93-933 at db021da0), the ServerNode's container of ClientNodes: it restores every stored node, starts the commissioned ones, allocates local ids, finds or creates a node for a discovered device or a peer address, serializes commission and decommission per node, culls expired commissionable nodes and addresses, and reacts to a peer's BasicInformation events. It owns its nodes: a node is created and deleted through it. It is safe for concurrent use.
A node whose fabric another administrator removed while no subscription to it was active stays commissioned, and commissioning the device again finds that node by its commissionable instance and is refused with ErrAlreadyCommissioned until the node is erased — as matter.js at db021da0: a leave event without an active subscription is ignored (Peers.ts:856-863), Peers.forDescriptor hands out the node the descriptor matches (Peers.ts:371-390; its `find` is Peers.ts:981-991, the ClientNodeFactory implementation), and CommissioningClient.commission refuses a node with a peer address (CommissioningClient.ts:204-209).
func NewRegistry ¶
func NewRegistry(cfg RegistryConfig) (*Registry, error)
NewRegistry builds the registry and restores every node its store holds — Peers.initialize (Peers.ts:123-152): synchronous, nothing started. A commissioned node's protocol peer is bound from its record (CommissioningClient.ts:139-142, #bindPeer :685-714). A node that fails to load is logged and skipped (:141-147). The id counter moves past every stored "peerN" (ClientNodeStores.ts:44-54).
func (*Registry) Close ¶
Close closes the registry and its nodes — Peers.close (Peers.ts:516-527): closed, the expiry timer cancelled, the running fabric operations' registrations and the cull drained, every node closed. The stored nodes stay. It is idempotent.
It returns the nodes' errors joined. A node whose stop outlasted ctx is closed and offline, with no flush timer armed, and completes its stop — the queued report jobs, then the store's final flush — by itself (Node.Stop); a host that closes its database right after such a Close loses that flush, and nothing of the registry writes to the database again once the node's queue has ended. A second Close closes the nodes again and waits, within its own ctx, for the stops the first could not wait for; it returns nil once every node's stop is complete.
func (*Registry) Commission ¶
Commission commissions the node — ClientNode.commission (node/ClientNode.ts:162-166) over CommissioningClient.commission (CommissioningClient.ts:170-330), as the node's fabric operation: a node with a peer address is ErrAlreadyCommissioned (:173-175); the fabric is the option's, else the first (:197-218), one of ours (:214-218); a node without an address is ErrNotLocated (:220-223); the commissioner commissions it over the addresses and the record's discovery data (:252-269, :290); the record takes the peer address, the commissioning time and our fabric index on the peer (:291-293) and the peer's descriptor (:296); the node is bound to its peer; the settings take the default subscription and AutoSubscribe (:308-314) and the node is marked newly commissioned (:314); record and settings are saved (:316) and the node started (:327) — an error of its initial read is returned and the node stays commissioned. A commissioner error leaves the node as it was.
The node's start is reported through o.Progress as the step commissioner.StepSubscribe 21.1 — started, then succeeded or failed with the start's error. It is never skipped: every commission that succeeds starts the node, and one that fails earlier reports nothing after its failed step, as matter.js reports nothing after a failure (ControllerCommissioningFlow.ts:437-465 at db021da0).
func (*Registry) Commissioned ¶
Commissioned are the commissioned operational nodes (Node.IsCommissioned) — a group address names no commissioned node, and a node that failed to load is none — Peers.commissioned (packages/node/src/node/client/ Peers.ts:416-419 at b25ed960: nodeType "client" and lifecycle.isCommissioned).
func (*Registry) CompleteCommissioning ¶ added in v0.13.0
func (r *Registry) CompleteCommissioning(ctx context.Context, nodeID uint64, o CompleteOptions) (*Node, error)
CompleteCommissioning finishes, on this registry, a commissioning another commissioner ran up to its operational hand-off (PASE, the NOC, commissioner.Options.FinalizeCommissioning) — Peers.completeCommissioning (packages/node/src/node/client/Peers.ts:236-359 at db021da0): the node of nodeID on the shared fabric, unless it is commissioned already (ErrAlreadyCommissioned, :258-266), is created, its peer seeded with the discovery data and session parameters (:278-287), set up as a commission sets it up and started (:289-300); CommissioningComplete goes out with the extended fail-safe response timeout (:302-314), and a status or error code other than Ok is a commissioner.CommissioningError (:316-340). Any failure up to an Ok deletes the node, so none is left behind (:341-353). On the address of a node that failed to load the fabric operation is refused with its load error and nothing is erased (Peers.ts:278, :282, :641 at b25ed960; Registry.Forget drops it).
func (*Registry) Decommission ¶
Decommission removes the node from its fabric and deletes it — matter.js ClientNode.decommission (packages/node/src/node/ClientNode.ts:200-210 at b25ed960) as the node's fabric operation: a commissioned node is decommissioned first (CommissioningClient.decommission, CommissioningClient.ts:340-446), then the node is deleted (:208). A removal the peer refused, or one that was not confirmed, returns its error and keeps the node. A node that failed to load is refused with its load error and nothing is erased (:175-178, assertNotGone); Registry.Forget drops it.
func (*Registry) Erase ¶
Erase deletes every node — Peers.erase (Peers.ts:495-514): one that cannot be deleted is closed and dropped instead, its stored data left, the failures logged.
func (*Registry) ForAddress ¶
func (r *Registry) ForAddress(addr PeerAddress, id string) (*Node, error)
ForAddress is the node of peer address addr, created when there is none — Peers.forAddress (Peers.ts:458-499 at db021da0): the address must be on one of our fabrics (:459-461); the creation is serialized (:468-471); a new node takes id when given (:477-483, :960; reserved, so no allocation hands it out again) and an allocated one otherwise, joins the registry and takes the address, bound to its peer but neither started nor auto-subscribed (:487-495).
func (*Registry) ForDevice ¶
ForDevice is the node of a device the scanner found, created when the registry has none — Peers.forDescriptor (Peers.ts:371-390). A node matches by the device's instance id (Factory.find :981-991, RemoteDescriptor.is RemoteDescriptor.ts:37-50); a match under decommission is waited for and the search repeated (:374-381); a match is refreshed from the device (:382-388, the record's applyDevice); otherwise a new node is created with id, or an allocated one when id is "" (:389; the id is the local id a newly discovered node takes, matter.js Discovery.InstanceOptions.id, packages/node/src/behavior/system/controller/discovery/Discovery.ts:269, :355-357, :505-513 at db021da0 — a found node keeps its own; an id another node holds is ErrConfig; a given id is reserved, so no allocation hands it out again). The host runs discovery.Scanner and hands the device over; Commission commissions the node. A device known by its address alone — no DNS-SD answer, no instance id, its Addresses only (controller.DeviceAt) — is a supported input: it matches no node and a new one is created, as matter.js's MatterController.commission hands Peers.forDescriptor a descriptor of the known address only (packages/matter.js/src/MatterController.ts:545-549 at db021da0) and RemoteDescriptor.is matches nothing on an absent identifier (RemoteDescriptor.ts:37-50).
func (*Registry) Forget ¶
Forget drops n from the registry and the database without reaching it: its subscriptions close, its rows and its peer go. For a node that no longer exists — the controller's former own node (phase 37) — or a node that failed to load, which no fabric operation touches; not for a node still on the fabric, which [Node.Decommission] removes from both sides. A store that fails to erase the rows is returned and the node, closed, stays in the registry, so a Forget again retries the erase.
func (*Registry) Get ¶
Get is the node of local id, nil when there is none.
A local id is not an identity: once a node is gone and its data erased, a node created later may receive the same id (ClientNodeStores.ts:71-75). Hold a node by its peer address (Registry.GetByAddress) for anything that outlives a commissioning — and even an address names one device only while it stays commissioned (Peers.ts:402-411).
func (*Registry) GetByAddress ¶
func (r *Registry) GetByAddress(addr PeerAddress) *Node
GetByAddress is the node with peer address addr (Node.PeerAddress), nil when there is none: a commissioned node, or a node that failed to load whose stored record names addr. Mirrors matter.js packages/node/src/node/client/Peers.ts:421-445 at b25ed960 (Peers.get by address, through ClientNode.peerAddress).
func (*Registry) SetFabricLabel ¶ added in v0.12.1
SetFabricLabel sets the label of our fabrics, persists it with each fabric's record (commissioner.Fabric.SetLabel), and reconciles it to every commissioned node that is connected; a node that is not gets it at its next start, when the reconciliation runs again on its first SubscriptionAlive — matter.js CommissioningController.updateFabricLabel (packages/matter.js/src/CommissioningController.ts:998-1045 at db021da0): the fabric's setLabel (MatterController.ts:797-799), then validateAndUpdateFabricLabel for each connected node (:953-992), an offline node updated on its next connection. matter.js returns after the first connected node it updated (:1008-1010); every connected node gets the label here. A label longer than 32 characters is commissioner.ErrLabel; the error of each node it could not update is joined into the returned error, a refusal of the name commissioner.ErrFabricLabelConflict.
func (*Registry) Start ¶
Start brings the registry online — Peers.#nodeOnline (Peers.ts:154-169): with AutoStart every commissioned, enabled node is started in turn, an error logged and the next one started (:157-165); then the expiry timer is managed (:168).
func (*Registry) Stop ¶
Stop takes the registry offline — Peers.#nodeOffline (Peers.ts:171-176): the expiry timer is cancelled and every node stopped in turn. It returns the nodes' errors joined: a node whose stop outlasted ctx is offline and completes its stop by itself (Node.Stop); a second Stop stops every node again and waits, within its own ctx, for those.
func (*Registry) UpdateOperationalCertificate ¶
func (r *Registry) UpdateOperationalCertificate(ctx context.Context, n *Node, o CertificateUpdateOptions) error
UpdateOperationalCertificate replaces the node operational certificate of the commissioned node with one for a freshly generated key pair, as the node's fabric operation: its node id, fabric, CASE Authenticated Tags and fabric-scoped data stay. Mirrors matter.js ClientNode .updateOperationalCertificate (packages/node/src/node/ClientNode.ts:218-224 at b25ed960) under Peers.runOperationalCertificateUpdate (Peers.ts:630-632), over CommissioningClient.updateOperationalCertificate (CommissioningClient.ts:519-570), which hands the update to commissioner.Commissioner.UpdateOperationalCertificate (the sequence, the failure table and what ctx ends are documented there).
A node without a peer address is ErrNotCommissioned (:520-525). The update reads the node's CurrentFabricIndex first; once that read succeeded, the read index replaces Record.FabricIndexOnPeer — with a warning when another one was stored (:562-570) — also when the update fails afterwards: a *commissioner.CertificateUpdateError that carries an index stores it and is returned unchanged; a failing record save is logged and does not replace the update's error (:533-537, :544-555). While the update runs, a commission, decommission or second update of the node is ErrFabricOperationInProgress.
type RegistryConfig ¶
type RegistryConfig struct {
// Store holds every node's image, settings and record; nil is a
// [MemoryStore].
Store Store
// Commissioner commissions the nodes and binds their interactions.
// Required.
Commissioner *commissioner.Commissioner
// Peers is the peer set the commissioner works on. Required.
Peers *peer.Set
// Exchanges is the controller's exchange manager. Required.
Exchanges *exchange.Manager
// Fabrics are our fabrics — matter.js FabricManager for the registry;
// the first is the default of a commission. At least one is required.
Fabrics []*commissioner.Fabric
// Subscriptions is the controller's subscription registry, the one
// the commissioner binds.
Subscriptions *interaction.Subscriptions
// AutoStart starts every commissioned, enabled node in Start —
// matter.js NetworkServer.autoStartCommissionedPeers (NetworkServer.ts:242,
// read by Peers.#nodeOnline, Peers.ts:164-175 at db021da0). matter.js
// defaults it to true; the registry, a seam below the controller,
// leaves it to its composer: controller.New sets it unless
// controller.Config.ManualStart, so the controller's default is
// matter.js's.
AutoStart bool
// Node is the template of every node: its Hooks, Logger, Clock, Rand
// and FlushInterval. ID, Peer, Interaction and Store are the
// registry's; the commissioning choices (AutoSubscribe,
// DefaultSubscription, NewlyCommissioned, NoInitialRead) are a
// commission's ([CommissionOptions]).
Node Config
// HooksFor, when set, returns the hooks of the node with local id in
// place of Node.Hooks, so a host tells its nodes' callbacks apart.
HooksFor func(id string) Hooks
// Logger receives the registry's diagnostics; nil discards them.
Logger *slog.Logger
// Clock paces the expiry of discovered addresses and nodes; nil is the
// system clock.
Clock exchange.Clock
// MaxImageBytesPerNode is each node's image quota: the bytes its
// image is charged, its attribute values in their stored form and what
// each endpoint, cluster, attribute and TLV element of it holds in
// memory ([DefaultMaxImageBytesPerNode]). A report
// that would raise a node's image above it is not applied, and an
// image stored above it is cut back to what the node's structure
// names when it loads. Zero or less is [DefaultMaxImageBytesPerNode].
MaxImageBytesPerNode int
}
RegistryConfig is what a Registry works with.
type Report ¶ added in v0.10.3
type Report = interaction.Report
Report is a read's data, or one subscription report's, its chunks merged: Attributes (values), Statuses (attribute paths answered with a status), Events, EventStatuses. [Report.Values] collects one cluster's values for a generated <cluster>def.StateFrom.
type Result ¶ added in v0.10.3
type Result = interaction.Result
Result is a command's answer: the response Command and its Fields (HasFields false for a status answer), or the Status and ClusterStatus.
type SecretCode ¶
type SecretCode struct {
// contains filtered or unexported fields
}
SecretCode is the text of an onboarding code: a QR code's "MT:…" or a manual pairing code's digits. It carries the device's setup passcode, so it is redacted wherever a value is rendered without being asked for: under every fmt verb, in a log record of either slog handler, in encoding/json and every encoding that takes an encoding.TextMarshaler — also as a field of a host's own struct. SecretCode.Reveal is the one way to the text. The zero value is no code.
A SecretCode is not comparable; compare the revealed texts.
func (SecretCode) GoString ¶
func (s SecretCode) GoString() string
GoString keeps the text out of a %#v.
func (SecretCode) LogValue ¶
func (s SecretCode) LogValue() slog.Value
LogValue keeps the text out of a log record.
func (SecretCode) MarshalText ¶
func (s SecretCode) MarshalText() ([]byte, error)
MarshalText keeps the text out of encoding/json and every other encoding that takes an encoding.TextMarshaler. There is no UnmarshalText: a redacted value does not come back.
func (SecretCode) Reveal ¶
func (s SecretCode) Reveal() string
Reveal is the code's text — the secret. Call it where the code is shown or printed, and nowhere a log or a serialiser can see the result.
func (SecretCode) String ¶
func (s SecretCode) String() string
String keeps the text out of a formatted value.
type SessionParameters ¶ added in v0.10.3
type SessionParameters = sessionparams.Parameters
SessionParameters are the session parameters a node reported.
type SpecVersion ¶ added in v0.12.1
type SpecVersion struct {
Major, Minor, Patch, Reserved uint8
}
SpecVersion is a BasicInformation SpecificationVersion decoded into its four component bytes, most significant first: 0x01040200 is version 1.4.2, Reserved 0 — the layout matter.js documents for the attribute (packages/types/src/clusters/basic-information.d.ts:168-200 at db021da0; Specification.SPECIFICATION_VERSION 0x01060100 is 1.6.1, packages/model/src/common/Specification.ts:110). Compare versions by SpecVersion.Uint32, over all 32 bits, as the specification says.
func SpecVersionOf ¶ added in v0.12.1
func SpecVersionOf(v uint32) SpecVersion
SpecVersionOf decodes a SpecificationVersion attribute value.
func (SpecVersion) String ¶ added in v0.12.1
func (v SpecVersion) String() string
String is "Major.Minor.Patch" ("1.4.0"), with ".Reserved" appended when that byte is not zero.
func (SpecVersion) Uint32 ¶ added in v0.12.1
func (v SpecVersion) Uint32() uint32
Uint32 is the attribute value of v.
type StatusError ¶ added in v0.10.3
type StatusError = interaction.StatusError
StatusError is an IM status other than Success: Status, the ClusterStatus when the peer sent one, and the attribute Path for an attribute's status.
type Store ¶
type Store interface {
// Load returns every stored endpoint of the node with every cluster's
// values; an unknown node has none.
Load(nodeID string) ([]StoredEndpoint, error)
// Save stores values of one cluster: a nil value deletes its key
// (EndpointStore.ts:58-131); version is the cluster's DataVersion, nil
// for an unknown one.
Save(nodeID string, ep uint16, cluster uint32, values map[uint32][]byte, version *uint32) error
// EraseCluster removes one cluster (DatasourceCache.erase,
// LocalWriter.ts:38-40).
EraseCluster(nodeID string, ep uint16, cluster uint32) error
// EraseEndpoint removes an endpoint (ClientEndpointStore.erase).
EraseEndpoint(nodeID string, ep uint16) error
// EraseNode removes the node (ClientNodeStore.erase,
// ClientNodeStore.ts:88-107).
EraseNode(nodeID string) error
// NodeIDs are the ids of the nodes the store holds, sorted — matter.js
// ClientNodeStores.knownIds (storage/client/ClientNodeStores.ts:117-121),
// the storage contexts restored at construction (:44-57). A [Registry]
// restores one node per id.
NodeIDs() ([]string, error)
}
Store persists a node's image: endpoint → cluster → attribute values and the cluster's DataVersion. It replaces matter.js's ClientNodeStore, ClientEndpointStore and LocalWriter (packages/node/src/storage/client/ at 0ceb202d), whose layout is nodes/<id>/endpoints/<ep>/<cluster>/<attr> with the version under "__version__". A value is the attribute's TLV encoding. Implementations must be safe for concurrent use.
type StoredCluster ¶
StoredCluster is one cluster of an endpoint as a Store holds it.
type StoredEndpoint ¶
type StoredEndpoint struct {
Number uint16
Clusters []StoredCluster
}
StoredEndpoint is one endpoint of a node as a Store holds it.
type SubscribeOptions ¶
type SubscribeOptions struct {
Attributes []AttributePath
Events []EventPath
// NoFabricFilter subscribes unfiltered (fabricFilter false). The cache
// keeps the values of one fabric view: those of interactions with its
// recorded filter, which adopts the default subscription's at Start and
// at [Node.SetDefaultSubscription] (ClientStructure.ts:343-390,
// :573-576 at db021da0).
NoFabricFilter bool
// KeepSubscriptions keeps our other subscriptions with the peer
// (keepSubscriptions true); the default subscription replaces them.
KeepSubscriptions bool
// MinIntervalFloor and MaxIntervalCeiling bound the reporting interval;
// nil takes the node's physical defaults ([Node.IntervalBounds]).
MinIntervalFloor *time.Duration
MaxIntervalCeiling *time.Duration
}
SubscribeOptions narrows the default subscription — the fields of matter.js Subscribe a NetworkClient.State.defaultSubscription overrides (NetworkClient.ts:121-128). A nil list keeps the default (every attribute, every event urgent); a non-nil one, empty included, replaces it.
type SubscribePaths ¶ added in v0.13.0
type SubscribePaths = interaction.SubscribeRequest
SubscribePaths are a subscription as it is sent, the part of SubscribeRequest the subscription sends: the paths and filters of a read (ReadPaths); MinIntervalFloor and MaxIntervalCeiling (Interval; nil for the defaults, the node's bounds applied over them); ReplaceSubscriptions (false, the default, keeps the other subscriptions with the peer — matter.js keepSubscriptions true); Updated, called with every report that carries data, the priming report too, on the report's exchange (keep it short); Closed, called once the subscription ended; Sustain, which re-establishes a lost subscription. The Subscription it returns ends with [Subscription.Close] or with the node; its Done channel closes then. A SubscribeRequest's fields are promoted.
type SubscribeRequest ¶ added in v0.10.3
type SubscribeRequest struct {
interaction.SubscribeRequest
// IncludeKnownVersions skips the version filters — in the first
// request and, for a sustained subscription, in every later one it
// sends — so the peer sends every value (:123-124).
IncludeKnownVersions bool
}
SubscribeRequest is a subscription through the node — matter.js ClientSubscribe with ClientNodeInteraction's includeKnownVersions (packages/node/src/node/client/ClientNodeInteraction.ts:111-124 at b25ed960): what it sends (SubscribePaths, embedded, its fields promoted) and IncludeKnownVersions.
type Subscription ¶ added in v0.10.3
type Subscription = interaction.Subscription
Subscription is an established subscription: ID, MaxInterval, Done (closed when it ended) and Close (idempotent; the peer learns of it from the next report it sends).
type SupportedTransports ¶ added in v0.10.3
type SupportedTransports = discovery.SupportedTransports
SupportedTransports are the transports a node announces (its `T` TXT key).
type Timing ¶ added in v0.10.3
Timing are the peer's connection timing parameters (a zero field is the default).
type Value ¶ added in v0.12.1
Value is a decoded TLV value as the role hands it out: an attribute's value in the image and in a report (AttributeData.Value, Cluster.Value), an event's data (EventData), a command response's fields (Result.Fields). Render it with DecodeJSON, or decode it with a generated <cluster>def package's StateFrom.
func ValueOf ¶
ValueOf is e as the Value tree the role hands out — e's TLV read back — so a generated struct a call returns (camera.Provider.Send's result, a response a host built) renders through DecodeJSON like a value off the wire, without an encoder of the host's own. A nil e is ErrNoValue.
type WindowOptions ¶ added in v0.12.1
type WindowOptions struct {
// Basic opens a Basic Commissioning Window, in which the node takes its
// own passcode (the one printed on it), in place of an enhanced one
// with a fresh passcode — openBasicCommissioningWindow. The node must
// support the Basic feature ([ErrNoBasicWindow]); the window returned
// carries the timeout alone.
Basic bool
}
WindowOptions configure Node.OpenCommissioningWindow; the zero value opens an enhanced window.
type WriteOptions ¶ added in v0.10.3
type WriteOptions = interaction.WriteOptions
WriteOptions are a write's options: Timed (a TimedRequest first, for an attribute that needs one), TimedTimeout, SuppressResponse, DisableListChunking.
type WriteRequest ¶ added in v0.10.3
type WriteRequest = interaction.WriteRequest
WriteRequest is one attribute write: Path, Value (a spec.Encodable: a generated struct or request, a spec.List, or a scalar spec.Value such as spec.Uint8(20) and spec.Null[uint16]()) and DataVersion (nil for an unconditional write).
type WriteStatus ¶ added in v0.10.3
type WriteStatus = interaction.WriteStatus
WriteStatus is one path's answer to a write.
type WriteStatuses ¶ added in v0.10.3
type WriteStatuses = interaction.WriteStatuses
WriteStatuses are a write's answers, one per path; Err is the first that is not Success, as a *StatusError.
Source Files
¶
- addresses.go
- cache.go
- cluster.go
- complete.go
- config.go
- conformance.go
- doc.go
- endpoint.go
- event_history.go
- fabricops.go
- icd.go
- icd_errors.go
- image_bounds.go
- interact.go
- jobs.go
- json.go
- known.go
- label.go
- network.go
- node.go
- onboarding.go
- opcreds.go
- ping.go
- properties.go
- reactions.go
- record.go
- redact.go
- registry.go
- scope.go
- settings.go
- specversion.go
- store.go
- structure.go
- surface.go
- window.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package sqlstore is a durable client.Store on SQLite (brief AL §8; ADR 0020, stage 4): the images, settings and commissioning records of a controller's client nodes, in the tables matter_client_values and matter_client_versions.
|
Package sqlstore is a durable client.Store on SQLite (brief AL §8; ADR 0020, stage 4): the images, settings and commissioning records of a controller's client nodes, in the tables matter_client_values and matter_client_versions. |