### Install matter.js Examples Source: https://github.com/matter-js/matter.js/blob/main/README.md Install the example applications for matter.js to run them directly. Refer to the Examples readme for usage details. ```bash npm install @matter/examples ``` -------------------------------- ### Run Matter.js Sensor Example Source: https://github.com/matter-js/matter.js/blob/main/examples/device-sensor/README.md Execute this command in the examples root directory to start the Matter.js sensor example. Refer to the general Examples README for details on CLI parameters and environment variables. ```bash npm run matter-sensor ``` -------------------------------- ### Install @matter/examples Globally Source: https://github.com/matter-js/matter.js/blob/main/examples/README.md Install the @matter/examples package globally using npm. This command is useful for quickly accessing example implementations. ```bash npm i -g @matter/examples ``` -------------------------------- ### Run Robotic Vacuum Cleaner Example Source: https://github.com/matter-js/matter.js/blob/main/examples/device-robotic-vacuum-cleaner/README.md Execute this command in the examples root directory to start the Robotic Vacuum Cleaner example. Refer to the general examples README for CLI parameters and environment variables. ```bash npm run matter-rvc ``` -------------------------------- ### Run OnOff Light Example Source: https://github.com/matter-js/matter.js/blob/main/examples/device-onoff-light/README.md Execute this command in the examples root directory to run the OnOff light example. Refer to the general examples README for details on CLI parameters and environment variables. ```bash npm run matter-light ``` -------------------------------- ### Create and configure a Matter device node with full options Source: https://context7.com/matter-js/matter.js/llms.txt Create a `ServerNode` with full configuration, including custom ID, network port, commissioning details, product description, and basic information. This example also demonstrates adding an `Endpoint` and starting the server. ```typescript const server = await ServerNode.create({ id: "my-light-001", // Unique storage key network: { port: 5540 }, commissioning: { passcode: 20202021, discriminator: 3840, }, productDescription: { name: "My Smart Light", deviceType: DeviceTypeId(OnOffLightDevice.deviceType), }, basicInformation: { vendorName: "Acme Corp", vendorId: VendorId(0xfff1), productName: "Smart Light v1", productLabel: "Smart Light v1", productId: 0x8000, nodeLabel: "Living Room Light", serialNumber: "SN-001", uniqueId: "light-uuid-001", }, }); const endpoint = new Endpoint(OnOffLightDevice, { id: "onoff" }); await server.add(endpoint); // Lifecycle events server.lifecycle.commissioned.on(() => console.log("First commissioning done")); server.lifecycle.online.on(() => console.log("Node is online, fabrics:", server.state.commissioning.fabrics)); server.lifecycle.offline.on(() => console.log("Node went offline")); server.lifecycle.decommissioned.on(() => console.log("All fabrics removed")); // Session events server.events.sessions.opened.on(session => console.log("Controller connected", session)); server.events.sessions.closed.on(session => console.log("Controller disconnected", session)); await server.start(); // Non-blocking; use run() if you want it to block // After start, read commissioning pairing codes if not yet commissioned if (!server.lifecycle.isCommissioned) { const { qrPairingCode, manualPairingCode } = server.state.commissioning.pairingCodes; console.log(`Manual code: ${manualPairingCode}`); // QR code string can be rendered with QrCode.get(qrPairingCode) } // Graceful shutdown process.on("SIGINT", () => server.close().then(() => process.exit(0))); ``` -------------------------------- ### Install Matter.js Dependencies and Build Source: https://github.com/matter-js/matter.js/blob/main/examples/README.md Install all dependencies and build the Matter.js packages from a cloned repository. This is a prerequisite for using the examples directly from the source code. ```bash npm install ``` -------------------------------- ### Run matter.js Device Example for Thread Credentials Source: https://github.com/matter-js/matter.js/blob/main/docs/USAGE_THREAD.md Use this command to start a mock device for commissioning. Adjust passcode or discriminator if re-pairing is needed. BLE support can be finicky. ```bash node node_modules/@matter/examples/dist/esm/examples/DeviceNodeFull.js --storage-path=.thread --ble-enable --ble-thread-fake --passcode=20202021 --discriminator=1234 ``` -------------------------------- ### Run Air Quality Sensor Example Source: https://github.com/matter-js/matter.js/blob/main/examples/device-air-quality-sensor/README.md Execute this command to run the air quality sensor example. Ensure you are in the examples root directory. ```bash npm run matter-air-quality-sensor ``` -------------------------------- ### Run Advanced OnOff Device Node Source: https://github.com/matter-js/matter.js/blob/main/examples/device-onoff-advanced/README.md Execute the advanced OnOff device node example using Node.js. This command starts the device with its configured features. ```bash node .dist/examples/device-onoff-advanced-cli/DeviceNodeFull.js ``` -------------------------------- ### CLI Command for Composed Device (Socket Example) Source: https://github.com/matter-js/matter.js/blob/main/examples/device-composed-onoff/README.md Execute this command to start a composed device with two socket types. It specifies the shell commands to run when each socket is turned on or off. ```bash matter-composeddevice --type=socket --num=2 --on1="echo 255 > /sys/class/leds/led1/brightness" --off1="echo 0 > /sys/class/leds/led1/brightness" --type2=socket --on2="echo 255 > /sys/class/leds/led2/brightness" --off2="echo 0 > /sys/class/leds/led2/brightness" ``` -------------------------------- ### Run Composed Device Example Source: https://github.com/matter-js/matter.js/blob/main/examples/device-composed-wc-light/README.md Execute this command to run the example that implements a composed device with Window Covering and Light endpoints. Refer to the general CLI usage documentation for more parameters. ```bash npm run matter-excelsior1000 ``` -------------------------------- ### NPM Run Command for Multiple OnOff Devices Source: https://github.com/matter-js/matter.js/blob/main/examples/device-multiple-onoff/README.md Use this command when starting from TS files. The '--' separates npm run arguments from the script's arguments. This example starts two socket devices with custom shell commands for on and off states. ```bash npm run matter-multidevice -- --type=socket --num=2 --on1="echo 255 > /sys/class/leds/led1/brightness" --off1="echo 0 > /sys/class/leds/led1/brightness" --type2=socket --on2="echo 255 > /sys/class/leds/led2/brightness" --off2="echo 0 > /sys/class/leds/led2/brightness" ``` -------------------------------- ### Install Python Setuptools for Node-gyp Source: https://github.com/matter-js/matter.js/blob/main/docs/TROUBLESHOOTING.md If you encounter errors related to missing 'setuptools' during matter.js BLE builds, install it using pip. Ensure your Node.js and npm versions are up-to-date. ```bash pip install setuptools ``` -------------------------------- ### Run Matter Measured Socket Example Source: https://github.com/matter-js/matter.js/blob/main/examples/device-measuring-socket/README.md Execute this command in the examples root directory to run the measured socket device. Refer to the Examples README for general CLI parameter and environment variable documentation. ```bash npm run matter-measuredsocket ``` -------------------------------- ### Matter Shell CLI for Device Management Source: https://context7.com/matter-js/matter.js/llms.txt Install and launch the interactive Matter Shell CLI for commissioning devices, reading/writing attributes, invoking commands, and managing OTA updates. Example shows commissioning a device using a QR pairing code. ```bash # Install and launch npm install @matter/nodejs-shell npx matter-shell # Commission a device using its QR pairing code matter-node> commission pair --pairing-code MT:Y.K908000 ``` -------------------------------- ### Start the Application Source: https://github.com/matter-js/matter.js/blob/main/examples/electron-matter-controller/README.md Execute this command to launch the Electron application. ```shell npm start ``` -------------------------------- ### Setup WebSocket Connection Source: https://github.com/matter-js/matter.js/blob/main/packages/nodejs-shell/src/shell/webassets/index.html Establishes a WebSocket connection and sets up event listeners for messages and connection status. This is the initial setup for the web shell. ```javascript function setupWebSocket() { ws = new WebSocket('ws://localhost:8080'); ws.onopen = () => { logMessage('WebSocket connection opened.\n', 'info'); reconnectAttempts = 0; updateStatus('connected-node-status'); }; ws.onmessage = (event) => { logMessage(event.data, 'received'); }; ws.onclose = () => { logMessage('WebSocket connection closed.\n', 'error'); updateStatus('disconnected-node-status'); scheduleReconnect(); }; ws.onerror = (error) => { logMessage(`WebSocket error: ${error.message}\n`, 'error'); updateStatus('error-node-status'); }; } ``` -------------------------------- ### Run Smoke CO Alarm Example Source: https://github.com/matter-js/matter.js/blob/main/examples/device-smoke-co-alarm/README.md Execute this command in the examples root directory to run the Smoke CO Alarm example. ```bash npm run matter-smoke-co-alarm ``` -------------------------------- ### Start Device with Amazon Thread Network Parameters Source: https://github.com/matter-js/matter.js/blob/main/docs/USAGE_THREAD.md Use this command to start a device and connect it to an Amazon-branded Thread network. Ensure you have scanned for networks using `ot-ctl discover` and replaced the placeholder values with your network's specific details. ```bash node node_modules/@matter/examples/dist/esm/examples/DeviceNodeFull.js --storage-path=.thread --ble-enable --ble-thread-fake --passcode=20202438 --discriminator=1248 --ble-thread-panid=XXXX --ble-thread-extendedpanid=XXXXXXXXX --ble-thread-networkname=AMZN-Thread-XXXX --ble-thread-channel=XX --ble-thread-address=XXXXXXXXXXX ``` -------------------------------- ### Install Matter.js Development Dependencies Source: https://github.com/matter-js/matter.js/blob/main/README.md Clone the repository and install all necessary dependencies to set up a local development environment for matter.js. This includes building all packages. ```bash git clone https://github.com/matter-js/matter.js cd matter.js npm install ``` -------------------------------- ### Install @matter/nodejs-shell Source: https://github.com/matter-js/matter.js/blob/main/packages/nodejs-shell/README.md Install the shell app using npm. ```bash npm install @matter/nodejs-shell ``` -------------------------------- ### Create and start a minimal Matter device node Source: https://context7.com/matter-js/matter.js/llms.txt Create a minimal `ServerNode` with default settings and add an `OnOffLightDevice`. The `run()` method blocks until offline and automatically prints the QR code. ```typescript import { DeviceTypeId, Endpoint, ServerNode, VendorId } from "@matter/main"; import { OnOffLightDevice } from "@matter/main/devices/on-off-light"; // Minimal node — all defaults (port 5540, random passcode/discriminator) const node = await ServerNode.create(); await node.add(OnOffLightDevice); await node.run(); // Blocks until offline; prints QR code automatically ``` -------------------------------- ### Instantiate and Run a Server Node Source: https://github.com/matter-js/matter.js/blob/main/packages/node/src/node/README.md Use this to start and publish a Matter node. Additional functionality must be added to make the node useful. The import referencing 'matter-node.js' is necessary for Node.js-specific extensions. ```typescript import { ServerNode } from "@matter/main"; const node = await ServerNode.create(); await node.run(); ``` -------------------------------- ### Add matter.js to an Existing Project Source: https://github.com/matter-js/matter.js/blob/main/README.md Install the main matter.js package as a dependency in your existing Node.js project. For BLE support, install `@matter/nodejs-ble` separately. ```bash npm install @matter/main --save ``` -------------------------------- ### Run matter-node-shell with npx Source: https://github.com/matter-js/matter.js/blob/main/packages/nodejs-shell/README.md Start the matter-node-shell using npx, providing a unique identifier for the process. ```bash npx matter-shell ``` -------------------------------- ### CLI Command for Multiple OnOff Devices Source: https://github.com/matter-js/matter.js/blob/main/examples/device-multiple-onoff/README.md Execute this command to start two socket devices with custom shell commands for on and off states. Ensure you use different storage locations, network ports, and passcodes if starting multiple parallel processes. ```bash matter-multidevice --type=socket --num=2 --on1="echo 255 > /sys/class/leds/led1/brightness" --off1="echo 0 > /sys/class/leds/led1/brightness" --type2=socket --on2="echo 255 > /sys/class/leds/led2/brightness" --off2="echo 0 > /sys/class/leds/led2/brightness" ``` -------------------------------- ### Run Matter.js Server Source: https://github.com/matter-js/matter.js/blob/main/examples/README.md Execute the Matter.js server using npm. This command is used to start the server when using the Matter.js library directly from a cloned repository. ```bash npm run matter-device ``` -------------------------------- ### Run Matter Device (Bash) Source: https://github.com/matter-js/matter.js/blob/main/examples/device-onoff/README.md Starts a MatterServer (DeviceNode) listening on port 5540 and announces it as a socket device. Use this command to run the device from compiled JavaScript files. ```bash matter-device ``` -------------------------------- ### Run Multiple Instances Source: https://github.com/matter-js/matter.js/blob/main/packages/nodejs-shell/README.md Starts multiple instances of the matter shell using a nodenum to ensure separate configuration directories and communication ports. ```bash # From matter-node-shell top-level npm run shell 1 ``` -------------------------------- ### Display help for a specific command Source: https://github.com/matter-js/matter.js/blob/main/packages/nodejs-shell/README.md Get detailed help for a specific command, such as 'config', by appending '--help' to the command. ```shell > config config loglevel Manage Console and File LogLevels config logfile Manage Logfile path config ble-hci Manage BLE HCI ID (Linux) config wifi-credentials Manage Wi-Fi credentials used in commissioning process config thread-credentials Manage Thread credentials used in commissioning process config dcl-test-certificates Manage DCL test certificate fetching Done ``` -------------------------------- ### ServerNode.create() Source: https://context7.com/matter-js/matter.js/llms.txt Creates and starts a Matter device node. This is the top-level container for endpoints and manages network presence, commissioning, and storage. ```APIDOC ## ServerNode.create() ### Description Creates and starts a Matter device node. This is the top-level container for endpoints and manages network presence, commissioning, and storage. ### Method `ServerNode.create(options?: ServerNodeCreateOptions)` ### Parameters #### Options - **id** (string) - Optional - Unique storage key for the node. - **network** (object) - Optional - Network configuration. - **port** (number) - The port to use for Matter communication. - **commissioning** (object) - Optional - Commissioning parameters. - **passcode** (number) - The passcode for commissioning. - **discriminator** (number) - The discriminator for commissioning. - **productDescription** (object) - Optional - Description of the product. - **name** (string) - The name of the product. - **deviceType** (number) - The Matter Device Type ID. - **basicInformation** (object) - Optional - Basic information about the device. - **vendorName** (string) - The name of the vendor. - **vendorId** (number) - The Vendor ID. - **productName** (string) - The name of the product. - **productLabel** (string) - The label of the product. - **productId** (number) - The Product ID. - **nodeLabel** (string) - The label of the node. - **serialNumber** (string) - The serial number of the device. - **uniqueId** (string) - A unique identifier for the device. ### Request Example ```typescript import { ServerNode } from "@matter/main"; // Minimal node const node = await ServerNode.create(); await node.run(); // Full configuration example const server = await ServerNode.create({ id: "my-light-001", network: { port: 5540 }, commissioning: { passcode: 20202021, discriminator: 3840, }, productDescription: { name: "My Smart Light", deviceType: DeviceTypeId(OnOffLightDevice.deviceType), }, basicInformation: { vendorName: "Acme Corp", vendorId: VendorId(0xfff1), productName: "Smart Light v1", productLabel: "Smart Light v1", productId: 0x8000, nodeLabel: "Living Room Light", serialNumber: "SN-001", uniqueId: "light-uuid-001", }, }); await server.start(); ``` ### Response Returns a `ServerNode` instance. ### Lifecycle Events - **commissioned**: Emitted when the node is commissioned for the first time. - **online**: Emitted when the node comes online. - **offline**: Emitted when the node goes offline. - **decommissioned**: Emitted when all fabrics are removed. ### Session Events - **sessions.opened**: Emitted when a controller session is opened. - **sessions.closed**: Emitted when a controller session is closed. ### Graceful Shutdown ```typescript process.on("SIGINT", () => server.close().then(() => process.exit(0))); ``` ``` -------------------------------- ### Importing the Matter Model Source: https://github.com/matter-js/matter.js/blob/main/packages/model/README.md Import the Matter API from the @matter/model package to start working with the Matter object model. ```APIDOC ## Import Matter Model ### Description Import the main Matter API entrypoint to access the object model. ### Code ```ts import { Matter } from "@matter/model"; ``` ``` -------------------------------- ### Run matter-node-shell from node_modules Source: https://github.com/matter-js/matter.js/blob/main/packages/nodejs-shell/README.md Alternatively, run the shell from the installed node_modules directory using npm run. ```bash cd node_modules/@matter/nodejs-shell npm run shell ``` -------------------------------- ### CLI Command for Matter Bridge with On/Off Scripts Source: https://github.com/matter-js/matter.js/blob/main/examples/device-bridge-onoff/README.md Use this command to start a Matter bridge that exposes two devices: a light and a socket. It configures specific shell commands to control the brightness of system LEDs when the devices are turned on or off. ```bash matter-bridge --num=2 --on1="echo 255 > /sys/class/leds/led1/brightness" --off1="echo 0 > /sys/class/leds/led1/brightness" --type2=socket --on2="echo 255 > /sys/class/leds/led2/brightness" --off2="echo 0 > /sys/class/leds/led2/brightness" ``` -------------------------------- ### Compose Multiple Devices into One Node with 'parts' Source: https://context7.com/matter-js/matter.js/llms.txt Bundle multiple sub-devices into a single Matter node by using the 'parts' array in the ServerNode constructor. This example composes a roller shade and a valance light. ```typescript import { ServerNode, VendorId } from "@matter/main"; import { MovementDirection, MovementType, WindowCoveringServer } from "@matter/main/behaviors/window-covering"; import { OnOffLightDevice, OnOffLightRequirements } from "@matter/main/devices/on-off-light"; import { WindowCoveringDevice } from "@matter/main/devices/window-covering"; const LiftingWindowCoveringServer = WindowCoveringServer.with("Lift", "PositionAwareLift"); class RollerShade extends LiftingWindowCoveringServer { override async handleMovement( type: MovementType, reversed: boolean, direction: MovementDirection, targetPercent100ths?: number, ) { console.log( "Moving shade", direction === MovementDirection.Open ? "OPEN" : "CLOSE", targetPercent100ths !== undefined ? `to ${targetPercent100ths / 100}%` : "", ); await super.handleMovement(type, reversed, direction, targetPercent100ths); } } class ValanceLight extends OnOffLightRequirements.OnOffServer { override initialize() { this.events.onOff$Changed.on(v => console.log(`Valance: ${v ? "illuminated" : "dark"}`)); } } // Compose two sub-devices into one node via "parts" const node = new ServerNode({ id: "roller-shade-combo", commissioning: { passcode: 20202021, discriminator: 3840 }, basicInformation: { vendorName: "Acme Corp", vendorId: VendorId(0xfff1), productName: "EZ-Nite Roller Shade", productId: 0x8002, serialNumber: "shade-001", }, parts: [ { type: WindowCoveringDevice.with(RollerShade), id: "shade" }, { type: OnOffLightDevice.with(ValanceLight), id: "valance" }, ], }); await node.run(); ``` -------------------------------- ### Run Matter Shell over WebSockets Source: https://github.com/matter-js/matter.js/blob/main/packages/nodejs-shell/README.md Start the matter shell with the '--webSocketInterface' flag to enable interaction via websockets. The port can be specified using '--webSocketPort NNNN'. ```bash npm run shell 2 -- --webSocketInterface --webSocketPort 3000 ``` -------------------------------- ### Extend and customize Matter.js cluster servers Source: https://context7.com/matter-js/matter.js/llms.txt Shows how to extend default cluster server behavior classes to intercept commands, manage state manually, and react to attribute changes. Includes examples of custom command handling and scoped event listeners. ```typescript import { ServerNode } from "@matter/main"; import { OnOffServer } from "@matter/main/behaviors"; import { OnOff } from "@matter/main/clusters"; import { OnOffLightDevice, OnOffLightRequirements } from "@matter/main/devices/on-off-light"; // Extend the default OnOff server class MyOnOffServer extends OnOffLightRequirements.OnOffServer { // Intercept the "on" Matter command override async on() { console.log("Hardware: turning relay ON"); // Call super to update state and send response await super.on(); } // Override "off" without calling super — manage state manually override off() { console.log("Hardware: turning relay OFF"); this.state.onOff = false; // Direct state mutation within transaction } // initialize() runs once when the behavior starts override initialize() { // React to any state change (including remote writes, not just commands) this.events.onOff$Changed.on(value => { console.log(`Reactive handler: light is now ${value ? "ON" : "OFF"}`); }); // You can also use reactTo for scoped listener management this.reactTo(this.events.onOff$Changed, this.#onOffChanged); } #onOffChanged(value: boolean) { // This handler is automatically removed when behavior closes console.log(`scoped handler: ${value}`); } } // Use OnOffServer.with() to add a feature flag class LightingOnOffServer extends OnOffServer.with(OnOff.Feature.Lighting) { override async on() { console.log("Lighting feature: ON"); await super.on(); } } // Compose device with custom behavior const MyLight = OnOffLightDevice.with(MyOnOffServer); const node = await ServerNode.create(); await node.add(MyLight); await node.run(); ``` -------------------------------- ### Get QR Code and Pairing Details for Uncommissioned Devices Source: https://github.com/matter-js/matter.js/blob/main/docs/MIGRATION_GUIDE_08.md Retrieve and display pairing information, including QR codes, for devices that have not yet been commissioned. This is essential for the initial setup process. ```javascript if (!serverNode.lifecycle.isCommissioned) { const { qrPairingCode, manualPairingCode } = server.state.commissioning.pairingCodes; console.log(QrCode.get(qrPairingCode)); logger.info(`QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`); logger.info(`Manual pairing code: ${manualPairingCode}`); } else { logger.info("Device is already commissioned. Waiting for controllers to connect ..."); } ``` -------------------------------- ### Initialize a New matter.js Project Source: https://github.com/matter-js/matter.js/blob/main/README.md Use this command to bootstrap a new Node.js project with matter.js templates. For more options, run with 'help'. ```bash npm init @matter ``` ```bash npm init @matter help ``` -------------------------------- ### Get Attribute Property Name Source: https://github.com/matter-js/matter.js/blob/main/packages/model/README.md Use `propertyName` to get the camelCase JavaScript property key for a given attribute. ```typescript const name = attribute.propertyName; // e.g. "onOff" for "OnOff" ``` -------------------------------- ### Run Controller with Pairing Code Source: https://github.com/matter-js/matter.js/blob/main/examples/controller/README.md Execute the controller from build files, initiating device commissioning with a provided pairing code. ```bash matter-controller --pairingcode=12345678901 ``` -------------------------------- ### Bootstrap a new matter.js project Source: https://context7.com/matter-js/matter.js/llms.txt Bootstrap a new project from an official template using the npm init command. Use `npm init @matter help` to see available templates. ```bash npm init @matter ``` -------------------------------- ### Initialize WebSocket Connection and Console Source: https://github.com/matter-js/matter.js/blob/main/packages/nodejs-shell/src/shell/webassets/index.html Sets up the WebSocket URL based on the current page protocol and host. Initializes the console and establishes a WebSocket connection. Logs 'info' level messages for certain commands. ```javascript const DEFAULT_PORT = 3000; // Default port for WebSocket connection const tiles = document.getElementById('tiles'); const consoleDiv = document.getElementById('console'); const matterCommand = document.getElementById('matterCommand'); const pairingCode = document.getElementById('pairingCode'); const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const host = window.location.hostname || 'localhost'; const defaultPort = window.location.port || DEFAULT_PORT; const wsUrl = `${protocol}//${host}:${defaultPort}`; let ws = null; let reconnectAttempts = 0; const ON_OFF = 6; const ILLUMINANCE = 1024; const TEMPERATURE = 1026; const PRESSURE = 1027; const HUMIDITY = 1029; const VOLTAGE = 144; // etc. const valueFormat = { [VOLTAGE]: (value, units = 'v') => { return (value / 1000).toFixed(1) + units; }, [ILLUMINANCE]: (value, units = 'lux') => { return (value / 100).toFixed(1) + units; }, [TEMPERATURE]: (value, units = "F") => { return (units === "F" ? (value / 100 * 9 / 5 + 32) : (value / 100)).toFixed(1) + '°' + units; }, [PRESSURE]: (value, units = 'mb') => { return (value / 10000).toFixed(1) + units; }, [HUMIDITY]: (value, units = '%') => { return (value / 100).toFixed(1) + units; }, }; function initConsole(clear) { if (clear) consoleDiv.innerHTML = ''; // Clear the console const dummy = document.createElement('div'); // Inject invisible wide line to reserve width dummy.style.visibility = 'hidden'; dummy.style.height = '0'; dummy.textContent = 'X'.repeat(120); consoleDiv.appendChild(dummy); } function logMessage(message, type) { const MAX_MESSAGES = 1000; // Maximum number of messages to keep in the console const fragment = document.createDocumentFragment(); const lines = message.split('\n'); lines.forEach(line => { const msg = document.createElement('div'); msg.textContent = line; msg.className = type; fragment.appendChild(msg); }); consoleDiv.appendChild(fragment); while (consoleDiv.children.length > MAX_MESSAGES) consoleDiv.removeChild(consoleDiv.firstChild); // Only scroll if the user was already at the bottom const shouldScroll = consoleDiv.scrollTop + consoleDiv.clientHeight >= consoleDiv.scrollHeight - consoleDiv.lastChild.offsetHeight - 5; // Adjusted for new content if (shouldScroll) consoleDiv.scrollTop = consoleDiv.scrollHeight; } function setupWebSocket() { ws = new WebSocket(wsUrl); initConsole(false); ws.onopen = () => { sendCommand('config loglevel set info'); // info level required for some msgs to be passed ``` -------------------------------- ### Provision Device with chip-tool Source: https://github.com/matter-js/matter.js/blob/main/docs/ECOSYSTEMS.md Use this command to provision a Matter device onto your network using the chip-tool. Ensure the device ID and passcode are correct. ```bash chip-tool pairing onnetwork 222 20202021 ``` -------------------------------- ### Add Endpoint to ServerNode Source: https://github.com/matter-js/matter.js/blob/main/docs/MIGRATION_GUIDE_08.md Endpoints can be added to a `ServerNode` after its creation. This example shows adding an `OnOffLightDevice` endpoint with a specific ID. ```typescript const endpoint = await serverNode.add(OnOffLightDevice, { id: "myonofflight" }); ``` -------------------------------- ### Display all top-level commands Source: https://github.com/matter-js/matter.js/blob/main/packages/nodejs-shell/README.md Execute the 'help' command in the matter-node-shell to list all supported top-level commands and their brief descriptions. ```shell matter-node> help commission Handle device commissioning config Manage global configuration session Manage session nodes Manage nodes ota OTA update operations cert Certificate management operations subscribe [node-id] Subscribe to all events and attributes of a node identify [time] [node-id] [endpoint-id] Trigger Identify command with given time (default 10s). Execute on one node or endpoint, else all onoff clusters will be controlled discover Handle device discovery attributes Read and Write attributes events Read events commands Invoke commands tlv TLV decoding tools exit Exit ``` -------------------------------- ### Get Certificate as PEM Source: https://github.com/matter-js/matter.js/blob/main/packages/nodejs-shell/README.md Use `cert as-pem ` to retrieve a certificate in PEM format. The output can be redirected to a file. ```bash cert as-pem 6AFD22771F511FECBF1641976710DCDC31A1717E ``` ```bash cert as-pem 6AFD22771F511FECBF1641976710DCDC31A1717E > certificate.pem ``` -------------------------------- ### Create and manage Matter.js endpoints Source: https://context7.com/matter-js/matter.js/llms.txt Demonstrates creating a simple light endpoint, reacting to its events, reading its state, and updating attributes atomically. Also shows setting up a temperature sensor and updating its value periodically. ```typescript import { Endpoint, ServerNode } from "@matter/main"; import { OnOffLightDevice } from "@matter/main/devices/on-off-light"; import { OnOffPlugInUnitDevice } from "@matter/main/devices/on-off-plug-in-unit"; import { TemperatureSensorDevice } from "@matter/main/devices/temperature-sensor"; import { HumiditySensorDevice } from "@matter/main/devices/humidity-sensor"; const server = await ServerNode.create(); // Simple light endpoint const light = new Endpoint(OnOffLightDevice, { id: "light1" }); await server.add(light); // React to state changes light.events.onOff.onOff$Changed.on(value => console.log(`Light is ${value ? "ON" : "OFF"}`)); light.events.identify.startIdentifying.on(() => console.log("Start blinking!")); light.events.identify.stopIdentifying.on(() => console.log("Stop blinking!")); // Read attribute state synchronously from local cache const currentOnOff = light.state.onOff.onOff; console.log("Current on/off:", currentOnOff); // Write one or multiple attributes atomically (transaction — all-or-nothing) await light.set({ onOff: { onOff: true }, }); // Temperature sensor with initial value const tempSensor = new Endpoint(TemperatureSensorDevice, { id: "tempsensor", temperatureMeasurement: { measuredValue: 2150 }, // 21.50 °C (value × 100) }); await server.add(tempSensor); // Update sensor value periodically setInterval(async () => { const newTemp = Math.round((20 + Math.random() * 5) * 100); // 20–25 °C await tempSensor.set({ temperatureMeasurement: { measuredValue: newTemp } }); }, 30_000); await server.run(); ``` -------------------------------- ### Run Controller with Pairing Code (NPM) Source: https://github.com/matter-js/matter.js/blob/main/examples/controller/README.md Execute the controller directly from Typescript files using npm, enabling on-the-fly compilation and device commissioning with a pairing code. ```bash npm run matter-controller -- --pairingcode=12345678901 ``` -------------------------------- ### Connect to a Node and Subscribe to Attributes/Events Source: https://context7.com/matter-js/matter.js/llms.txt Establishes a connection to a specified node and subscribes to all its attributes and events. ```bash matter-node> nodes connect 5000 ``` -------------------------------- ### TypeScript Configuration for Matter.js Source: https://github.com/matter-js/matter.js/blob/main/packages/matter.js/README.md Configure your tsconfig.json to ensure TypeScript and your IDE correctly recognize Matter.js exports. This setup is crucial for module resolution and import handling. ```json { compilerOptions: { moduleResolution: "node16", // Required to support package.json exports module: "node16", // Required to make sure all imports are js }, } ``` -------------------------------- ### Bundle Device Application (Bash) Source: https://github.com/matter-js/matter.js/blob/main/examples/device-onoff/README.md Executes the bundling script to create a single JavaScript file for the application and its dependencies. This is useful for production environments where space and CPU are limited. ```bash npm run bundle-device ``` -------------------------------- ### Timers and Time Utilities in Matter.js Source: https://context7.com/matter-js/matter.js/llms.txt Implement one-shot and periodic timers, and access the current time in milliseconds using the Time module. Timers can be started and stopped as needed. ```typescript import { Seconds, Time } from "@matter/main"; // One-shot timer const oneShotTimer = Time.getTimer("startup-delay", Seconds(5), () => { console.log("5 seconds elapsed"); }); oneShotTimer.start(); // Cancel before firing: // oneShotTimer.stop(); // Periodic timer const periodicTimer = Time.getPeriodicTimer("heartbeat", Seconds(30), () => { console.log("Heartbeat at", new Date(Time.nowMs).toISOString()); }); periodicTimer.start(); // Stop when done // periodicTimer.stop(); // Current time console.log("Now (ms):", Time.nowMs); ``` -------------------------------- ### Display help for matter-node-shell parameters Source: https://github.com/matter-js/matter.js/blob/main/packages/nodejs-shell/README.md Use the --help flag with npx to see available parameters for the shell, separating npm and shell parameters with '--'. ```bash npx matter-shell -- --help ``` -------------------------------- ### Dynamically Add Clusters to an Endpoint Source: https://github.com/matter-js/matter.js/blob/main/docs/MIGRATION_GUIDE_08.md Add clusters to an endpoint after its creation using the `behaviors.require` method. This example demonstrates adding a BridgedDeviceBasicInformation cluster, which requires specific methods for accessing its state. ```typescript endpoint.behaviors.require(BridgedDeviceBasicInformationServer, { nodeLabel: name, productName: name, productLabel: name, uniqueId: this.devicesOptions[i].uuid[i].replace(/-/g, ""), reachable: true, }); ``` -------------------------------- ### Add OnOffLightDevice to a ServerNode Source: https://github.com/matter-js/matter.js/blob/main/packages/node/src/node/README.md Demonstrates how to add a predefined OnOffLightDevice to a Matter.js server node. This publishes a node with a functional 'on/off' cluster. ```typescript import { OnOffLightDevice } from "@matter/main/devices/OnOffLightDevice"; import { ServerNode } from "@matter/main"; const node = await ServerNode.create(); await node.add(OnOffLightDevice); await node.run(); ``` -------------------------------- ### Generate Model Files Source: https://github.com/matter-js/matter.js/blob/main/packages/model/README.md Navigate to the codegen directory and run the npm script to generate model files. ```bash cd matter.js/support/codegen npm run generate-model ``` -------------------------------- ### Import Matter Model Source: https://github.com/matter-js/matter.js/blob/main/packages/model/README.md Import the Matter object model to begin working with it. ```typescript import { Matter } from "@matter/model"; ``` -------------------------------- ### Commission Matter Devices with CommissioningController Source: https://context7.com/matter-js/matter.js/llms.txt Use CommissioningController to pair new devices, manage fabrics, and interact with commissioned nodes. It requires explicit start and provides detailed event handling for connection and attribute changes. ```typescript import { Environment, Logger, StorageService } from "@matter/main"; import { OnOffClient } from "@matter/main/behaviors/on-off"; import { DescriptorClient } from "@matter/main/behaviors/descriptor"; import { GeneralCommissioning } from "@matter/main/clusters"; import { NodeId } from "@matter/main/types"; import { CommissioningController, NodeCommissioningOptions } from "@project-chip/matter.js"; import { NodeStates } from "@project-chip/matter.js/device"; const environment = Environment.default; const controller = new CommissioningController({ environment: { environment, id: "controller-001" }, autoConnect: false, adminFabricLabel: "My Controller", }); await controller.start(); // Commission a new device (once only) if (!controller.isCommissioned()) { const nodeId = await controller.commissionNode({ commissioning: { regulatoryLocation: GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor, regulatoryCountryCode: "XX", }, discovery: { identifierData: { longDiscriminator: 3840 }, // For BLE commissioning: // discoveryCapabilities: { ble: true }, }, passcode: 20202021, } satisfies NodeCommissioningOptions); console.log("Commissioned node:", nodeId); } // Connect to an already-commissioned node const nodes = controller.getCommissionedNodes(); const node = await controller.getNode(NodeId(nodes[0])); // Connection state tracking node.events.stateChanged.on(info => { if (info === NodeStates.Connected) console.log("Connected"); if (info === NodeStates.Disconnected) console.log("Disconnected"); if (info === NodeStates.Reconnecting) console.log("Reconnecting..."); }); node.events.attributeChanged.on(({ path, value }) => console.log(`${path.endpointId}/${path.clusterId}/${path.attributeName} =`, value), ); node.connect(); // Non-blocking if (!node.initialized) { await node.events.initialized; // Wait for initial subscription data } node.logStructure(); // Print full endpoint/cluster tree // Access typed cluster state (from local cache) const descriptorState = node.stateOf(DescriptorClient); console.log("Device types:", descriptorState?.deviceTypeList); // Access a specific endpoint and invoke a command const ep1 = node.parts.get(1); if (ep1) { const onOffState = ep1.stateOf(OnOffClient); console.log("OnOff state:", onOffState?.onOff); // Toggle on/off every minute setInterval(() => { ep1.commandsOf(OnOffClient).toggle().catch(console.error); }, 60_000); } ``` -------------------------------- ### Run Matter Shell with WebSocket and Web Server Source: https://github.com/matter-js/matter.js/blob/main/packages/nodejs-shell/README.md Enable both websocket communication and an HTTP server for serving application files by adding the '--webServer' flag. The 'exit' command will only close the websocket connection. ```bash npm run shell 2 -- --webSocketInterface --webSocketPort 3000 --webServer ``` -------------------------------- ### Run Matter Controller with Custom Environment Variables Source: https://github.com/matter-js/matter.js/blob/main/examples/controller-shared-fabric/README.md Configure and run Matter controller commands using custom environment variables for fabric ID, node ID, target node ID, and endpoint. This allows for flexible multi-controller setups. ```bash MATTER_CERTDIR=/path/to/certificates \ MATTER_FABRICID=2 \ MATTER_NODEID=200 \ MATTER_TARGETNODEID=1 \ MATTER_ENDPOINT=1 \ npm run matter-controller-shared-fabric toggle ``` -------------------------------- ### Run Local Linter and Formatter Source: https://github.com/matter-js/matter.js/blob/main/CONTRIBUTING.md Apply the linter and formatter to maintain code style consistency. ```bash npm run lint npm run format ``` -------------------------------- ### Generate External Certificates with chip-tool Source: https://github.com/matter-js/matter.js/blob/main/examples/controller-shared-fabric/README.md Use chip-tool to generate the necessary certificate chain for multi-controller setups. This includes the Root CA (RCAC), and intermediate CAs (ICACs) for each controller, along with their corresponding keys. Certificates are converted to Matter TLV formats for use. ```bash cd /path/to/connectedhomeip # Create certificates directory mkdir -p certificates # Generate RCAC (Root CA) ./out/linux-x64-chip-tool/chip-cert gen-att-cert \ --type r \ --subject-cn "Matter Test Root CA" \ --valid-from "2024-01-01 00:00:00" \ --lifetime 3650 \ --out-key certificates/rcac_key.pem \ --out certificates/rcac.pem # Convert RCAC to Matter TLV format ./out/linux-x64-chip-tool/chip-cert convert-cert \ certificates/rcac.pem certificates/rcac.chip --chip # Generate ICAC 1 (for chip-tool controller) ./out/linux-x64-chip-tool/chip-cert gen-att-cert \ --type i \ --subject-cn "Matter Test ICA 1" \ --ca-cert certificates/rcac.pem \ --ca-key certificates/rcac_key.pem \ --valid-from "2024-01-01 00:00:00" \ --lifetime 3650 \ --out-key certificates/icac1_key.pem \ --out certificates/icac1.pem # Convert ICAC 1 to Matter formats ./out/linux-x64-chip-tool/chip-cert convert-cert \ certificates/icac1.pem certificates/icac1.chip --chip ./out/linux-x64-chip-tool/chip-cert convert-key \ certificates/icac1_key.pem certificates/icac1_key.bin --chip # Generate ICAC 2 (for matter.js controller) ./out/linux-x64-chip-tool/chip-cert gen-att-cert \ --type i \ --subject-cn "Matter Test ICA 2" \ --ca-cert certificates/rcac.pem \ --ca-key certificates/rcac_key.pem \ --valid-from "2024-01-01 00:00:00" \ --lifetime 3650 \ --out-key certificates/icac2_key.pem \ --out certificates/icac2.pem # Convert ICAC 2 to Matter formats ./out/linux-x64-chip-tool/chip-cert convert-cert \ certificates/icac2.pem certificates/icac2.chip --chip ./out/linux-x64-chip-tool/chip-cert convert-key \ certificates/icac2_key.pem certificates/icac2_key.bin --chip ``` -------------------------------- ### Run Matter Controller Commands Source: https://github.com/matter-js/matter.js/blob/main/examples/controller-shared-fabric/README.md Execute common Matter controller operations like toggling, turning on/off, or reading the state of a device. These commands assume default environment variables are set. ```bash cd examples # Toggle the device ON/OFF npm run matter-controller-shared-fabric toggle # Turn device ON npm run matter-controller-shared-fabric on # Turn device OFF npm run matter-controller-shared-fabric off # Read current OnOff state npm run matter-controller-shared-fabric read ``` -------------------------------- ### Create a ServerNode Source: https://github.com/matter-js/matter.js/blob/main/docs/MIGRATION_GUIDE_08.md Use `ServerNode.create()` to instantiate a new Matter Server node. This method takes the RootEndpoint definition and node configuration as parameters. The configuration includes node-specific details and root endpoint cluster configurations. ```typescript const serverNode = await ServerNode.create({ id: "myNode", //... serverNode configuration parts: [ { type: OnOffLightDevice, id: "myonofflight", //... more config for this part }, ], }); ```