@project-chip/matter-node.js-examples 0.11.0-alpha.0-20240909-b3b29745 → 0.11.0-alpha.0-20240911-db8f7c80
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/esm/examples/BridgedDevicesNode.js +2 -3
- package/dist/esm/examples/BridgedDevicesNode.js.map +2 -2
- package/dist/esm/examples/BridgedDevicesNodeLegacy.js +14 -15
- package/dist/esm/examples/BridgedDevicesNodeLegacy.js.map +2 -2
- package/dist/esm/examples/ComposedDeviceNode.js +2 -3
- package/dist/esm/examples/ComposedDeviceNode.js.map +2 -2
- package/dist/esm/examples/ComposedDeviceNodeLegacy.js +15 -16
- package/dist/esm/examples/ComposedDeviceNodeLegacy.js.map +2 -2
- package/dist/esm/examples/ControllerNode.js +2 -5
- package/dist/esm/examples/ControllerNode.js.map +2 -2
- package/dist/esm/examples/ControllerNodeLegacy.js +21 -22
- package/dist/esm/examples/ControllerNodeLegacy.js.map +2 -2
- package/dist/esm/examples/DeviceNode.js +2 -3
- package/dist/esm/examples/DeviceNode.js.map +2 -2
- package/dist/esm/examples/DeviceNodeFull.js +4 -8
- package/dist/esm/examples/DeviceNodeFull.js.map +2 -2
- package/dist/esm/examples/DeviceNodeFullLegacy.js +16 -18
- package/dist/esm/examples/DeviceNodeFullLegacy.js.map +2 -2
- package/dist/esm/examples/IlluminatedRollerShade.js +1 -1
- package/dist/esm/examples/IlluminatedRollerShade.js.map +1 -1
- package/dist/esm/examples/LegacyStorageConverter.js +2 -3
- package/dist/esm/examples/LegacyStorageConverter.js.map +2 -2
- package/dist/esm/examples/LightDevice.js +1 -1
- package/dist/esm/examples/LightDevice.js.map +1 -1
- package/dist/esm/examples/MultiDeviceNode.js +2 -3
- package/dist/esm/examples/MultiDeviceNode.js.map +2 -2
- package/dist/esm/examples/MultiDeviceNodeLegacy.js +13 -14
- package/dist/esm/examples/MultiDeviceNodeLegacy.js.map +2 -2
- package/dist/esm/examples/SensorDeviceNode.js +2 -3
- package/dist/esm/examples/SensorDeviceNode.js.map +2 -2
- package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js +11 -8
- package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js.map +2 -2
- package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js +15 -11
- package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js.map +2 -2
- package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js +12 -10
- package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js.map +2 -2
- package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js +8 -8
- package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js.map +2 -2
- package/dist/esm/tutorial/example01.js +1 -1
- package/dist/esm/tutorial/example01.js.map +1 -1
- package/dist/esm/tutorial/example02.js +1 -1
- package/dist/esm/tutorial/example02.js.map +1 -1
- package/dist/esm/tutorial/example03.js +1 -1
- package/dist/esm/tutorial/example03.js.map +1 -1
- package/dist/esm/tutorial/example04.js +1 -1
- package/dist/esm/tutorial/example04.js.map +1 -1
- package/dist/esm/tutorial/example05.js +1 -1
- package/dist/esm/tutorial/example05.js.map +1 -1
- package/package.json +6 -5
- package/src/examples/BridgedDevicesNode.ts +2 -3
- package/src/examples/BridgedDevicesNodeLegacy.ts +15 -16
- package/src/examples/ComposedDeviceNode.ts +2 -3
- package/src/examples/ComposedDeviceNodeLegacy.ts +15 -16
- package/src/examples/ControllerNode.ts +2 -6
- package/src/examples/ControllerNodeLegacy.ts +22 -23
- package/src/examples/DeviceNode.ts +2 -3
- package/src/examples/DeviceNodeFull.ts +5 -10
- package/src/examples/DeviceNodeFullLegacy.ts +16 -18
- package/src/examples/IlluminatedRollerShade.ts +1 -1
- package/src/examples/LegacyStorageConverter.ts +3 -3
- package/src/examples/LightDevice.ts +1 -1
- package/src/examples/MultiDeviceNode.ts +2 -3
- package/src/examples/MultiDeviceNodeLegacy.ts +15 -15
- package/src/examples/SensorDeviceNode.ts +2 -3
- package/src/examples/cluster/DummyThreadNetworkCommissioningServer.ts +11 -8
- package/src/examples/cluster/DummyWifiNetworkCommissioningServer.ts +15 -11
- package/src/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.ts +12 -10
- package/src/examples/cluster/MyFancyOwnFunctionality.ts +9 -9
- package/src/tsconfig.json +1 -1
- package/src/tutorial/example01.ts +1 -1
- package/src/tutorial/example02.ts +1 -1
- package/src/tutorial/example03.ts +1 -1
- package/src/tutorial/example04.ts +1 -1
- package/src/tutorial/example05.ts +1 -1
@@ -4,52 +4,51 @@
|
|
4
4
|
* Copyright 2022-2023 Project CHIP Authors
|
5
5
|
* SPDX-License-Identifier: Apache-2.0
|
6
6
|
*/
|
7
|
-
import {
|
7
|
+
import {
|
8
|
+
StorageBackendDisk,
|
9
|
+
getIntParameter,
|
10
|
+
getParameter,
|
11
|
+
hasParameter,
|
12
|
+
requireMinNodeVersion
|
13
|
+
} from "@project-chip/matter.js-nodejs";
|
8
14
|
import { BleNode } from "@project-chip/matter-node-ble.js/ble";
|
9
|
-
import {
|
15
|
+
import { CommissioningController, MatterServer } from "@project-chip/matter.js";
|
16
|
+
import { LogFormat, LogLevel, Logger, StorageManager, singleton } from "@project-chip/matter.js-general";
|
17
|
+
import { Ble } from "@project-chip/matter.js/ble";
|
10
18
|
import {
|
11
19
|
BasicInformationCluster,
|
12
20
|
DescriptorCluster,
|
13
21
|
GeneralCommissioning,
|
14
22
|
OnOffCluster
|
15
|
-
} from "@project-chip/matter
|
16
|
-
import { NodeId } from "@project-chip/matter
|
17
|
-
import { NodeStateInformation } from "@project-chip/matter
|
18
|
-
import {
|
19
|
-
import { ManualPairingCodeCodec } from "@project-chip/matter-node.js/schema";
|
20
|
-
import { StorageBackendDisk, StorageManager } from "@project-chip/matter-node.js/storage";
|
21
|
-
import {
|
22
|
-
getIntParameter,
|
23
|
-
getParameter,
|
24
|
-
hasParameter,
|
25
|
-
requireMinNodeVersion,
|
26
|
-
singleton
|
27
|
-
} from "@project-chip/matter-node.js/util";
|
23
|
+
} from "@project-chip/matter.js/cluster";
|
24
|
+
import { NodeId } from "@project-chip/matter.js/datatype";
|
25
|
+
import { NodeStateInformation } from "@project-chip/matter.js/device";
|
26
|
+
import { ManualPairingCodeCodec } from "@project-chip/matter.js/schema";
|
28
27
|
const logger = Logger.get("Controller");
|
29
28
|
requireMinNodeVersion(16);
|
30
29
|
switch (getParameter("loglevel")) {
|
31
30
|
case "fatal":
|
32
|
-
Logger.defaultLogLevel =
|
31
|
+
Logger.defaultLogLevel = LogLevel.FATAL;
|
33
32
|
break;
|
34
33
|
case "error":
|
35
|
-
Logger.defaultLogLevel =
|
34
|
+
Logger.defaultLogLevel = LogLevel.ERROR;
|
36
35
|
break;
|
37
36
|
case "warn":
|
38
|
-
Logger.defaultLogLevel =
|
37
|
+
Logger.defaultLogLevel = LogLevel.WARN;
|
39
38
|
break;
|
40
39
|
case "info":
|
41
|
-
Logger.defaultLogLevel =
|
40
|
+
Logger.defaultLogLevel = LogLevel.INFO;
|
42
41
|
break;
|
43
42
|
}
|
44
43
|
switch (getParameter("logformat")) {
|
45
44
|
case "plain":
|
46
|
-
Logger.format =
|
45
|
+
Logger.format = LogFormat.PLAIN;
|
47
46
|
break;
|
48
47
|
case "html":
|
49
|
-
Logger.format =
|
48
|
+
Logger.format = LogFormat.HTML;
|
50
49
|
break;
|
51
50
|
default:
|
52
|
-
if (process.stdin?.isTTY) Logger.format =
|
51
|
+
if (process.stdin?.isTTY) Logger.format = LogFormat.ANSI;
|
53
52
|
}
|
54
53
|
if (hasParameter("ble")) {
|
55
54
|
Ble.get = singleton(
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/ControllerNodeLegacy.ts"],
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2023 Project CHIP Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This example shows how to create a Matter controller to pair with a device and interfact with it.\n * It can be used as CLI script, but is more thought as a starting point for your own controller implementation\n * because you need to adjust the code in any way depending on your use case.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport { CommissioningController, MatterServer, NodeCommissioningOptions } from \"@project-chip/matter-node.js\";\n\nimport { BleNode } from \"@project-chip/matter-node-ble.js/ble\";\nimport { Ble } from \"@project-chip/matter-node.js/ble\";\nimport {\n BasicInformationCluster,\n DescriptorCluster,\n GeneralCommissioning,\n OnOffCluster,\n} from \"@project-chip/matter-node.js/cluster\";\nimport { NodeId } from \"@project-chip/matter-node.js/datatype\";\nimport { NodeStateInformation } from \"@project-chip/matter-node.js/device\";\nimport { Format, Level, Logger } from \"@project-chip/matter-node.js/log\";\nimport { CommissioningOptions } from \"@project-chip/matter-node.js/protocol\";\nimport { ManualPairingCodeCodec } from \"@project-chip/matter-node.js/schema\";\nimport { StorageBackendDisk, StorageManager } from \"@project-chip/matter-node.js/storage\";\nimport {\n getIntParameter,\n getParameter,\n hasParameter,\n requireMinNodeVersion,\n singleton,\n} from \"@project-chip/matter-node.js/util\";\n\nconst logger = Logger.get(\"Controller\");\n\nrequireMinNodeVersion(16);\n\n/** Configure logging */\nswitch (getParameter(\"loglevel\")) {\n case \"fatal\":\n Logger.defaultLogLevel = Level.FATAL;\n break;\n case \"error\":\n Logger.defaultLogLevel = Level.ERROR;\n break;\n case \"warn\":\n Logger.defaultLogLevel = Level.WARN;\n break;\n case \"info\":\n Logger.defaultLogLevel = Level.INFO;\n break;\n}\n\nswitch (getParameter(\"logformat\")) {\n case \"plain\":\n Logger.format = Format.PLAIN;\n break;\n case \"html\":\n Logger.format = Format.HTML;\n break;\n default:\n if (process.stdin?.isTTY) Logger.format = Format.ANSI;\n}\n\nif (hasParameter(\"ble\")) {\n // Initialize Ble\n Ble.get = singleton(\n () =>\n new BleNode({\n hciId: getIntParameter(\"ble-hci-id\"),\n }),\n );\n}\n\nconst storageLocation = getParameter(\"store\") ?? \".controller-node\";\nconst storage = new StorageBackendDisk(storageLocation, hasParameter(\"clearstorage\"));\nlogger.info(`Storage location: ${storageLocation} (Directory)`);\nlogger.info(\n 'Use the parameter \"-store NAME\" to specify a different storage location, use -clearstorage to start with an empty storage.',\n);\n\nclass ControllerNode {\n async start() {\n logger.info(`node-matter Controller started`);\n\n /**\n * Initialize the storage system.\n *\n * The storage manager is then also used by the Matter server, so this code block in general is required,\n * but you can choose a different storage backend as long as it implements the required API.\n */\n\n const storageManager = new StorageManager(storage);\n await storageManager.initialize();\n\n /**\n * Collect all needed data\n *\n * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data\n * come from.\n *\n * Note: This example also uses the initialized storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts\n * (so maybe better not ;-)).\n */\n\n const controllerStorage = storageManager.createContext(\"Controller\");\n const ip = controllerStorage.has(\"ip\") ? controllerStorage.get<string>(\"ip\") : getParameter(\"ip\");\n const port = controllerStorage.has(\"port\") ? controllerStorage.get<number>(\"port\") : getIntParameter(\"port\");\n\n const pairingCode = getParameter(\"pairingcode\");\n let longDiscriminator, setupPin, shortDiscriminator;\n if (pairingCode !== undefined) {\n const pairingCodeCodec = ManualPairingCodeCodec.decode(pairingCode);\n shortDiscriminator = pairingCodeCodec.shortDiscriminator;\n longDiscriminator = undefined;\n setupPin = pairingCodeCodec.passcode;\n logger.debug(`Data extracted from pairing code: ${Logger.toJSON(pairingCodeCodec)}`);\n } else {\n longDiscriminator =\n getIntParameter(\"longDiscriminator\") ?? controllerStorage.get(\"longDiscriminator\", 3840);\n if (longDiscriminator > 4095) throw new Error(\"Discriminator value must be less than 4096\");\n setupPin = getIntParameter(\"pin\") ?? controllerStorage.get(\"pin\", 20202021);\n }\n if ((shortDiscriminator === undefined && longDiscriminator === undefined) || setupPin === undefined) {\n throw new Error(\n \"Please specify the longDiscriminator of the device to commission with -longDiscriminator or provide a valid passcode with -passcode\",\n );\n }\n\n // Collect commissioning options from commandline parameters\n const commissioningOptions: CommissioningOptions = {\n regulatoryLocation: GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor,\n regulatoryCountryCode: \"XX\",\n };\n\n let ble = false;\n if (hasParameter(\"ble\")) {\n ble = true;\n const wifiSsid = getParameter(\"ble-wifi-ssid\");\n const wifiCredentials = getParameter(\"ble-wifi-credentials\");\n const threadNetworkName = getParameter(\"ble-thread-networkname\");\n const threadOperationalDataset = getParameter(\"ble-thread-operationaldataset\");\n if (wifiSsid !== undefined && wifiCredentials !== undefined) {\n logger.info(`Registering Commissioning over BLE with WiFi: ${wifiSsid}`);\n commissioningOptions.wifiNetwork = {\n wifiSsid: wifiSsid,\n wifiCredentials: wifiCredentials,\n };\n }\n if (threadNetworkName !== undefined && threadOperationalDataset !== undefined) {\n logger.info(`Registering Commissioning over BLE with Thread: ${threadNetworkName}`);\n commissioningOptions.threadNetwork = {\n networkName: threadNetworkName,\n operationalDataset: threadOperationalDataset,\n };\n }\n }\n\n /**\n * Create Matter Server and Controller Node\n *\n * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a\n * CommissioningController to it and add the just created device instance to it.\n * The Controller node defines the port where the server listens for the UDP packages of the Matter protocol\n * and initializes deice specific certificates and such.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled internally\n * like testEventTrigger (General Diagnostic Cluster) that can be implemented with the logic when these commands\n * are called.\n */\n\n const matterServer = new MatterServer(storageManager);\n const commissioningController = new CommissioningController({\n autoConnect: false,\n });\n await matterServer.addCommissioningController(commissioningController);\n\n /**\n * Start the Matter Server\n *\n * After everything was plugged together we can start the server. When not delayed announcement is set for the\n * CommissioningServer node then this command also starts the announcement of the device into the network.\n */\n\n await matterServer.start();\n\n if (!commissioningController.isCommissioned()) {\n const options = {\n commissioning: commissioningOptions,\n discovery: {\n knownAddress: ip !== undefined && port !== undefined ? { ip, port, type: \"udp\" } : undefined,\n identifierData:\n longDiscriminator !== undefined\n ? { longDiscriminator }\n : shortDiscriminator !== undefined\n ? { shortDiscriminator }\n : {},\n discoveryCapabilities: {\n ble,\n },\n },\n passcode: setupPin,\n } as NodeCommissioningOptions;\n logger.info(`Commissioning ... ${Logger.toJSON(options)}`);\n const nodeId = await commissioningController.commissionNode(options);\n\n console.log(`Commissioning successfully done with nodeId ${nodeId}`);\n }\n\n /**\n * TBD\n */\n try {\n const nodes = commissioningController.getCommissionedNodes();\n console.log(\"Found commissioned nodes:\", Logger.toJSON(nodes));\n\n const nodeId = NodeId(getIntParameter(\"nodeid\") ?? nodes[0]);\n if (!nodes.includes(nodeId)) {\n throw new Error(`Node ${nodeId} not found in commissioned nodes`);\n }\n\n const node = await commissioningController.connectNode(nodeId, {\n attributeChangedCallback: (\n peerNodeId,\n { path: { nodeId, clusterId, endpointId, attributeName }, value },\n ) =>\n console.log(\n `attributeChangedCallback ${peerNodeId}: Attribute ${nodeId}/${endpointId}/${clusterId}/${attributeName} changed to ${Logger.toJSON(\n value,\n )}`,\n ),\n eventTriggeredCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, eventName }, events }) =>\n console.log(\n `eventTriggeredCallback ${peerNodeId}: Event ${nodeId}/${endpointId}/${clusterId}/${eventName} triggered with ${Logger.toJSON(\n events,\n )}`,\n ),\n stateInformationCallback: (peerNodeId, info) => {\n switch (info) {\n case NodeStateInformation.Connected:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} connected`);\n break;\n case NodeStateInformation.Disconnected:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} disconnected`);\n break;\n case NodeStateInformation.Reconnecting:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} reconnecting`);\n break;\n case NodeStateInformation.WaitingForDeviceDiscovery:\n console.log(\n `stateInformationCallback ${peerNodeId}: Node ${nodeId} waiting for device discovery`,\n );\n break;\n case NodeStateInformation.StructureChanged:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} structure changed`);\n break;\n case NodeStateInformation.Decommissioned:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} decommissioned`);\n break;\n }\n },\n });\n\n // Important: This is a temporary API to proof the methods working and this will change soon and is NOT stable!\n // It is provided to proof the concept\n\n node.logStructure();\n\n // Example to initialize a ClusterClient and access concrete fields as API methods\n const descriptor = node.getRootClusterClient(DescriptorCluster);\n if (descriptor !== undefined) {\n console.log(await descriptor.attributes.deviceTypeList.get()); // you can call that way\n console.log(await descriptor.getServerListAttribute()); // or more convenient that way\n } else {\n console.log(\"No Descriptor Cluster found. This should never happen!\");\n }\n\n // Example to subscribe to a field and get the value\n const info = node.getRootClusterClient(BasicInformationCluster);\n if (info !== undefined) {\n console.log(await info.getProductNameAttribute()); // This call is executed remotely\n //console.log(await info.subscribeProductNameAttribute(value => console.log(\"productName\", value), 5, 30));\n //console.log(await info.getProductNameAttribute()); // This call is resolved locally because we have subscribed to the value!\n } else {\n console.log(\"No BasicInformation Cluster found. This should never happen!\");\n }\n\n // Example to get all Attributes of the commissioned node: */*/*\n //const attributesAll = await interactionClient.getAllAttributes();\n //console.log(\"Attributes-All:\", Logger.toJSON(attributesAll));\n\n // Example to get all Attributes of all Descriptor Clusters of the commissioned node: */DescriptorCluster/*\n //const attributesAllDescriptor = await interactionClient.getMultipleAttributes([{ clusterId: DescriptorCluster.id} ]);\n //console.log(\"Attributes-Descriptor:\", JSON.stringify(attributesAllDescriptor, null, 2));\n\n // Example to get all Attributes of the Basic Information Cluster of endpoint 0 of the commissioned node: 0/BasicInformationCluster/*\n //const attributesBasicInformation = await interactionClient.getMultipleAttributes([{ endpointId: 0, clusterId: BasicInformationCluster.id} ]);\n //console.log(\"Attributes-BasicInformation:\", JSON.stringify(attributesBasicInformation, null, 2));\n\n const devices = node.getDevices();\n if (devices[0] && devices[0].number === 1) {\n // Example to subscribe to all Attributes of endpoint 1 of the commissioned node: */*/*\n //await interactionClient.subscribeMultipleAttributes([{ endpointId: 1, /* subscribe anything from endpoint 1 */ }], 0, 180, data => {\n // console.log(\"Subscribe-All Data:\", Logger.toJSON(data));\n //});\n\n const onOff = devices[0].getClusterClient(OnOffCluster);\n if (onOff !== undefined) {\n let onOffStatus = await onOff.getOnOffAttribute();\n console.log(\"initial onOffStatus\", onOffStatus);\n\n onOff.addOnOffAttributeListener(value => {\n console.log(\"subscription onOffStatus\", value);\n onOffStatus = value;\n });\n // read data every minute to keep up the connection to show the subscription is working\n setInterval(() => {\n onOff\n .toggle()\n .then(() => {\n onOffStatus = !onOffStatus;\n console.log(\"onOffStatus\", onOffStatus);\n })\n .catch(error => logger.error(error));\n }, 60000);\n }\n }\n } finally {\n //await matterServer.close(); // Comment out when subscribes are used, else the connection will be closed\n setTimeout(() => process.exit(0), 1000000);\n }\n }\n}\n\nnew ControllerNode().start().catch(error => logger.error(error));\n\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n // Pragmatic way to make sure the storage is correctly closed before the process ends.\n storage.close();\n process.exit(0);\n});\n"],
|
5
|
-
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAgBA
|
4
|
+
"sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2023 Project CHIP Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This example shows how to create a Matter controller to pair with a device and interfact with it.\n * It can be used as CLI script, but is more thought as a starting point for your own controller implementation\n * because you need to adjust the code in any way depending on your use case.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport {\n StorageBackendDisk,\n getIntParameter,\n getParameter,\n hasParameter,\n requireMinNodeVersion,\n} from \"@project-chip/matter.js-nodejs\";\n\nimport { BleNode } from \"@project-chip/matter-node-ble.js/ble\";\nimport { CommissioningController, MatterServer, NodeCommissioningOptions } from \"@project-chip/matter.js\";\nimport { LogFormat, LogLevel, Logger, StorageManager, singleton } from \"@project-chip/matter.js-general\";\nimport { Ble } from \"@project-chip/matter.js/ble\";\nimport {\n BasicInformationCluster,\n DescriptorCluster,\n GeneralCommissioning,\n OnOffCluster,\n} from \"@project-chip/matter.js/cluster\";\nimport { NodeId } from \"@project-chip/matter.js/datatype\";\nimport { NodeStateInformation } from \"@project-chip/matter.js/device\";\nimport { CommissioningOptions } from \"@project-chip/matter.js/protocol\";\nimport { ManualPairingCodeCodec } from \"@project-chip/matter.js/schema\";\n\nconst logger = Logger.get(\"Controller\");\n\nrequireMinNodeVersion(16);\n\n/** Configure logging */\nswitch (getParameter(\"loglevel\")) {\n case \"fatal\":\n Logger.defaultLogLevel = LogLevel.FATAL;\n break;\n case \"error\":\n Logger.defaultLogLevel = LogLevel.ERROR;\n break;\n case \"warn\":\n Logger.defaultLogLevel = LogLevel.WARN;\n break;\n case \"info\":\n Logger.defaultLogLevel = LogLevel.INFO;\n break;\n}\n\nswitch (getParameter(\"logformat\")) {\n case \"plain\":\n Logger.format = LogFormat.PLAIN;\n break;\n case \"html\":\n Logger.format = LogFormat.HTML;\n break;\n default:\n if (process.stdin?.isTTY) Logger.format = LogFormat.ANSI;\n}\n\nif (hasParameter(\"ble\")) {\n // Initialize Ble\n Ble.get = singleton(\n () =>\n new BleNode({\n hciId: getIntParameter(\"ble-hci-id\"),\n }),\n );\n}\n\nconst storageLocation = getParameter(\"store\") ?? \".controller-node\";\nconst storage = new StorageBackendDisk(storageLocation, hasParameter(\"clearstorage\"));\nlogger.info(`Storage location: ${storageLocation} (Directory)`);\nlogger.info(\n 'Use the parameter \"-store NAME\" to specify a different storage location, use -clearstorage to start with an empty storage.',\n);\n\nclass ControllerNode {\n async start() {\n logger.info(`node-matter Controller started`);\n\n /**\n * Initialize the storage system.\n *\n * The storage manager is then also used by the Matter server, so this code block in general is required,\n * but you can choose a different storage backend as long as it implements the required API.\n */\n\n const storageManager = new StorageManager(storage);\n await storageManager.initialize();\n\n /**\n * Collect all needed data\n *\n * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data\n * come from.\n *\n * Note: This example also uses the initialized storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts\n * (so maybe better not ;-)).\n */\n\n const controllerStorage = storageManager.createContext(\"Controller\");\n const ip = controllerStorage.has(\"ip\") ? controllerStorage.get<string>(\"ip\") : getParameter(\"ip\");\n const port = controllerStorage.has(\"port\") ? controllerStorage.get<number>(\"port\") : getIntParameter(\"port\");\n\n const pairingCode = getParameter(\"pairingcode\");\n let longDiscriminator, setupPin, shortDiscriminator;\n if (pairingCode !== undefined) {\n const pairingCodeCodec = ManualPairingCodeCodec.decode(pairingCode);\n shortDiscriminator = pairingCodeCodec.shortDiscriminator;\n longDiscriminator = undefined;\n setupPin = pairingCodeCodec.passcode;\n logger.debug(`Data extracted from pairing code: ${Logger.toJSON(pairingCodeCodec)}`);\n } else {\n longDiscriminator =\n getIntParameter(\"longDiscriminator\") ?? controllerStorage.get(\"longDiscriminator\", 3840);\n if (longDiscriminator > 4095) throw new Error(\"Discriminator value must be less than 4096\");\n setupPin = getIntParameter(\"pin\") ?? controllerStorage.get(\"pin\", 20202021);\n }\n if ((shortDiscriminator === undefined && longDiscriminator === undefined) || setupPin === undefined) {\n throw new Error(\n \"Please specify the longDiscriminator of the device to commission with -longDiscriminator or provide a valid passcode with -passcode\",\n );\n }\n\n // Collect commissioning options from commandline parameters\n const commissioningOptions: CommissioningOptions = {\n regulatoryLocation: GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor,\n regulatoryCountryCode: \"XX\",\n };\n\n let ble = false;\n if (hasParameter(\"ble\")) {\n ble = true;\n const wifiSsid = getParameter(\"ble-wifi-ssid\");\n const wifiCredentials = getParameter(\"ble-wifi-credentials\");\n const threadNetworkName = getParameter(\"ble-thread-networkname\");\n const threadOperationalDataset = getParameter(\"ble-thread-operationaldataset\");\n if (wifiSsid !== undefined && wifiCredentials !== undefined) {\n logger.info(`Registering Commissioning over BLE with WiFi: ${wifiSsid}`);\n commissioningOptions.wifiNetwork = {\n wifiSsid: wifiSsid,\n wifiCredentials: wifiCredentials,\n };\n }\n if (threadNetworkName !== undefined && threadOperationalDataset !== undefined) {\n logger.info(`Registering Commissioning over BLE with Thread: ${threadNetworkName}`);\n commissioningOptions.threadNetwork = {\n networkName: threadNetworkName,\n operationalDataset: threadOperationalDataset,\n };\n }\n }\n\n /**\n * Create Matter Server and Controller Node\n *\n * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a\n * CommissioningController to it and add the just created device instance to it.\n * The Controller node defines the port where the server listens for the UDP packages of the Matter protocol\n * and initializes deice specific certificates and such.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled internally\n * like testEventTrigger (General Diagnostic Cluster) that can be implemented with the logic when these commands\n * are called.\n */\n\n const matterServer = new MatterServer(storageManager);\n const commissioningController = new CommissioningController({\n autoConnect: false,\n });\n await matterServer.addCommissioningController(commissioningController);\n\n /**\n * Start the Matter Server\n *\n * After everything was plugged together we can start the server. When not delayed announcement is set for the\n * CommissioningServer node then this command also starts the announcement of the device into the network.\n */\n\n await matterServer.start();\n\n if (!commissioningController.isCommissioned()) {\n const options = {\n commissioning: commissioningOptions,\n discovery: {\n knownAddress: ip !== undefined && port !== undefined ? { ip, port, type: \"udp\" } : undefined,\n identifierData:\n longDiscriminator !== undefined\n ? { longDiscriminator }\n : shortDiscriminator !== undefined\n ? { shortDiscriminator }\n : {},\n discoveryCapabilities: {\n ble,\n },\n },\n passcode: setupPin,\n } as NodeCommissioningOptions;\n logger.info(`Commissioning ... ${Logger.toJSON(options)}`);\n const nodeId = await commissioningController.commissionNode(options);\n\n console.log(`Commissioning successfully done with nodeId ${nodeId}`);\n }\n\n /**\n * TBD\n */\n try {\n const nodes = commissioningController.getCommissionedNodes();\n console.log(\"Found commissioned nodes:\", Logger.toJSON(nodes));\n\n const nodeId = NodeId(getIntParameter(\"nodeid\") ?? nodes[0]);\n if (!nodes.includes(nodeId)) {\n throw new Error(`Node ${nodeId} not found in commissioned nodes`);\n }\n\n const node = await commissioningController.connectNode(nodeId, {\n attributeChangedCallback: (\n peerNodeId,\n { path: { nodeId, clusterId, endpointId, attributeName }, value },\n ) =>\n console.log(\n `attributeChangedCallback ${peerNodeId}: Attribute ${nodeId}/${endpointId}/${clusterId}/${attributeName} changed to ${Logger.toJSON(\n value,\n )}`,\n ),\n eventTriggeredCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, eventName }, events }) =>\n console.log(\n `eventTriggeredCallback ${peerNodeId}: Event ${nodeId}/${endpointId}/${clusterId}/${eventName} triggered with ${Logger.toJSON(\n events,\n )}`,\n ),\n stateInformationCallback: (peerNodeId, info) => {\n switch (info) {\n case NodeStateInformation.Connected:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} connected`);\n break;\n case NodeStateInformation.Disconnected:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} disconnected`);\n break;\n case NodeStateInformation.Reconnecting:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} reconnecting`);\n break;\n case NodeStateInformation.WaitingForDeviceDiscovery:\n console.log(\n `stateInformationCallback ${peerNodeId}: Node ${nodeId} waiting for device discovery`,\n );\n break;\n case NodeStateInformation.StructureChanged:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} structure changed`);\n break;\n case NodeStateInformation.Decommissioned:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} decommissioned`);\n break;\n }\n },\n });\n\n // Important: This is a temporary API to proof the methods working and this will change soon and is NOT stable!\n // It is provided to proof the concept\n\n node.logStructure();\n\n // Example to initialize a ClusterClient and access concrete fields as API methods\n const descriptor = node.getRootClusterClient(DescriptorCluster);\n if (descriptor !== undefined) {\n console.log(await descriptor.attributes.deviceTypeList.get()); // you can call that way\n console.log(await descriptor.getServerListAttribute()); // or more convenient that way\n } else {\n console.log(\"No Descriptor Cluster found. This should never happen!\");\n }\n\n // Example to subscribe to a field and get the value\n const info = node.getRootClusterClient(BasicInformationCluster);\n if (info !== undefined) {\n console.log(await info.getProductNameAttribute()); // This call is executed remotely\n //console.log(await info.subscribeProductNameAttribute(value => console.log(\"productName\", value), 5, 30));\n //console.log(await info.getProductNameAttribute()); // This call is resolved locally because we have subscribed to the value!\n } else {\n console.log(\"No BasicInformation Cluster found. This should never happen!\");\n }\n\n // Example to get all Attributes of the commissioned node: */*/*\n //const attributesAll = await interactionClient.getAllAttributes();\n //console.log(\"Attributes-All:\", Logger.toJSON(attributesAll));\n\n // Example to get all Attributes of all Descriptor Clusters of the commissioned node: */DescriptorCluster/*\n //const attributesAllDescriptor = await interactionClient.getMultipleAttributes([{ clusterId: DescriptorCluster.id} ]);\n //console.log(\"Attributes-Descriptor:\", JSON.stringify(attributesAllDescriptor, null, 2));\n\n // Example to get all Attributes of the Basic Information Cluster of endpoint 0 of the commissioned node: 0/BasicInformationCluster/*\n //const attributesBasicInformation = await interactionClient.getMultipleAttributes([{ endpointId: 0, clusterId: BasicInformationCluster.id} ]);\n //console.log(\"Attributes-BasicInformation:\", JSON.stringify(attributesBasicInformation, null, 2));\n\n const devices = node.getDevices();\n if (devices[0] && devices[0].number === 1) {\n // Example to subscribe to all Attributes of endpoint 1 of the commissioned node: */*/*\n //await interactionClient.subscribeMultipleAttributes([{ endpointId: 1, /* subscribe anything from endpoint 1 */ }], 0, 180, data => {\n // console.log(\"Subscribe-All Data:\", Logger.toJSON(data));\n //});\n\n const onOff = devices[0].getClusterClient(OnOffCluster);\n if (onOff !== undefined) {\n let onOffStatus = await onOff.getOnOffAttribute();\n console.log(\"initial onOffStatus\", onOffStatus);\n\n onOff.addOnOffAttributeListener(value => {\n console.log(\"subscription onOffStatus\", value);\n onOffStatus = value;\n });\n // read data every minute to keep up the connection to show the subscription is working\n setInterval(() => {\n onOff\n .toggle()\n .then(() => {\n onOffStatus = !onOffStatus;\n console.log(\"onOffStatus\", onOffStatus);\n })\n .catch(error => logger.error(error));\n }, 60000);\n }\n }\n } finally {\n //await matterServer.close(); // Comment out when subscribes are used, else the connection will be closed\n setTimeout(() => process.exit(0), 1000000);\n }\n }\n}\n\nnew ControllerNode().start().catch(error => logger.error(error));\n\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n // Pragmatic way to make sure the storage is correctly closed before the process ends.\n storage.close();\n process.exit(0);\n});\n"],
|
5
|
+
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAgBA;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAEP,SAAS,eAAe;AACxB,SAAS,yBAAyB,oBAA8C;AAChF,SAAS,WAAW,UAAU,QAAQ,gBAAgB,iBAAiB;AACvE,SAAS,WAAW;AACpB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,cAAc;AACvB,SAAS,4BAA4B;AAErC,SAAS,8BAA8B;AAEvC,MAAM,SAAS,OAAO,IAAI,YAAY;AAEtC,sBAAsB,EAAE;AAGxB,QAAQ,aAAa,UAAU,GAAG;AAAA,EAC9B,KAAK;AACD,WAAO,kBAAkB,SAAS;AAClC;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,SAAS;AAClC;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,SAAS;AAClC;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,SAAS;AAClC;AACR;AAEA,QAAQ,aAAa,WAAW,GAAG;AAAA,EAC/B,KAAK;AACD,WAAO,SAAS,UAAU;AAC1B;AAAA,EACJ,KAAK;AACD,WAAO,SAAS,UAAU;AAC1B;AAAA,EACJ;AACI,QAAI,QAAQ,OAAO,MAAO,QAAO,SAAS,UAAU;AAC5D;AAEA,IAAI,aAAa,KAAK,GAAG;AAErB,MAAI,MAAM;AAAA,IACN,MACI,IAAI,QAAQ;AAAA,MACR,OAAO,gBAAgB,YAAY;AAAA,IACvC,CAAC;AAAA,EACT;AACJ;AAEA,MAAM,kBAAkB,aAAa,OAAO,KAAK;AACjD,MAAM,UAAU,IAAI,mBAAmB,iBAAiB,aAAa,cAAc,CAAC;AACpF,OAAO,KAAK,qBAAqB,eAAe,cAAc;AAC9D,OAAO;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
|
* Copyright 2022-2024 Matter.js Authors
|
5
5
|
* SPDX-License-Identifier: Apache-2.0
|
6
6
|
*/
|
7
|
-
import "@project-chip/matter
|
8
|
-
import {
|
7
|
+
import { requireMinNodeVersion } from "@project-chip/matter.js-nodejs";
|
8
|
+
import { Time } from "@project-chip/matter.js-general";
|
9
9
|
import { DeviceTypeId, VendorId } from "@project-chip/matter.js/datatype";
|
10
10
|
import { logEndpoint } from "@project-chip/matter.js/device";
|
11
11
|
import { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
|
@@ -13,7 +13,6 @@ import { OnOffPlugInUnitDevice } from "@project-chip/matter.js/devices/OnOffPlug
|
|
13
13
|
import { Endpoint, EndpointServer } from "@project-chip/matter.js/endpoint";
|
14
14
|
import { Environment, StorageService } from "@project-chip/matter.js/environment";
|
15
15
|
import { ServerNode } from "@project-chip/matter.js/node";
|
16
|
-
import { Time } from "@project-chip/matter.js/time";
|
17
16
|
import { execSync } from "child_process";
|
18
17
|
requireMinNodeVersion(16);
|
19
18
|
async function main() {
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/DeviceNode.ts"],
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This example shows how to create a simple on-off Matter device as a light or as a socket.\n * It can be used as CLI script and starting point for your own device node implementation.\n * This example is CJS conform and do not use top level await's.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter
|
5
|
-
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAgBA,
|
4
|
+
"sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This example shows how to create a simple on-off Matter device as a light or as a socket.\n * It can be used as CLI script and starting point for your own device node implementation.\n * This example is CJS conform and do not use top level await's.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport { requireMinNodeVersion } from \"@project-chip/matter.js-nodejs\";\n\nimport { Time } from \"@project-chip/matter.js-general\";\nimport { DeviceTypeId, VendorId } from \"@project-chip/matter.js/datatype\";\nimport { logEndpoint } from \"@project-chip/matter.js/device\";\nimport { OnOffLightDevice } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { OnOffPlugInUnitDevice } from \"@project-chip/matter.js/devices/OnOffPlugInUnitDevice\";\nimport { Endpoint, EndpointServer } from \"@project-chip/matter.js/endpoint\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\nimport { execSync } from \"child_process\";\n\nrequireMinNodeVersion(16);\n\nasync function main() {\n /** Initialize configuration values */\n const {\n isSocket,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n } = await getConfiguration();\n\n /**\n * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration\n */\n const server = await ServerNode.create({\n // Required: Give the Node a unique ID which is used to store the state of this node\n id: uniqueId,\n\n // Provide Network relevant configuration like the port\n // Optional when operating only one device on a host, Default port is 5540\n network: {\n port,\n },\n\n // Provide Commissioning relevant settings\n // Optional for development/testing purposes\n commissioning: {\n passcode,\n discriminator,\n },\n\n // Provide Node announcement settings\n // Optional: If Ommitted some development defaults are used\n productDescription: {\n name: deviceName,\n deviceType: DeviceTypeId(isSocket ? OnOffPlugInUnitDevice.deviceType : OnOffLightDevice.deviceType),\n },\n\n // Provide defaults for the BasicInformation cluster on the Root endpoint\n // Optional: If Omitted some development defaults are used\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `matterjs-${uniqueId}`,\n uniqueId,\n },\n });\n\n /**\n * Matter Nodes are a composition of endpoints. Create and add a single endpoint to the node. This example uses the\n * OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type parameter. It also assigns this Part a\n * unique ID to store the endpoint number for it in the storage to restore the device on restart.\n * In this case we directly use the default command implementation from matter.js. Check out the DeviceNodeFull example\n * to see how to customize the command handlers.\n */\n const endpoint = new Endpoint(isSocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: \"onoff\" });\n await server.add(endpoint);\n\n /**\n * Register state change handlers and events of the node for identify and onoff states to react to the commands.\n * If the code in these change handlers fail then the change is also rolled back and not executed and an error is\n * reported back to the controller.\n */\n endpoint.events.identify.startIdentifying.on(() => {\n console.log(`Run identify logic, ideally blink a light every 0.5s ...`);\n });\n\n endpoint.events.identify.stopIdentifying.on(() => {\n console.log(`Stop identify logic ...`);\n });\n\n endpoint.events.onOff.onOff$Changed.on(value => {\n executeCommand(value ? \"on\" : \"off\");\n console.log(`OnOff is now ${value ? \"ON\" : \"OFF\"}`);\n });\n\n /**\n * Log the endpoint structure for debugging reasons and to allow to verify anything is correct\n */\n logEndpoint(EndpointServer.forEndpoint(server));\n\n /**\n * In order to start the node and announce it into the network we use the run method which resolves when the node goes\n * offline again because we do not need anything more here. See the Full example for other starting options.\n * The QR Code is printed automatically.\n */\n await server.run();\n}\n\nmain().catch(error => console.error(error));\n\n/*********************************************************************************************************\n * Convenience Methods\n *********************************************************************************************************/\n\n/** Defined a shell command from an environment variable and execute it and log the response. */\nfunction executeCommand(scriptParamName: string) {\n const script = Environment.default.vars.string(scriptParamName);\n if (script === undefined) return undefined;\n console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);\n}\n\nasync function getConfiguration() {\n /**\n * Collect all needed data\n *\n * This block collects all needed data from cli, environment or storage. Replace this with where ever your data come from.\n *\n * Note: This example uses the matter.js process storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts\n * (so maybe better not do it ;-)).\n */\n const environment = Environment.default;\n\n const storageService = environment.get(StorageService);\n console.log(`Storage location: ${storageService.location} (Directory)`);\n console.log(\n 'Use the parameter \"--storage-path=NAME-OR-PATH\" to specify a different storage location in this directory, use --storage-clear to start with an empty storage.',\n );\n const deviceStorage = (await storageService.open(\"device\")).createContext(\"data\");\n\n const isSocket = await deviceStorage.get(\"isSocket\", environment.vars.get(\"type\") === \"socket\");\n if (await deviceStorage.has(\"isSocket\")) {\n console.log(`Device type ${isSocket ? \"socket\" : \"light\"} found in storage. --type parameter is ignored.`);\n }\n const deviceName = \"Matter test device\";\n const vendorName = \"matter-node.js\";\n const passcode = environment.vars.number(\"passcode\") ?? (await deviceStorage.get(\"passcode\", 20202021));\n const discriminator = environment.vars.number(\"discriminator\") ?? (await deviceStorage.get(\"discriminator\", 3840));\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = environment.vars.number(\"vendorid\") ?? (await deviceStorage.get(\"vendorid\", 0xfff1));\n const productName = `node-matter OnOff ${isSocket ? \"Socket\" : \"Light\"}`;\n const productId = environment.vars.number(\"productid\") ?? (await deviceStorage.get(\"productid\", 0x8000));\n\n const port = environment.vars.number(\"port\") ?? 5540;\n\n const uniqueId =\n environment.vars.string(\"uniqueid\") ?? (await deviceStorage.get(\"uniqueid\", Time.nowMs())).toString();\n\n // Persist basic data to keep them also on restart\n await deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n isSocket,\n uniqueid: uniqueId,\n });\n\n return {\n isSocket,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n };\n}\n"],
|
5
|
+
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAgBA,SAAS,6BAA6B;AAEtC,SAAS,YAAY;AACrB,SAAS,cAAc,gBAAgB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AACtC,SAAS,UAAU,sBAAsB;AACzC,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IAAI,YAAY,KAAK,MAAM,CAAC,GAAG,SAAS;AAGxG,QAAM,cAAc,IAAI;AAAA,IACpB;AAAA,IACA;AAAA,IACA,UAAU;AAAA,IACV,WAAW;AAAA,IACX;AAAA,IACA,UAAU;AAAA,EACd,CAAC;AAED,SAAO;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ;AACJ;",
|
6
6
|
"names": []
|
7
7
|
}
|
@@ -4,10 +4,9 @@
|
|
4
4
|
* Copyright 2022-2024 Matter.js Authors
|
5
5
|
* SPDX-License-Identifier: Apache-2.0
|
6
6
|
*/
|
7
|
-
import "@project-chip/matter
|
7
|
+
import { createFileLogger, requireMinNodeVersion } from "@project-chip/matter.js-nodejs";
|
8
8
|
import { BleNode } from "@project-chip/matter-node-ble.js/ble";
|
9
|
-
import {
|
10
|
-
import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
|
9
|
+
import { LogLevel, Logger, Time, logLevelFromString, singleton } from "@project-chip/matter.js-general";
|
11
10
|
import { NetworkCommissioningServer } from "@project-chip/matter.js/behavior/definitions/network-commissioning";
|
12
11
|
import { OnOffServer } from "@project-chip/matter.js/behavior/definitions/on-off";
|
13
12
|
import { Ble } from "@project-chip/matter.js/ble";
|
@@ -20,11 +19,8 @@ import { Endpoint, EndpointServer } from "@project-chip/matter.js/endpoint";
|
|
20
19
|
import { RootRequirements } from "@project-chip/matter.js/endpoint/definitions";
|
21
20
|
import { Environment, StorageService } from "@project-chip/matter.js/environment";
|
22
21
|
import { FabricAction } from "@project-chip/matter.js/fabric";
|
23
|
-
import { Level, Logger, levelFromString } from "@project-chip/matter.js/log";
|
24
22
|
import { ServerNode } from "@project-chip/matter.js/node";
|
25
23
|
import { QrCode } from "@project-chip/matter.js/schema";
|
26
|
-
import { Time } from "@project-chip/matter.js/time";
|
27
|
-
import { ByteArray, singleton } from "@project-chip/matter.js/util";
|
28
24
|
import { execSync } from "child_process";
|
29
25
|
import { DummyThreadNetworkCommissioningServer } from "./cluster/DummyThreadNetworkCommissioningServer.js";
|
30
26
|
import { DummyWifiNetworkCommissioningServer } from "./cluster/DummyWifiNetworkCommissioningServer.js";
|
@@ -48,7 +44,7 @@ function executeCommand(scriptParamName) {
|
|
48
44
|
const logFile = environment.vars.string("logfile.filename");
|
49
45
|
if (logFile !== void 0) {
|
50
46
|
Logger.addLogger("filelogger", await createFileLogger(logFile), {
|
51
|
-
defaultLogLevel:
|
47
|
+
defaultLogLevel: logLevelFromString(environment.vars.string("logfile.loglevel")) ?? LogLevel.DEBUG
|
52
48
|
});
|
53
49
|
}
|
54
50
|
const storageService = environment.get(StorageService);
|
@@ -138,7 +134,7 @@ if (Ble.enabled) {
|
|
138
134
|
NetworkCommissioningServer.with(NetworkCommissioning.Feature.EthernetNetworkInterface)
|
139
135
|
);
|
140
136
|
}
|
141
|
-
const networkId = new
|
137
|
+
const networkId = new Uint8Array(32);
|
142
138
|
const server = await ServerNode.create(RootEndpoint, {
|
143
139
|
id: uniqueId,
|
144
140
|
network: {
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/DeviceNodeFull.ts"],
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This example is not optimized for simplicity, but to show all the advanced use cases for matter.js.\n * If you want to see a simple minimalistic and more standard example please look at DeviceNode.ts or the other examples.\n *\n * This example shows how to create a simple on-off Matter device as a light or as a socket.\n * It can be used as CLI script and starting point for your own device node implementation.\n * Additional to this it shows the following:\n * * How to modify the existing clusters on Root and also Device Endpoints\n * * How to add own Cluster implementations for Standard clusters\n * * How to add a custom Cluster to an Endpoint\n * * Which events are available to get status information from the Node aon commissioning and session/subscription changes\n * * How to get cluster state values\n * * How to set one or multiple state values in a transaction.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter-node.js\";\n\nimport { BleNode } from \"@project-chip/matter-node-ble.js/ble\";\nimport { GeneralDiagnostics } from \"@project-chip/matter-node.js/cluster\";\nimport { createFileLogger } from \"@project-chip/matter-node.js/log\";\nimport { requireMinNodeVersion } from \"@project-chip/matter-node.js/util\";\nimport { NetworkCommissioningServer } from \"@project-chip/matter.js/behavior/definitions/network-commissioning\";\nimport { OnOffServer } from \"@project-chip/matter.js/behavior/definitions/on-off\";\nimport { Ble } from \"@project-chip/matter.js/ble\";\nimport { NetworkCommissioning } from \"@project-chip/matter.js/cluster\";\nimport { DeviceTypeId, VendorId } from \"@project-chip/matter.js/datatype\";\nimport { logEndpoint } from \"@project-chip/matter.js/device\";\nimport { OnOffLightDevice } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { OnOffPlugInUnitDevice } from \"@project-chip/matter.js/devices/OnOffPlugInUnitDevice\";\nimport { Endpoint, EndpointServer } from \"@project-chip/matter.js/endpoint\";\nimport { RootRequirements } from \"@project-chip/matter.js/endpoint/definitions\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { FabricAction } from \"@project-chip/matter.js/fabric\";\nimport { Level, Logger, levelFromString } from \"@project-chip/matter.js/log\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\nimport { QrCode } from \"@project-chip/matter.js/schema\";\nimport { Time } from \"@project-chip/matter.js/time\";\nimport { ByteArray, singleton } from \"@project-chip/matter.js/util\";\nimport { execSync } from \"child_process\";\nimport { DummyThreadNetworkCommissioningServer } from \"./cluster/DummyThreadNetworkCommissioningServer.js\";\nimport { DummyWifiNetworkCommissioningServer } from \"./cluster/DummyWifiNetworkCommissioningServer.js\";\nimport {\n MyFancyCommandRequest,\n MyFancyCommandResponse,\n MyFancyOwnFunctionalityBehavior,\n} from \"./cluster/MyFancyOwnFunctionality.js\";\n\n/**\n * The following code brings some convenience to the CLI script. It allows to set the log level and format via\n * command line parameters. It also initializes the BLE stack if the `--ble` parameter is present.\n * Some of these parameters can also be replaced by generically accepted parameters or even environment variables. See the comments in the relevant places for information.\n * When using this code as basis for your own device node implementation, you can remove this part or hard code it.\n */\n\nrequireMinNodeVersion(16);\n\n// To configure Logging use\n// * \"--log-level\" or environment variable \"MATTER_LOG_LEVEL\" or \"environment.vars.set('log.level', Level.DEBUG)\"\n// Allowed values are: Level.FATAL, Level.ERROR, Level.WARN, Level.NOTICE, Level.INFO, Level.DEBUG\n// * \"--log-format\" or environment variable \"MATTER_LOG_FORMAT\" or \"environment.vars.set('log.format', Format.PLAIN)\"\n// Allowed values are: Format.PLAIN, Format.HTML, Format.ANSI,\n\nconst environment = Environment.default;\n\n// Alternatively \"--ble-enable\" or environment variable \"BLE_ENABLED\"\n// Alternatively \"--ble-hciId\" or environment variable \"BLE_HCIID\"\nif (environment.vars.get(\"ble.enable\")) {\n // Initialize Ble\n Ble.get = singleton(\n () =>\n new BleNode({\n hciId: environment.vars.number(\"ble.hciId\"),\n }),\n );\n}\n\nfunction executeCommand(scriptParamName: string) {\n const script = environment.vars.string(scriptParamName);\n if (script === undefined) return undefined;\n console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);\n}\n\n/**\n * Collect all needed data\n *\n * This block collects all needed data from cli or storage. Replace this with where ever your data come from.\n *\n * Note: This example uses the matter.js process storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts\n * (so maybe better not do it ;-)).\n */\n\nconst logFile = environment.vars.string(\"logfile.filename\");\nif (logFile !== undefined) {\n Logger.addLogger(\"filelogger\", await createFileLogger(logFile), {\n defaultLogLevel: levelFromString(environment.vars.string(\"logfile.loglevel\")) ?? Level.DEBUG,\n });\n}\n\nconst storageService = environment.get(StorageService);\nconsole.log(`Storage location: ${storageService.location} (Directory)`);\nconsole.log(\n 'Use the parameter \"--storage-path=NAME-OR-PATH\" to specify a different storage location in this directory, use --storage-clear to start with an empty storage.',\n);\n\nconst deviceStorage = (await storageService.open(\"device\")).createContext(\"data\");\n\nif (await deviceStorage.has(\"isSocket\")) {\n console.log(\"Device type found in storage. --type parameter is ignored.\");\n}\nconst isSocket = await deviceStorage.get(\"isSocket\", environment.vars.string(\"type\") === \"socket\");\nconst deviceName = \"Matter test device\";\nconst vendorName = \"matter-node.js\";\nconst passcode = environment.vars.number(\"passcode\") ?? (await deviceStorage.get(\"passcode\", 20202021));\nconst discriminator = environment.vars.number(\"discriminator\") ?? (await deviceStorage.get(\"discriminator\", 3840));\n// product name / id and vendor id should match what is in the device certificate\nconst vendorId = environment.vars.number(\"vendorid\") ?? (await deviceStorage.get(\"vendorid\", 0xfff1));\nconst productName = `node-matter OnOff ${isSocket ? \"Socket\" : \"Light\"}`;\nconst productId = environment.vars.number(\"productid\") ?? (await deviceStorage.get(\"productid\", 0x8000));\n\nconst port = environment.vars.number(\"port\") ?? 5540;\n\nconst uniqueId = environment.vars.string(\"uniqueid\") ?? (await deviceStorage.get(\"uniqueid\", Time.nowMs().toString()));\n\nawait deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n isSocket,\n uniqueid: uniqueId,\n});\n\n// Matter exposes functionality in groups called \"clusters\". For this example device we override the matter.js \"On/Off\"\n// cluster implementation to print status to the console.\nclass OnOffShellExecServer extends OnOffServer {\n // Intercept the \"on\" command to the Matter On/Off cluster to print a log message.\n override async on() {\n executeCommand(\"on\");\n await super.on();\n }\n\n // This is the functional inverse of on() above.\n //\n // For demonstration purposes we update state ourselves rather than deferring to matter.js's default \"off\" handler\n // via super.off().\n override async off() {\n executeCommand(\"off\");\n this.state.onOff = false;\n }\n\n // Use event handlers to log on/off state reactively, after it changes.\n override initialize() {\n this.events.onOff$Changed.on(value => {\n console.log(`Light is now ${value ? \"ON\" : \"OFF\"}`);\n });\n }\n}\n\nclass TestGeneralDiagnosticsServer extends RootRequirements.GeneralDiagnosticsServer {\n override initialize() {\n this.state.testEventTriggersEnabled = true; // set to true if you support test triggers ...\n super.initialize();\n }\n\n override testEventTrigger({ enableKey, eventTrigger }: GeneralDiagnostics.TestEventTriggerRequest) {\n console.log(`testEventTrigger called on GeneralDiagnostic cluster: ${enableKey} ${eventTrigger}`);\n }\n}\n\nclass MyFancyOwnFunctionalityServer extends MyFancyOwnFunctionalityBehavior {\n /** We return the incoming value and store the length of the string in our attribute and send it out as event */\n override myFancyCommand(request: MyFancyCommandRequest): MyFancyCommandResponse {\n const { value } = request;\n this.state.myFancyValue = value.length;\n\n this.events.myFancyEvent.emit({ eventValue: value }, this.context);\n\n return { response: value };\n }\n\n override initialize() {\n this.state.myFancyValue = -1; // Always initialize with -1\n }\n}\n\n/**\n * Create Device instance and add needed Listener\n *\n * Create an instance of the matter device class you want to use.\n * This example uses the OnOffLightDevice or OnOffPluginUnitDevice depending on the value of the type parameter.\n * To execute the on/off scripts defined as parameters a listener for the onOff attribute is registered via the\n * device specific API.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled device internally\n * like identify that can be implemented with the logic when these commands are called.\n */\n\n// Devices are compositions of behaviors like OnOffServer above. To extend an existing device you use builder methods.\n//\n// In this case we are using with() to install our On/Off cluster behavior.\n// .with(\"Lighting\") not needed because we always have it in by default because we have default implementation\nconst OnOffDevice = isSocket\n ? vendorId === 0xfff4\n ? OnOffPlugInUnitDevice.with(OnOffShellExecServer, MyFancyOwnFunctionalityServer)\n : OnOffPlugInUnitDevice.with(OnOffShellExecServer)\n : vendorId === 0xfff4\n ? OnOffLightDevice.with(OnOffShellExecServer, MyFancyOwnFunctionalityServer)\n : OnOffLightDevice.with(OnOffShellExecServer);\n\n/**\n * Modify automatically added clusters of the Root endpoint if needed\n * In this example we change the networkCommissioning cluster into one for \"Wifi only\" devices when BLE is used\n * for commissioning, to demonstrate how to do this.\n * If you want to implement Ethernet only devices that get connected to the network via LAN/Ethernet cable,\n * then all this is not needed.\n * The same as shown here for Wi-Fi is also possible theoretical for Thread only or combined devices.\n */\n\n// We use the Basic Root Endpoint without a NetworkCommissioning cluster\nlet RootEndpoint = ServerNode.RootEndpoint.with(TestGeneralDiagnosticsServer);\n\nlet wifiOrThreadAdded = false;\nlet threadAdded = false;\nif (Ble.enabled) {\n // matter.js will create a Ethernet-only device by default when ut comes to Network Commissioning Features.\n // To offer e.g. a \"Wi-Fi only device\" (or any other combination) we need to override the Network Commissioning\n // cluster and implement all the need handling here. This is a \"static implementation\" for pure demonstration\n // purposes and just \"simulates\" the actions to be done. In a real world implementation this would be done by\n // the device implementor based on the relevant networking stack.\n // The NetworkCommissioningCluster and all logics are described in Matter Core Specifications section 11.8\n if (environment.vars.has(\"ble.wifi.fake\")) {\n RootEndpoint = RootEndpoint.with(DummyWifiNetworkCommissioningServer);\n wifiOrThreadAdded = true;\n } else if (environment.vars.has(\"ble.thread.fake\")) {\n RootEndpoint = RootEndpoint.with(DummyThreadNetworkCommissioningServer);\n wifiOrThreadAdded = true;\n threadAdded = true;\n }\n} else {\n RootEndpoint = RootEndpoint.with(\n NetworkCommissioningServer.with(NetworkCommissioning.Feature.EthernetNetworkInterface),\n );\n}\n\nconst networkId = new ByteArray(32);\n// Physical devices appear as \"nodes\" on a Matter network. As a device implementer you use a NodeServer to bring a\n// device online.\n//\n// Note there are a large number of options to NodeServer that we are allowing to take default values here. See\n// CompositeWindowCovering.ts for a more detailed example.\nconst server = await ServerNode.create(RootEndpoint, {\n id: uniqueId,\n network: {\n port,\n discoveryCapabilities: {\n onIpNetwork: !environment.vars.has(\"ble.enable\"),\n ble: environment.vars.has(\"ble.enable\"),\n },\n ble: environment.vars.has(\"ble.enable\"), // TODO remove when state init is fixed\n },\n commissioning: {\n passcode,\n discriminator,\n },\n productDescription: {\n name: deviceName,\n deviceType: DeviceTypeId(OnOffDevice.deviceType),\n },\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `node-matter-${uniqueId}`,\n uniqueId,\n },\n\n // @ts-expect-error ... TS do not see the types because both next clusters was added conditionally\n networkCommissioning: {\n maxNetworks: 1,\n interfaceEnabled: true,\n lastConnectErrorValue: 0,\n lastNetworkId: wifiOrThreadAdded ? null : networkId,\n lastNetworkingStatus: wifiOrThreadAdded ? null : NetworkCommissioning.NetworkCommissioningStatus.Success,\n networks: [{ networkId: networkId, connected: !wifiOrThreadAdded }],\n scanMaxTimeSeconds: wifiOrThreadAdded ? 3 : undefined,\n connectMaxTimeSeconds: wifiOrThreadAdded ? 3 : undefined,\n supportedWifiBands: wifiOrThreadAdded && !threadAdded ? [NetworkCommissioning.WiFiBand[\"2G4\"]] : undefined,\n supportedThreadFeatures: wifiOrThreadAdded && threadAdded ? { isFullThreadDevice: true } : undefined,\n threadVersion: wifiOrThreadAdded && threadAdded ? 4 : undefined, // means: Thread 1.3\n },\n myFancyFunctionality: {\n myFancyValue: 0,\n },\n});\n\n// Nodes are a composition of endpoints. Add a single endpoint to the node, our example light device.\nconst endpoint = new Endpoint(OnOffDevice, { id: \"onoff\" });\nawait server.add(endpoint);\n\n/**\n * This event is triggered when the device is initially commissioned successfully.\n * This means: It is added to the first fabric.\n */\nserver.lifecycle.commissioned.on(() => console.log(\"Server was initially commissioned successfully!\"));\n\n/** This event is triggered when all fabrics are removed from the device, usually it also does a factory reset then. */\nserver.lifecycle.decommissioned.on(() => console.log(\"Server was fully decommissioned successfully!\"));\n\n/** This event is triggered when the device went online. This means that it is discoverable in the network. */\nserver.lifecycle.online.on(() => console.log(\"Server is online\"));\n\n/** This event is triggered when the device went offline. it is not longer discoverable or connectable in the network. */\nserver.lifecycle.offline.on(() => console.log(\"Server is offline\"));\n\n/**\n * This event is triggered when a fabric is added, removed or updated on the device. Use this if more granular\n * information is needed.\n */\nserver.events.commissioning.fabricsChanged.on((fabricIndex, fabricAction) => {\n let action = \"\";\n switch (fabricAction) {\n case FabricAction.Added:\n action = \"added\";\n break;\n case FabricAction.Removed:\n action = \"removed\";\n break;\n case FabricAction.Updated:\n action = \"updated\";\n break;\n }\n console.log(`Commissioned Fabrics changed event (${action}) for ${fabricIndex} triggered`);\n console.log(server.state.commissioning.fabrics[fabricIndex]);\n});\n\n/**\n * This event is triggered when an operative new session was opened by a Controller.\n * It is not triggered for the initial commissioning process, just afterwards for real connections.\n */\nserver.events.sessions.opened.on(session => console.log(`Session opened`, session));\n\n/**\n * This event is triggered when an operative session is closed by a Controller or because the Device goes offline.\n */\nserver.events.sessions.closed.on(session => console.log(`Session closed`, session));\n\n/** This event is triggered when a subscription gets added or removed on an operative session. */\nserver.events.sessions.subscriptionsChanged.on(session => {\n console.log(`Session subscriptions changed`, session);\n console.log(`Status of all sessions`, server.state.sessions.sessions);\n});\n\n// React on a change of identificationTime to do Identify stuff for the own device\nendpoint.events.identify.startIdentifying.on(() => {\n console.log(`Run identify logic, ideally blink a light every 0.5s ...`);\n});\n\nendpoint.events.identify.stopIdentifying.on(() => {\n console.log(`Stop identify logic ...`);\n});\n\n// Our device is now built and we can bring the node online.\n//\n// Note that you may serve multiple nodes from a single process. We only have one, however, so we can use the run()\n// method of the node.\n\nlogEndpoint(EndpointServer.forEndpoint(server));\n\n/**\n * In order to start the node and announce it into the network we start the node. This method resolves when the Matter\n * node enters his online state. Alternatively, we could also use `await server.run()` which\n * resolves when the node goes offline again, but we want to execute code afterwards, so we use start() here\n */\nawait server.start();\n\nconsole.log(\"Initial Fabrics\", server.state.operationalCredentials.fabrics);\n\n/**\n * If the node is not commissioned already we display the QR code on console. The QR code is also logged\n */\nif (!server.lifecycle.isCommissioned) {\n const { qrPairingCode, manualPairingCode } = server.state.commissioning.pairingCodes;\n\n console.log(QrCode.get(qrPairingCode));\n console.log(`QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`);\n console.log(`Manual pairing code: ${manualPairingCode}`);\n} else {\n console.log(\"Device is already commissioned. Waiting for controllers to connect ...\");\n\n /**\n * Sometimes reading or writing attributes is required. The following code shows how this works.\n * For read it is basically `endpoint.state.clustername.attributename`.\n * The set method allows to set one or multiple values via the structure of also clustername.attributename. When multiple values are set they are considered being one transaction which would be rolled back completely if one value fails to be set.\n */\n\n // Read onOff attribute from onOff cluster\n const onOffValue = endpoint.state.onOff.onOff;\n console.log(`current OnOff attribute: ${onOffValue}`);\n\n if (vendorId === 0xfff4) {\n // Set onOff attribute from OnOff cluster AND the myFancyValue of the MyFancyOwnFunctionality cluster together\n await endpoint.set({\n onOff: {\n onOff: !onOffValue,\n },\n // @ts-expect-error Needed because the Fancy cluster is added conditionally, so TS do not get that it's there.\n myFancyOwnFunctionality: {\n myFancyValue: 36,\n },\n });\n } else {\n // Set onOff attribute from OnOff cluster only\n await endpoint.set({\n onOff: {\n onOff: !onOffValue,\n },\n });\n }\n}\n\n/**\n * To correctly tear down the server we can use server.close().\n */\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n server\n .close()\n .then(() => process.exit(0))\n .catch(err => console.error(err));\n});\n"],
|
5
|
-
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAyBA,
|
4
|
+
"sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This example is not optimized for simplicity, but to show all the advanced use cases for matter.js.\n * If you want to see a simple minimalistic and more standard example please look at DeviceNode.ts or the other examples.\n *\n * This example shows how to create a simple on-off Matter device as a light or as a socket.\n * It can be used as CLI script and starting point for your own device node implementation.\n * Additional to this it shows the following:\n * * How to modify the existing clusters on Root and also Device Endpoints\n * * How to add own Cluster implementations for Standard clusters\n * * How to add a custom Cluster to an Endpoint\n * * Which events are available to get status information from the Node aon commissioning and session/subscription changes\n * * How to get cluster state values\n * * How to set one or multiple state values in a transaction.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport { createFileLogger, requireMinNodeVersion } from \"@project-chip/matter.js-nodejs\";\n\nimport { BleNode } from \"@project-chip/matter-node-ble.js/ble\";\nimport { LogLevel, Logger, Time, logLevelFromString, singleton } from \"@project-chip/matter.js-general\";\nimport { NetworkCommissioningServer } from \"@project-chip/matter.js/behavior/definitions/network-commissioning\";\nimport { OnOffServer } from \"@project-chip/matter.js/behavior/definitions/on-off\";\nimport { Ble } from \"@project-chip/matter.js/ble\";\nimport { GeneralDiagnostics, NetworkCommissioning } from \"@project-chip/matter.js/cluster\";\nimport { DeviceTypeId, VendorId } from \"@project-chip/matter.js/datatype\";\nimport { logEndpoint } from \"@project-chip/matter.js/device\";\nimport { OnOffLightDevice } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { OnOffPlugInUnitDevice } from \"@project-chip/matter.js/devices/OnOffPlugInUnitDevice\";\nimport { Endpoint, EndpointServer } from \"@project-chip/matter.js/endpoint\";\nimport { RootRequirements } from \"@project-chip/matter.js/endpoint/definitions\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { FabricAction } from \"@project-chip/matter.js/fabric\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\nimport { QrCode } from \"@project-chip/matter.js/schema\";\nimport { execSync } from \"child_process\";\nimport { DummyThreadNetworkCommissioningServer } from \"./cluster/DummyThreadNetworkCommissioningServer.js\";\nimport { DummyWifiNetworkCommissioningServer } from \"./cluster/DummyWifiNetworkCommissioningServer.js\";\nimport {\n MyFancyCommandRequest,\n MyFancyCommandResponse,\n MyFancyOwnFunctionalityBehavior,\n} from \"./cluster/MyFancyOwnFunctionality.js\";\n\n/**\n * The following code brings some convenience to the CLI script. It allows to set the log level and format via\n * command line parameters. It also initializes the BLE stack if the `--ble` parameter is present.\n * Some of these parameters can also be replaced by generically accepted parameters or even environment variables. See the comments in the relevant places for information.\n * When using this code as basis for your own device node implementation, you can remove this part or hard code it.\n */\n\nrequireMinNodeVersion(16);\n\n// To configure Logging use\n// * \"--log-level\" or environment variable \"MATTER_LOG_LEVEL\" or \"environment.vars.set('log.level', Level.DEBUG)\"\n// Allowed values are: Level.FATAL, Level.ERROR, Level.WARN, Level.NOTICE, Level.INFO, Level.DEBUG\n// * \"--log-format\" or environment variable \"MATTER_LOG_FORMAT\" or \"environment.vars.set('log.format', Format.PLAIN)\"\n// Allowed values are: Format.PLAIN, Format.HTML, Format.ANSI,\n\nconst environment = Environment.default;\n\n// Alternatively \"--ble-enable\" or environment variable \"BLE_ENABLED\"\n// Alternatively \"--ble-hciId\" or environment variable \"BLE_HCIID\"\nif (environment.vars.get(\"ble.enable\")) {\n // Initialize Ble\n Ble.get = singleton(\n () =>\n new BleNode({\n hciId: environment.vars.number(\"ble.hciId\"),\n }),\n );\n}\n\nfunction executeCommand(scriptParamName: string) {\n const script = environment.vars.string(scriptParamName);\n if (script === undefined) return undefined;\n console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);\n}\n\n/**\n * Collect all needed data\n *\n * This block collects all needed data from cli or storage. Replace this with where ever your data come from.\n *\n * Note: This example uses the matter.js process storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts\n * (so maybe better not do it ;-)).\n */\n\nconst logFile = environment.vars.string(\"logfile.filename\");\nif (logFile !== undefined) {\n Logger.addLogger(\"filelogger\", await createFileLogger(logFile), {\n defaultLogLevel: logLevelFromString(environment.vars.string(\"logfile.loglevel\")) ?? LogLevel.DEBUG,\n });\n}\n\nconst storageService = environment.get(StorageService);\nconsole.log(`Storage location: ${storageService.location} (Directory)`);\nconsole.log(\n 'Use the parameter \"--storage-path=NAME-OR-PATH\" to specify a different storage location in this directory, use --storage-clear to start with an empty storage.',\n);\n\nconst deviceStorage = (await storageService.open(\"device\")).createContext(\"data\");\n\nif (await deviceStorage.has(\"isSocket\")) {\n console.log(\"Device type found in storage. --type parameter is ignored.\");\n}\nconst isSocket = await deviceStorage.get(\"isSocket\", environment.vars.string(\"type\") === \"socket\");\nconst deviceName = \"Matter test device\";\nconst vendorName = \"matter-node.js\";\nconst passcode = environment.vars.number(\"passcode\") ?? (await deviceStorage.get(\"passcode\", 20202021));\nconst discriminator = environment.vars.number(\"discriminator\") ?? (await deviceStorage.get(\"discriminator\", 3840));\n// product name / id and vendor id should match what is in the device certificate\nconst vendorId = environment.vars.number(\"vendorid\") ?? (await deviceStorage.get(\"vendorid\", 0xfff1));\nconst productName = `node-matter OnOff ${isSocket ? \"Socket\" : \"Light\"}`;\nconst productId = environment.vars.number(\"productid\") ?? (await deviceStorage.get(\"productid\", 0x8000));\n\nconst port = environment.vars.number(\"port\") ?? 5540;\n\nconst uniqueId = environment.vars.string(\"uniqueid\") ?? (await deviceStorage.get(\"uniqueid\", Time.nowMs().toString()));\n\nawait deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n isSocket,\n uniqueid: uniqueId,\n});\n\n// Matter exposes functionality in groups called \"clusters\". For this example device we override the matter.js \"On/Off\"\n// cluster implementation to print status to the console.\nclass OnOffShellExecServer extends OnOffServer {\n // Intercept the \"on\" command to the Matter On/Off cluster to print a log message.\n override async on() {\n executeCommand(\"on\");\n await super.on();\n }\n\n // This is the functional inverse of on() above.\n //\n // For demonstration purposes we update state ourselves rather than deferring to matter.js's default \"off\" handler\n // via super.off().\n override async off() {\n executeCommand(\"off\");\n this.state.onOff = false;\n }\n\n // Use event handlers to log on/off state reactively, after it changes.\n override initialize() {\n this.events.onOff$Changed.on(value => {\n console.log(`Light is now ${value ? \"ON\" : \"OFF\"}`);\n });\n }\n}\n\nclass TestGeneralDiagnosticsServer extends RootRequirements.GeneralDiagnosticsServer {\n override initialize() {\n this.state.testEventTriggersEnabled = true; // set to true if you support test triggers ...\n super.initialize();\n }\n\n override testEventTrigger({ enableKey, eventTrigger }: GeneralDiagnostics.TestEventTriggerRequest) {\n console.log(`testEventTrigger called on GeneralDiagnostic cluster: ${enableKey} ${eventTrigger}`);\n }\n}\n\nclass MyFancyOwnFunctionalityServer extends MyFancyOwnFunctionalityBehavior {\n /** We return the incoming value and store the length of the string in our attribute and send it out as event */\n override myFancyCommand(request: MyFancyCommandRequest): MyFancyCommandResponse {\n const { value } = request;\n this.state.myFancyValue = value.length;\n\n this.events.myFancyEvent.emit({ eventValue: value }, this.context);\n\n return { response: value };\n }\n\n override initialize() {\n this.state.myFancyValue = -1; // Always initialize with -1\n }\n}\n\n/**\n * Create Device instance and add needed Listener\n *\n * Create an instance of the matter device class you want to use.\n * This example uses the OnOffLightDevice or OnOffPluginUnitDevice depending on the value of the type parameter.\n * To execute the on/off scripts defined as parameters a listener for the onOff attribute is registered via the\n * device specific API.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled device internally\n * like identify that can be implemented with the logic when these commands are called.\n */\n\n// Devices are compositions of behaviors like OnOffServer above. To extend an existing device you use builder methods.\n//\n// In this case we are using with() to install our On/Off cluster behavior.\n// .with(\"Lighting\") not needed because we always have it in by default because we have default implementation\nconst OnOffDevice = isSocket\n ? vendorId === 0xfff4\n ? OnOffPlugInUnitDevice.with(OnOffShellExecServer, MyFancyOwnFunctionalityServer)\n : OnOffPlugInUnitDevice.with(OnOffShellExecServer)\n : vendorId === 0xfff4\n ? OnOffLightDevice.with(OnOffShellExecServer, MyFancyOwnFunctionalityServer)\n : OnOffLightDevice.with(OnOffShellExecServer);\n\n/**\n * Modify automatically added clusters of the Root endpoint if needed\n * In this example we change the networkCommissioning cluster into one for \"Wifi only\" devices when BLE is used\n * for commissioning, to demonstrate how to do this.\n * If you want to implement Ethernet only devices that get connected to the network via LAN/Ethernet cable,\n * then all this is not needed.\n * The same as shown here for Wi-Fi is also possible theoretical for Thread only or combined devices.\n */\n\n// We use the Basic Root Endpoint without a NetworkCommissioning cluster\nlet RootEndpoint = ServerNode.RootEndpoint.with(TestGeneralDiagnosticsServer);\n\nlet wifiOrThreadAdded = false;\nlet threadAdded = false;\nif (Ble.enabled) {\n // matter.js will create a Ethernet-only device by default when ut comes to Network Commissioning Features.\n // To offer e.g. a \"Wi-Fi only device\" (or any other combination) we need to override the Network Commissioning\n // cluster and implement all the need handling here. This is a \"static implementation\" for pure demonstration\n // purposes and just \"simulates\" the actions to be done. In a real world implementation this would be done by\n // the device implementor based on the relevant networking stack.\n // The NetworkCommissioningCluster and all logics are described in Matter Core Specifications section 11.8\n if (environment.vars.has(\"ble.wifi.fake\")) {\n RootEndpoint = RootEndpoint.with(DummyWifiNetworkCommissioningServer);\n wifiOrThreadAdded = true;\n } else if (environment.vars.has(\"ble.thread.fake\")) {\n RootEndpoint = RootEndpoint.with(DummyThreadNetworkCommissioningServer);\n wifiOrThreadAdded = true;\n threadAdded = true;\n }\n} else {\n RootEndpoint = RootEndpoint.with(\n NetworkCommissioningServer.with(NetworkCommissioning.Feature.EthernetNetworkInterface),\n );\n}\n\nconst networkId = new Uint8Array(32);\n// Physical devices appear as \"nodes\" on a Matter network. As a device implementer you use a NodeServer to bring a\n// device online.\n//\n// Note there are a large number of options to NodeServer that we are allowing to take default values here. See\n// CompositeWindowCovering.ts for a more detailed example.\nconst server = await ServerNode.create(RootEndpoint, {\n id: uniqueId,\n network: {\n port,\n discoveryCapabilities: {\n onIpNetwork: !environment.vars.has(\"ble.enable\"),\n ble: environment.vars.has(\"ble.enable\"),\n },\n ble: environment.vars.has(\"ble.enable\"), // TODO remove when state init is fixed\n },\n commissioning: {\n passcode,\n discriminator,\n },\n productDescription: {\n name: deviceName,\n deviceType: DeviceTypeId(OnOffDevice.deviceType),\n },\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `node-matter-${uniqueId}`,\n uniqueId,\n },\n\n // @ts-expect-error ... TS do not see the types because both next clusters was added conditionally\n networkCommissioning: {\n maxNetworks: 1,\n interfaceEnabled: true,\n lastConnectErrorValue: 0,\n lastNetworkId: wifiOrThreadAdded ? null : networkId,\n lastNetworkingStatus: wifiOrThreadAdded ? null : NetworkCommissioning.NetworkCommissioningStatus.Success,\n networks: [{ networkId: networkId, connected: !wifiOrThreadAdded }],\n scanMaxTimeSeconds: wifiOrThreadAdded ? 3 : undefined,\n connectMaxTimeSeconds: wifiOrThreadAdded ? 3 : undefined,\n supportedWifiBands: wifiOrThreadAdded && !threadAdded ? [NetworkCommissioning.WiFiBand[\"2G4\"]] : undefined,\n supportedThreadFeatures: wifiOrThreadAdded && threadAdded ? { isFullThreadDevice: true } : undefined,\n threadVersion: wifiOrThreadAdded && threadAdded ? 4 : undefined, // means: Thread 1.3\n },\n myFancyFunctionality: {\n myFancyValue: 0,\n },\n});\n\n// Nodes are a composition of endpoints. Add a single endpoint to the node, our example light device.\nconst endpoint = new Endpoint(OnOffDevice, { id: \"onoff\" });\nawait server.add(endpoint);\n\n/**\n * This event is triggered when the device is initially commissioned successfully.\n * This means: It is added to the first fabric.\n */\nserver.lifecycle.commissioned.on(() => console.log(\"Server was initially commissioned successfully!\"));\n\n/** This event is triggered when all fabrics are removed from the device, usually it also does a factory reset then. */\nserver.lifecycle.decommissioned.on(() => console.log(\"Server was fully decommissioned successfully!\"));\n\n/** This event is triggered when the device went online. This means that it is discoverable in the network. */\nserver.lifecycle.online.on(() => console.log(\"Server is online\"));\n\n/** This event is triggered when the device went offline. it is not longer discoverable or connectable in the network. */\nserver.lifecycle.offline.on(() => console.log(\"Server is offline\"));\n\n/**\n * This event is triggered when a fabric is added, removed or updated on the device. Use this if more granular\n * information is needed.\n */\nserver.events.commissioning.fabricsChanged.on((fabricIndex, fabricAction) => {\n let action = \"\";\n switch (fabricAction) {\n case FabricAction.Added:\n action = \"added\";\n break;\n case FabricAction.Removed:\n action = \"removed\";\n break;\n case FabricAction.Updated:\n action = \"updated\";\n break;\n }\n console.log(`Commissioned Fabrics changed event (${action}) for ${fabricIndex} triggered`);\n console.log(server.state.commissioning.fabrics[fabricIndex]);\n});\n\n/**\n * This event is triggered when an operative new session was opened by a Controller.\n * It is not triggered for the initial commissioning process, just afterwards for real connections.\n */\nserver.events.sessions.opened.on(session => console.log(`Session opened`, session));\n\n/**\n * This event is triggered when an operative session is closed by a Controller or because the Device goes offline.\n */\nserver.events.sessions.closed.on(session => console.log(`Session closed`, session));\n\n/** This event is triggered when a subscription gets added or removed on an operative session. */\nserver.events.sessions.subscriptionsChanged.on(session => {\n console.log(`Session subscriptions changed`, session);\n console.log(`Status of all sessions`, server.state.sessions.sessions);\n});\n\n// React on a change of identificationTime to do Identify stuff for the own device\nendpoint.events.identify.startIdentifying.on(() => {\n console.log(`Run identify logic, ideally blink a light every 0.5s ...`);\n});\n\nendpoint.events.identify.stopIdentifying.on(() => {\n console.log(`Stop identify logic ...`);\n});\n\n// Our device is now built and we can bring the node online.\n//\n// Note that you may serve multiple nodes from a single process. We only have one, however, so we can use the run()\n// method of the node.\n\nlogEndpoint(EndpointServer.forEndpoint(server));\n\n/**\n * In order to start the node and announce it into the network we start the node. This method resolves when the Matter\n * node enters his online state. Alternatively, we could also use `await server.run()` which\n * resolves when the node goes offline again, but we want to execute code afterwards, so we use start() here\n */\nawait server.start();\n\nconsole.log(\"Initial Fabrics\", server.state.operationalCredentials.fabrics);\n\n/**\n * If the node is not commissioned already we display the QR code on console. The QR code is also logged\n */\nif (!server.lifecycle.isCommissioned) {\n const { qrPairingCode, manualPairingCode } = server.state.commissioning.pairingCodes;\n\n console.log(QrCode.get(qrPairingCode));\n console.log(`QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`);\n console.log(`Manual pairing code: ${manualPairingCode}`);\n} else {\n console.log(\"Device is already commissioned. Waiting for controllers to connect ...\");\n\n /**\n * Sometimes reading or writing attributes is required. The following code shows how this works.\n * For read it is basically `endpoint.state.clustername.attributename`.\n * The set method allows to set one or multiple values via the structure of also clustername.attributename. When multiple values are set they are considered being one transaction which would be rolled back completely if one value fails to be set.\n */\n\n // Read onOff attribute from onOff cluster\n const onOffValue = endpoint.state.onOff.onOff;\n console.log(`current OnOff attribute: ${onOffValue}`);\n\n if (vendorId === 0xfff4) {\n // Set onOff attribute from OnOff cluster AND the myFancyValue of the MyFancyOwnFunctionality cluster together\n await endpoint.set({\n onOff: {\n onOff: !onOffValue,\n },\n // @ts-expect-error Needed because the Fancy cluster is added conditionally, so TS do not get that it's there.\n myFancyOwnFunctionality: {\n myFancyValue: 36,\n },\n });\n } else {\n // Set onOff attribute from OnOff cluster only\n await endpoint.set({\n onOff: {\n onOff: !onOffValue,\n },\n });\n }\n}\n\n/**\n * To correctly tear down the server we can use server.close().\n */\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n server\n .close()\n .then(() => process.exit(0))\n .catch(err => console.error(err));\n});\n"],
|
5
|
+
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAyBA,SAAS,kBAAkB,6BAA6B;AAExD,SAAS,eAAe;AACxB,SAAS,UAAU,QAAQ,MAAM,oBAAoB,iBAAiB;AACtE,SAAS,kCAAkC;AAC3C,SAAS,mBAAmB;AAC5B,SAAS,WAAW;AACpB,SAA6B,4BAA4B;AACzD,SAAS,cAAc,gBAAgB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AACtC,SAAS,UAAU,sBAAsB;AACzC,SAAS,wBAAwB;AACjC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,cAAc;AACvB,SAAS,gBAAgB;AACzB,SAAS,6CAA6C;AACtD,SAAS,2CAA2C;AACpD;AAAA,EAGI;AAAA,OACG;AASP,sBAAsB,EAAE;AAQxB,MAAM,cAAc,YAAY;AAIhC,IAAI,YAAY,KAAK,IAAI,YAAY,GAAG;AAEpC,MAAI,MAAM;AAAA,IACN,MACI,IAAI,QAAQ;AAAA,MACR,OAAO,YAAY,KAAK,OAAO,WAAW;AAAA,IAC9C,CAAC;AAAA,EACT;AACJ;AAEA,SAAS,eAAe,iBAAyB;AAC7C,QAAM,SAAS,YAAY,KAAK,OAAO,eAAe;AACtD,MAAI,WAAW,OAAW,QAAO;AACjC,UAAQ,IAAI,GAAG,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: Apache-2.0
|
6
6
|
*/
|
7
|
-
import { CommissioningServer, MatterServer } from "@project-chip/matter-node.js";
|
8
|
-
import { BleNode } from "@project-chip/matter-node-ble.js/ble";
|
9
|
-
import { Ble } from "@project-chip/matter-node.js/ble";
|
10
|
-
import { OnOffLightDevice, OnOffPluginUnitDevice, logEndpoint } from "@project-chip/matter-node.js/device";
|
11
|
-
import { Format, Level, Logger } from "@project-chip/matter-node.js/log";
|
12
|
-
import { QrCode } from "@project-chip/matter-node.js/schema";
|
13
|
-
import { StorageBackendDisk, StorageManager } from "@project-chip/matter-node.js/storage";
|
14
|
-
import { Time } from "@project-chip/matter-node.js/time";
|
15
7
|
import {
|
8
|
+
StorageBackendDisk,
|
16
9
|
commandExecutor,
|
17
10
|
getIntParameter,
|
18
11
|
getParameter,
|
19
12
|
hasParameter,
|
20
|
-
requireMinNodeVersion
|
21
|
-
|
22
|
-
} from "@project-chip/matter-node.js/
|
13
|
+
requireMinNodeVersion
|
14
|
+
} from "@project-chip/matter.js-nodejs";
|
15
|
+
import { BleNode } from "@project-chip/matter-node-ble.js/ble";
|
16
|
+
import { CommissioningServer, MatterServer } from "@project-chip/matter.js";
|
17
|
+
import { LogFormat, LogLevel, Logger, StorageManager, Time, singleton } from "@project-chip/matter.js-general";
|
18
|
+
import { Ble } from "@project-chip/matter.js/ble";
|
23
19
|
import { DeviceTypeId, VendorId } from "@project-chip/matter.js/datatype";
|
20
|
+
import { OnOffLightDevice, OnOffPluginUnitDevice, logEndpoint } from "@project-chip/matter.js/device";
|
21
|
+
import { QrCode } from "@project-chip/matter.js/schema";
|
24
22
|
import DummyWifiNetworkCommissioningClusterServer from "./cluster/DummyWifiNetworkCommissioningServerLegacy.js";
|
25
23
|
const logger = Logger.get("Device");
|
26
24
|
requireMinNodeVersion(16);
|
27
25
|
switch (getParameter("loglevel")) {
|
28
26
|
case "fatal":
|
29
|
-
Logger.defaultLogLevel =
|
27
|
+
Logger.defaultLogLevel = LogLevel.FATAL;
|
30
28
|
break;
|
31
29
|
case "error":
|
32
|
-
Logger.defaultLogLevel =
|
30
|
+
Logger.defaultLogLevel = LogLevel.ERROR;
|
33
31
|
break;
|
34
32
|
case "warn":
|
35
|
-
Logger.defaultLogLevel =
|
33
|
+
Logger.defaultLogLevel = LogLevel.WARN;
|
36
34
|
break;
|
37
35
|
case "info":
|
38
|
-
Logger.defaultLogLevel =
|
36
|
+
Logger.defaultLogLevel = LogLevel.INFO;
|
39
37
|
break;
|
40
38
|
}
|
41
39
|
switch (getParameter("logformat")) {
|
42
40
|
case "plain":
|
43
|
-
Logger.format =
|
41
|
+
Logger.format = LogFormat.PLAIN;
|
44
42
|
break;
|
45
43
|
case "html":
|
46
|
-
Logger.format =
|
44
|
+
Logger.format = LogFormat.HTML;
|
47
45
|
break;
|
48
46
|
default:
|
49
|
-
if (process.stdin?.isTTY) Logger.format =
|
47
|
+
if (process.stdin?.isTTY) Logger.format = LogFormat.ANSI;
|
50
48
|
}
|
51
49
|
if (hasParameter("ble")) {
|
52
50
|
Ble.get = singleton(
|