@project-chip/matter-node.js-examples 0.7.5-alpha.0-20240222-8696097f → 0.8.0-alpha.1-20240308-033110a3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (74) hide show
  1. package/README.md +44 -0
  2. package/dist/esm/examples/BridgedDeviceNode.js +147 -0
  3. package/dist/esm/examples/BridgedDeviceNode.js.map +7 -0
  4. package/dist/esm/examples/{BridgedDevicesNode.js → BridgedDevicesNodeLegacy.js} +2 -2
  5. package/dist/esm/examples/BridgedDevicesNodeLegacy.js.map +7 -0
  6. package/dist/esm/examples/ComposedDeviceNode.js +116 -127
  7. package/dist/esm/examples/ComposedDeviceNode.js.map +3 -3
  8. package/dist/esm/examples/ComposedDeviceNodeLegacy.js +138 -0
  9. package/dist/esm/examples/ComposedDeviceNodeLegacy.js.map +7 -0
  10. package/dist/esm/examples/ControllerNode.js +24 -20
  11. package/dist/esm/examples/ControllerNode.js.map +2 -2
  12. package/dist/esm/examples/ControllerNodeLegacy.js +227 -0
  13. package/dist/esm/examples/ControllerNodeLegacy.js.map +7 -0
  14. package/dist/esm/examples/DeviceNode.js +118 -159
  15. package/dist/esm/examples/DeviceNode.js.map +2 -2
  16. package/dist/esm/examples/DeviceNodeFull.js +253 -0
  17. package/dist/esm/examples/DeviceNodeFull.js.map +7 -0
  18. package/dist/esm/examples/DeviceNodeFullLegacy.js +171 -0
  19. package/dist/esm/examples/DeviceNodeFullLegacy.js.map +7 -0
  20. package/dist/esm/examples/IlluminatedRollerShade.js +85 -0
  21. package/dist/esm/examples/IlluminatedRollerShade.js.map +7 -0
  22. package/dist/esm/examples/LightDevice.js +34 -0
  23. package/dist/esm/examples/LightDevice.js.map +7 -0
  24. package/dist/esm/examples/MultiDeviceNode.js +133 -134
  25. package/dist/esm/examples/MultiDeviceNode.js.map +3 -3
  26. package/dist/esm/examples/MultiDeviceNodeLegacy.js +146 -0
  27. package/dist/esm/examples/MultiDeviceNodeLegacy.js.map +7 -0
  28. package/dist/esm/examples/SensorDeviceNode.js +167 -0
  29. package/dist/esm/examples/SensorDeviceNode.js.map +7 -0
  30. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js +115 -0
  31. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js.map +7 -0
  32. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js +115 -0
  33. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js.map +7 -0
  34. package/dist/esm/examples/cluster/{DummyWifiNetworkCommissioningClusterServer.js → DummyWifiNetworkCommissioningServerLegacy.js} +16 -14
  35. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js.map +7 -0
  36. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js +110 -0
  37. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js.map +7 -0
  38. package/dist/esm/tutorial/example01.js +5 -0
  39. package/dist/esm/tutorial/example01.js.map +7 -0
  40. package/dist/esm/tutorial/example02.js +7 -0
  41. package/dist/esm/tutorial/example02.js.map +7 -0
  42. package/dist/esm/tutorial/example03.js +15 -0
  43. package/dist/esm/tutorial/example03.js.map +7 -0
  44. package/dist/esm/tutorial/example04.js +10 -0
  45. package/dist/esm/tutorial/example04.js.map +7 -0
  46. package/dist/esm/tutorial/example05.js +14 -0
  47. package/dist/esm/tutorial/example05.js.map +7 -0
  48. package/package.json +9 -6
  49. package/src/examples/BridgedDeviceNode.ts +260 -0
  50. package/src/examples/{BridgedDevicesNode.ts → BridgedDevicesNodeLegacy.ts} +6 -1
  51. package/src/examples/ComposedDeviceNode.ts +173 -223
  52. package/src/examples/ComposedDeviceNodeLegacy.ts +252 -0
  53. package/src/examples/ControllerNode.ts +28 -22
  54. package/src/examples/ControllerNodeLegacy.ts +354 -0
  55. package/src/examples/DeviceNode.ts +173 -273
  56. package/src/examples/DeviceNodeFull.ts +440 -0
  57. package/src/examples/DeviceNodeFullLegacy.ts +307 -0
  58. package/src/examples/IlluminatedRollerShade.ts +130 -0
  59. package/src/examples/LightDevice.ts +60 -0
  60. package/src/examples/MultiDeviceNode.ts +184 -236
  61. package/src/examples/MultiDeviceNodeLegacy.ts +267 -0
  62. package/src/examples/SensorDeviceNode.ts +236 -0
  63. package/src/examples/cluster/DummyThreadNetworkCommissioningServer.ts +156 -0
  64. package/src/examples/cluster/DummyWifiNetworkCommissioningServer.ts +153 -0
  65. package/src/examples/cluster/{DummyWifiNetworkCommissioningClusterServer.ts → DummyWifiNetworkCommissioningServerLegacy.ts} +16 -13
  66. package/src/examples/cluster/MyFancyOwnFunctionality.ts +185 -0
  67. package/src/tsconfig.json +9 -1
  68. package/src/tutorial/example01.ts +6 -0
  69. package/src/tutorial/example02.ts +9 -0
  70. package/src/tutorial/example03.ts +19 -0
  71. package/src/tutorial/example04.ts +13 -0
  72. package/src/tutorial/example05.ts +19 -0
  73. package/dist/esm/examples/BridgedDevicesNode.js.map +0 -7
  74. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningClusterServer.js.map +0 -7
package/README.md CHANGED
@@ -12,6 +12,50 @@ To better show how to use the library we provide some reference implementations
12
12
 
13
13
  For BLE usage please also see the [matter-node-ble.js README.md](../matter-node-ble.js/README.md) for prerequisites and limitations!
14
14
 
15
+ ## Examples Overview
16
+ The examples provided by this repository show different use cases demonstrating how to build different device types and show various ways to implement and interact with the matter.js structures. This section gives an overview regarding what the different examples demonstrate.
17
+
18
+ ### Legacy Device Examples
19
+ These examples use the matter.js API up to 0.7, which is considered "Legacy" now because it will be replaced by a new API starting with 0.8. The functionality is still working, but should be considered deprecated and will be removed with a later release!
20
+ The filenames of these examples were adjusted in 0.8 and a "Legacy" was added to the end of the filename and "-legacy" to the npm run script name (exception: DeviceNode is now called DeviceNodeFullLegacy). Other than that they are fully compatible with the pre-0.7 versions also regarding storage location and structure and can be directly used as before.
21
+
22
+ All examples create a MatterServer instance to add Matter nodes to be announced on a definable port number (default 5540).
23
+
24
+ * **BridgedDevicesNodeLegacy**: This example shows how to build a Matter-Bridge that offers multiple OnOff lights and/or sockets as a bridge. It can be configured via command line and allows for the specification of shell commands that will be executed for on and off commands on the numbered devices. For more details, see below.
25
+ * **ComposedDeviceNodeLegacy**: This example shows how to build a "simple" composed device where multiple OnOff lights and sockets are combined as one composed device. The devices are all added on the root level, so no bridge is used. The composed device can be configured via command line and allows for the specification of shell commands that will be executed for on and off commands, on the numbered devices. For more details, see below.
26
+ * **DeviceNodeFullLegacy**: This example shows how to build a simple Device node with just one socket or light endpoint. The shell commands to be executed by on/off commands can be configured via CLI. Additionally, this example also shows how to enable BLE for a device node and tweaks the announcement so that only BLE is announced in the beginning. This example also includes a dummy WifiNetworkCommissioning implementation that simulates Wi-Fi logic for the commissioner. Furthermore it also shows how to handle testEventTrigger calls on the GeneralDiagnostics cluster which might be needed for official device testing cases. It also implements the callbacks where implementers can get information on commissioning changes and session/connection changes to better know the status of the node.
27
+ * **MultiDeviceNodeLegacy**: This example shows how to start multiple Matter nodes on one MatterServer where each node is run on its own Port, but share a single MDNS broadcaster and scanner in order to optimize resources. Each node can be configured via CLI to be an onoff socket or a light. CLI. Options also allow specification of shell commands to be executed for on and off commands.
28
+
29
+ ## New API Device Examples
30
+ Some command line parameters, for example those used to set the level of logging or the MDNS interface are now included in the new environment processing. These can be set by generic command line arguments or by using environment variables. These parameters are processed automatically so are no longer handled by the new example code directly. These are:
31
+
32
+ * `--log-level=...` or environment variable `MATTER_LOG_LEVEL` or in code `environment.vars.set('log.level', Level.DEBUG)`. Allowed values are: Level.FATAL ("fatal"), Level.ERROR ("error"), Level.WARN ("warn"), Level.NOTICE ("notice"), Level.INFO ("info"), Level.DEBUG ("debug")
33
+ * `--log-format=...` or environment variable `MATTER_LOG_FORMAT` or `environment.vars.set('log.format', Format.PLAIN)`. Allowed values are: Format.PLAIN ("plain"), Format.HTML ("html"), Format.ANSI ("ansi")
34
+ * `--storage-path=...` or environment variable `MATTER_STORAGE_PATH` or `environment.vars.set('storage.path', "...")` allows to set the storage location. By default, it will be stored in the users home directory in `.matter/...`. If specified, the given path will be used relative to the current working directory.
35
+ * `--storage-clear` or environment variable `MATTER_STORAGE_CLEAR=1` or `environment.vars.set('storage.clear', true)` allows to define if the storage is reset on startup.
36
+ * `--mdns-networkinterface=...` or environment variable `MATTER_MDNS_NETWORKINTERFACE` or `environment.vars.set('mdns.networkInterface', "...")` allows to limit the DNS announcements and scanning to one network interface. By default, all available interfaces are used.
37
+ Additionally, all command line parameters now require to start with two dashes!
38
+
39
+ * **BridgedDevicesNode**: This example shows how to build a Matter-Bridge that offers multiple OnOff lights and sockets as a bridge. It can be configured via command line and allows for specifications of shell commands to be executed when on and off commands are received at the numbered devices. For more details see below.
40
+ * **ComposedDeviceNode**: This example shows how to build a "simple" composed device where multiple OnOff lights and sockets are combined as a single device. The devices are all added at the root level, so no bridge is used. It can be configured via command line and allows for specifications of shell commands to be executed when on and off commands are received at the numbered devices. For more details see below.
41
+ * **DeviceNode**: This example shows how to build a simple minimalistic DeviceNode with just one socket or light endpoint. The shell commands to be executed by on/off commands can be configured via CLI.
42
+ * **DeviceNodeFull**: This example shows how to build a simple Device node with just one socket or light endpoint. The shell commands to be executed by on/off commands can be configured via CLI. Additionally, this example also shows the following use cases:
43
+ * it shows how to enable BLE for a device node and tweaks the announcement so that BLE is only announced in the beginning.
44
+ * it includes a dummy WifiNetworkCommissioning and a dummy ThreadNetworkCommissioning implementation that simulates Wi-Fi/Thread logic for the commissioner and logs the Wi-Fi/Thread credentials the commissioner sends to the device.
45
+ * it enhances the GeneralDiagnostics and OnOff cluster to implement some commands with its own logic.
46
+ * it defines the ["My Fancy Functionality" custom cluster](./src/examples/cluster/MyFancyOwnFunctionality.ts) and adds this to the OnOff endpoint as additional cluster when the chosen vendorId is set to 0xfff4 (65524)
47
+ * it implements the callbacks where developers can get information on commissioning changes and session/connection changes to better know the status of the node.
48
+ * **MultiDeviceNode**: This example shows how to start multiple Matter nodes on one MatterServer where each node is run on its own Port, but share a single MDNS broadcaster and scanner in order to optimize resources. Each node can be configured via CLI to be an onoff socket or a light. CLI. Options also allow specification of shell commands to be executed for on and off commands.
49
+ * * **SensorDeviceNode**: This example shows how to build a simple Sensor device with a temperature (default) or humidity (`--type humidity`) sensor. The sensor values are updated by default every 60 seconds, or the number of seconds specified via the CLI parameter `--interval`. The value can be defined by the output of a CLI script provided via parameter `--value` or, if no command is specified, are randomly set in the interval -50..+50. To read the Temperature of a Raspberry Pi as example use `--value ="echo \$((\$(</sys/class/thermal/thermal_zone0/temp)/10))"` or to read temperature of your location `--value="curl -s 'wttr.in/?format=%t\&m' | sed 's/°C//'| awk '{print \$1*100}'"` (or use `?format=%h` for humidity).
50
+
51
+ Additionally, these two examples are not directly configurable by CLI and mainly show how to implement different combinations of devices:
52
+ * **IlluminatedRollerShade**: This example implements the Window Covering cluster server logic and also overrides a OnOff cluster server to build a composed devices with a window covering nd a light.
53
+ * **LightDevice**: This example shows how to run a Light device which is not configurable via CLI and only logs changes, so it is the most minimalistic example. It shows how to enhance the OnOff cluster server with own logic.
54
+
55
+ ## Controller example
56
+ * **ControllerNode**: This example shows basically how a controller could be implemented by showing pairing and connections to a paired device. When there is an OnOff Endpoint with ID 1 then this is controlled and toggled.
57
+
58
+
15
59
  ## Installation
16
60
 
17
61
  ### From NPM
@@ -0,0 +1,147 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2022-2024 Matter.js Authors
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import "@project-chip/matter-node.js";
7
+ import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
8
+ import { BridgedDeviceBasicInformationServer } from "@project-chip/matter.js/behavior/definitions/bridged-device-basic-information";
9
+ import { DeviceTypeId, VendorId } from "@project-chip/matter.js/datatype";
10
+ import { logEndpoint } from "@project-chip/matter.js/device";
11
+ import { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
12
+ import { OnOffPlugInUnitDevice } from "@project-chip/matter.js/devices/OnOffPlugInUnitDevice";
13
+ import { Endpoint, EndpointServer } from "@project-chip/matter.js/endpoint";
14
+ import { AggregatorEndpoint } from "@project-chip/matter.js/endpoint/definitions";
15
+ import { Environment, StorageService } from "@project-chip/matter.js/environment";
16
+ import { ServerNode } from "@project-chip/matter.js/node";
17
+ import { Time } from "@project-chip/matter.js/time";
18
+ import { execSync } from "child_process";
19
+ requireMinNodeVersion(16);
20
+ const { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } = await getConfiguration();
21
+ const server = await ServerNode.create({
22
+ // Required: Give the Node a unique ID which is used to store the state of this node
23
+ id: uniqueId,
24
+ // Provide Network relevant configuration like the port
25
+ // Optional when operating only one device on a host, Default port is 5540
26
+ network: {
27
+ port
28
+ },
29
+ // Provide Commissioning relevant settings
30
+ // Optional for development/testing purposes
31
+ commissioning: {
32
+ passcode,
33
+ discriminator
34
+ },
35
+ // Provide Node announcement settings
36
+ // Optional: If Ommitted some development defaults are used
37
+ productDescription: {
38
+ name: deviceName,
39
+ deviceType: DeviceTypeId(isSocket[0] ? OnOffPlugInUnitDevice.deviceType : OnOffLightDevice.deviceType)
40
+ },
41
+ // Provide defaults for the BasicInformation cluster on the Root endpoint
42
+ // Optional: If Omitted some development defaults are used
43
+ basicInformation: {
44
+ vendorName,
45
+ vendorId: VendorId(vendorId),
46
+ nodeLabel: productName,
47
+ productName,
48
+ productLabel: productName,
49
+ productId,
50
+ serialNumber: `matterjs-${uniqueId}`,
51
+ uniqueId
52
+ }
53
+ });
54
+ const aggregator = new Endpoint(AggregatorEndpoint, { id: "aggregator" });
55
+ await server.add(aggregator);
56
+ for (let idx = 0; idx < isSocket.length; idx++) {
57
+ const i = idx + 1;
58
+ const isASocket = isSocket[idx];
59
+ const name = `OnOff ${isASocket ? "Socket" : "Light"} ${i}`;
60
+ const endpoint = new Endpoint(
61
+ isASocket ? (
62
+ // For a Bridged Device we need to add a BridgedDeviceBasicInformation cluster as server
63
+ OnOffPlugInUnitDevice.with(BridgedDeviceBasicInformationServer)
64
+ ) : OnOffLightDevice.with(BridgedDeviceBasicInformationServer),
65
+ {
66
+ id: `onoff-${i}`,
67
+ bridgedDeviceBasicInformation: {
68
+ nodeLabel: name,
69
+ productName: name,
70
+ productLabel: name,
71
+ serialNumber: `node-matter-${uniqueId}-${i}`,
72
+ reachable: true
73
+ }
74
+ }
75
+ );
76
+ await aggregator.add(endpoint);
77
+ let isIdentifying = false;
78
+ endpoint.events.identify.identifyTime$Change.on((value) => {
79
+ if (value > 0 && !isIdentifying) {
80
+ isIdentifying = true;
81
+ console.log(`${name}: Run identify logic, ideally blink a light every 0.5s ...`);
82
+ } else if (value === 0) {
83
+ isIdentifying = false;
84
+ console.log(`${name}: Stop identify logic ...`);
85
+ }
86
+ });
87
+ endpoint.events.onOff.onOff$Change.on((value) => {
88
+ executeCommand(value ? `on${i}` : `off${i}`);
89
+ console.log(`${name} is now ${value ? "ON" : "OFF"}`);
90
+ });
91
+ }
92
+ await server.bringOnline();
93
+ logEndpoint(EndpointServer.forEndpoint(server));
94
+ function executeCommand(scriptParamName) {
95
+ const script = Environment.default.vars.string(scriptParamName);
96
+ if (script === void 0)
97
+ return void 0;
98
+ console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
99
+ }
100
+ async function getConfiguration() {
101
+ const environment = Environment.default;
102
+ const storageService = environment.get(StorageService);
103
+ console.log(`Storage location: ${storageService.location} (Directory)`);
104
+ console.log(
105
+ '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.'
106
+ );
107
+ const deviceStorage = (await storageService.open("device")).createContext("data");
108
+ const isSocket2 = Array();
109
+ const numDevices = environment.vars.number("num") || 2;
110
+ if (deviceStorage.has("isSocket")) {
111
+ console.log(`Device types found in storage. --type parameter is ignored.`);
112
+ deviceStorage.get("isSocket").forEach((type) => isSocket2.push(type));
113
+ }
114
+ for (let i = 1; i <= numDevices; i++) {
115
+ if (isSocket2[i - 1] !== void 0)
116
+ continue;
117
+ isSocket2.push(environment.vars.string(`type${i}`) === "socket");
118
+ }
119
+ const deviceName2 = "Matter test device";
120
+ const vendorName2 = "matter-node.js";
121
+ const passcode2 = environment.vars.number("passcode") ?? deviceStorage.get("passcode", 20202021);
122
+ const discriminator2 = environment.vars.number("discriminator") ?? deviceStorage.get("discriminator", 3840);
123
+ const vendorId2 = environment.vars.number("vendorid") ?? deviceStorage.get("vendorid", 65521);
124
+ const productName2 = `node-matter OnOff ${isSocket2 ? "Socket" : "Light"}`;
125
+ const productId2 = environment.vars.number("productid") ?? deviceStorage.get("productid", 32768);
126
+ const port2 = environment.vars.number("port") ?? 5540;
127
+ const uniqueId2 = environment.vars.string("uniqueid") ?? deviceStorage.get("uniqueid", Time.nowMs().toString());
128
+ deviceStorage.set("passcode", passcode2);
129
+ deviceStorage.set("discriminator", discriminator2);
130
+ deviceStorage.set("vendorid", vendorId2);
131
+ deviceStorage.set("productid", productId2);
132
+ deviceStorage.set("isSocket", isSocket2);
133
+ deviceStorage.set("uniqueid", uniqueId2);
134
+ return {
135
+ isSocket: isSocket2,
136
+ deviceName: deviceName2,
137
+ vendorName: vendorName2,
138
+ passcode: passcode2,
139
+ discriminator: discriminator2,
140
+ vendorId: vendorId2,
141
+ productName: productName2,
142
+ productId: productId2,
143
+ port: port2,
144
+ uniqueId: uniqueId2
145
+ };
146
+ }
147
+ //# sourceMappingURL=BridgedDeviceNode.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/examples/BridgedDeviceNode.ts"],
4
+ "sourcesContent": ["/**\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 new device node that is composed of multiple devices.\n * It creates multiple endpoints on the server. For information on how to add a composed device to a bridge please\n * refer to the bridge example!\n * It can be used as CLI script and starting point for your own device node implementation.\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 { requireMinNodeVersion } from \"@project-chip/matter-node.js/util\";\nimport { BridgedDeviceBasicInformationServer } from \"@project-chip/matter.js/behavior/definitions/bridged-device-basic-information\";\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 { AggregatorEndpoint } from \"@project-chip/matter.js/endpoint/definitions\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\nimport { Time } from \"@project-chip/matter.js/time\";\nimport { execSync } from \"child_process\";\n\nrequireMinNodeVersion(16);\n\n/** Initialize configuration values */\nconst { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } =\n await getConfiguration();\n\n/**\n * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration\n */\nconst 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[0] ? 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 multiple endpoint to the node to make it a\n * composed device. This example uses the OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type\n * parameter. It also assigns each Endpoint a unique ID to store the endpoint number for it in the storage to restore\n * the device on restart.\n *\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\nconst aggregator = new Endpoint(AggregatorEndpoint, { id: \"aggregator\" });\nawait server.add(aggregator);\n\nfor (let idx = 0; idx < isSocket.length; idx++) {\n const i = idx + 1;\n const isASocket = isSocket[idx]; // Is the Device we add a Socket or a Light?\n\n const name = `OnOff ${isASocket ? \"Socket\" : \"Light\"} ${i}`;\n\n const endpoint = new Endpoint(\n isASocket\n ? // For a Bridged Device we need to add a BridgedDeviceBasicInformation cluster as server\n OnOffPlugInUnitDevice.with(BridgedDeviceBasicInformationServer)\n : OnOffLightDevice.with(BridgedDeviceBasicInformationServer),\n {\n id: `onoff-${i}`,\n bridgedDeviceBasicInformation: {\n nodeLabel: name,\n productName: name,\n productLabel: name,\n serialNumber: `node-matter-${uniqueId}-${i}`,\n reachable: true,\n },\n },\n );\n await aggregator.add(endpoint);\n\n /**\n * Register state change handlers of the endpoint for identify and onoff states to react to the commands.\n *\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 let isIdentifying = false;\n endpoint.events.identify.identifyTime$Change.on(value => {\n // identifyTime is set when an identify commandf is called and then decreased every second while indenitfy logic runs.\n if (value > 0 && !isIdentifying) {\n isIdentifying = true;\n console.log(`${name}: Run identify logic, ideally blink a light every 0.5s ...`);\n } else if (value === 0) {\n isIdentifying = false;\n console.log(`${name}: Stop identify logic ...`);\n }\n });\n\n endpoint.events.onOff.onOff$Change.on(value => {\n executeCommand(value ? `on${i}` : `off${i}`);\n console.log(`${name} is now ${value ? \"ON\" : \"OFF\"}`);\n });\n}\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 */\nawait server.bringOnline();\n\n/**\n * Log the endpoint structure for debugging reasons and to allow to verify anything is correct\n */\nlogEndpoint(EndpointServer.forEndpoint(server));\n\n/*\n If you want to dynamically add another device during runtime you can do so by doing the following:\n\n const name = `OnOff Light 3`;\n\n const endpoint = new Endpoint(OnOffLightDevice.with(BridgedDeviceBasicInformationServer), {\n id: `onoff-3`,\n bridgedDeviceBasicInformation: {\n nodeLabel: name,\n productName: name,\n productLabel: name,\n serialNumber: `node-matter-${uniqueId}-3`,\n reachable: true,\n },\n });\n await aggregator.add(endpoint);\n\n endpoint.events.onOff.onOff$Change.on(value => {\n executeCommand(value ? `on3` : `off3`);\n console.log(`${name} is now ${value ? \"ON\" : \"OFF\"}`);\n });\n\n */\n\n/*\n To remove a device during runtime you can do so by doing the following:\n console.log(\"Removing Light 3 now!!\");\n\n await endpoint.close();\n\n This will automatically remove the endpoint from the bridge.\n */\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 = Array<boolean>();\n const numDevices = environment.vars.number(\"num\") || 2;\n if (deviceStorage.has(\"isSocket\")) {\n console.log(`Device types found in storage. --type parameter is ignored.`);\n deviceStorage.get<Array<boolean>>(\"isSocket\").forEach(type => isSocket.push(type));\n }\n for (let i = 1; i <= numDevices; i++) {\n if (isSocket[i - 1] !== undefined) continue;\n isSocket.push(environment.vars.string(`type${i}`) === \"socket\");\n }\n\n const deviceName = \"Matter test device\";\n const vendorName = \"matter-node.js\";\n const passcode = environment.vars.number(\"passcode\") ?? deviceStorage.get(\"passcode\", 20202021);\n const discriminator = environment.vars.number(\"discriminator\") ?? 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\") ?? deviceStorage.get(\"vendorid\", 0xfff1);\n const productName = `node-matter OnOff ${isSocket ? \"Socket\" : \"Light\"}`;\n const productId = environment.vars.number(\"productid\") ?? deviceStorage.get(\"productid\", 0x8000);\n\n const port = environment.vars.number(\"port\") ?? 5540;\n\n const uniqueId = environment.vars.string(\"uniqueid\") ?? deviceStorage.get(\"uniqueid\", Time.nowMs().toString());\n\n // Persist basic data to keep them also on restart\n deviceStorage.set(\"passcode\", passcode);\n deviceStorage.set(\"discriminator\", discriminator);\n deviceStorage.set(\"vendorid\", vendorId);\n deviceStorage.set(\"productid\", productId);\n deviceStorage.set(\"isSocket\", isSocket);\n deviceStorage.set(\"uniqueid\", uniqueId);\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": "AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,OAAO;AAEP,SAAS,6BAA6B;AACtC,SAAS,2CAA2C;AACpD,SAAS,cAAc,gBAAgB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AACtC,SAAS,UAAU,sBAAsB;AACzC,SAAS,0BAA0B;AACnC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AACrB,SAAS,gBAAgB;AAEzB,sBAAs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QAAIA,UAAS,IAAI,CAAC,MAAM;AAAW;AACnC,IAAAA,UAAS,KAAK,YAAY,KAAK,OAAO,OAAO,CAAC,EAAE,MAAM,QAAQ;AAAA,EAClE;AAEA,QAAMC,cAAa;AACnB,QAAMC,cAAa;AACnB,QAAMC,YAAW,YAAY,KAAK,OAAO,UAAU,KAAK,cAAc,IAAI,YAAY,QAAQ;AAC9F,QAAMC,iBAAgB,YAAY,KAAK,OAAO,eAAe,KAAK,cAAc,IAAI,iBAAiB,IAAI;AAEzG,QAAMC,YAAW,YAAY,KAAK,OAAO,UAAU,KAAK,cAAc,IAAI,YAAY,KAAM;AAC5F,QAAMC,eAAc,qBAAqBN,YAAW,WAAW,OAAO;AACtE,QAAMO,aAAY,YAAY,KAAK,OAAO,WAAW,KAAK,cAAc,IAAI,aAAa,KAAM;AAE/F,QAAMC,QAAO,YAAY,KAAK,OAAO,MAAM,KAAK;AAEhD,QAAMC,YAAW,YAAY,KAAK,OAAO,UAAU,KAAK,cAAc,IAAI,YAAY,KAAK,MAAM,EAAE,SAAS,CAAC;AAG7G,gBAAc,IAAI,YAAYN,SAAQ;AACtC,gBAAc,IAAI,iBAAiBC,cAAa;AAChD,gBAAc,IAAI,YAAYC,SAAQ;AACtC,gBAAc,IAAI,aAAaE,UAAS;AACxC,gBAAc,IAAI,YAAYP,SAAQ;AACtC,gBAAc,IAAI,YAAYS,SAAQ;AAEtC,SAAO;AAAA,IACH,UAAAT;AAAA,IACA,YAAAC;AAAA,IACA,YAAAC;AAAA,IACA,UAAAC;AAAA,IACA,eAAAC;AAAA,IACA,UAAAC;AAAA,IACA,aAAAC;AAAA,IACA,WAAAC;AAAA,IACA,MAAAC;AAAA,IACA,UAAAC;AAAA,EACJ;AACJ;",
6
+ "names": ["isSocket", "deviceName", "vendorName", "passcode", "discriminator", "vendorId", "productName", "productId", "port", "uniqueId"]
7
+ }
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * @license
4
- * Copyright 2022 The node-matter Authors
4
+ * Copyright 2022-2024 Matter.js Authors
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
7
  import { CommissioningServer, MatterServer } from "@project-chip/matter-node.js";
@@ -138,4 +138,4 @@ process.on("SIGINT", () => {
138
138
  storage.close().then(() => process.exit(0)).catch((err) => console.error(err));
139
139
  }).catch((err) => console.error(err));
140
140
  });
141
- //# sourceMappingURL=BridgedDevicesNode.js.map
141
+ //# sourceMappingURL=BridgedDevicesNodeLegacy.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/examples/BridgedDevicesNodeLegacy.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 * IMPORTANT: This example uses a Legacy API which will be deprecated in the future.\n * It is just still here to support developers in converting their code to the new API!\n */\n\n/**\n * This example shows how to create a device bridge that exposed multiple devices.\n * It can be used as CLI script and starting point for your own device node implementation.\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 { CommissioningServer, MatterServer } from \"@project-chip/matter-node.js\";\n\nimport { VendorId } from \"@project-chip/matter-node.js/datatype\";\nimport { Aggregator, DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from \"@project-chip/matter-node.js/device\";\nimport { Format, Level, Logger } from \"@project-chip/matter-node.js/log\";\nimport { QrCode } from \"@project-chip/matter-node.js/schema\";\nimport { StorageBackendDisk, StorageManager } from \"@project-chip/matter-node.js/storage\";\nimport { Time } from \"@project-chip/matter-node.js/time\";\nimport {\n commandExecutor,\n getIntParameter,\n getParameter,\n hasParameter,\n requireMinNodeVersion,\n} from \"@project-chip/matter-node.js/util\";\n\nconst logger = Logger.get(\"Device\");\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\nconst storageLocation = getParameter(\"store\") ?? \".device-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 BridgedDevice {\n private matterServer: MatterServer | undefined;\n\n async start() {\n logger.info(`node-matter`);\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 deviceStorage = storageManager.createContext(\"Device\");\n\n const deviceName = \"Matter Bridge device\";\n const deviceType = DeviceTypes.AGGREGATOR.code;\n const vendorName = \"matter-node.js\";\n const passcode = getIntParameter(\"passcode\") ?? deviceStorage.get(\"passcode\", 20202021);\n const discriminator = getIntParameter(\"discriminator\") ?? deviceStorage.get(\"discriminator\", 3840);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = getIntParameter(\"vendorid\") ?? deviceStorage.get(\"vendorid\", 0xfff1);\n const productName = `node-matter OnOff-Bridge`;\n const productId = getIntParameter(\"productid\") ?? deviceStorage.get(\"productid\", 0x8000);\n\n const netInterface = getParameter(\"netinterface\");\n const port = getIntParameter(\"port\") ?? 5540;\n\n const uniqueId = getIntParameter(\"uniqueid\") ?? deviceStorage.get(\"uniqueid\", Time.nowMs());\n\n deviceStorage.set(\"passcode\", passcode);\n deviceStorage.set(\"discriminator\", discriminator);\n deviceStorage.set(\"vendorid\", vendorId);\n deviceStorage.set(\"productid\", productId);\n deviceStorage.set(\"uniqueid\", uniqueId);\n\n /**\n * Create Matter Server and CommissioningServer Node\n *\n * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a\n * commissioningServer to it and add the just created device instance to it.\n * The CommissioningServer 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 this.matterServer = new MatterServer(storageManager, { mdnsInterface: netInterface });\n\n const commissioningServer = new CommissioningServer({\n port,\n deviceName,\n deviceType,\n passcode,\n discriminator,\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `node-matter-${uniqueId}`,\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 const aggregator = new Aggregator();\n\n const numDevices = getIntParameter(\"num\") || 2;\n for (let i = 1; i <= numDevices; i++) {\n const onOffDevice =\n getParameter(`type${i}`) === \"socket\" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n\n onOffDevice.addOnOffListener(on => commandExecutor(on ? `on${i}` : `off${i}`)?.());\n onOffDevice.addCommandHandler(\"identify\", async ({ request: { identifyTime } }) =>\n console.log(\n `Identify called for OnOffDevice ${onOffDevice.name} with id: ${i} and identifyTime: ${identifyTime}`,\n ),\n );\n\n const name = `OnOff ${onOffDevice instanceof OnOffPluginUnitDevice ? \"Socket\" : \"Light\"} ${i}`;\n aggregator.addBridgedDevice(onOffDevice, {\n nodeLabel: name,\n productName: name,\n productLabel: name,\n serialNumber: `node-matter-${uniqueId}-${i}`,\n reachable: true,\n });\n }\n\n commissioningServer.addDevice(aggregator);\n\n await this.matterServer.addCommissioningServer(commissioningServer);\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 this.matterServer.start();\n\n /**\n * Print Pairing Information\n *\n * If the device is not already commissioned (this info is stored in the storage system) then get and print the\n * pairing details. This includes the QR code that can be scanned by the Matter app to pair the device.\n */\n\n logger.info(\"Listening\");\n if (!commissioningServer.isCommissioned()) {\n const pairingData = commissioningServer.getPairingCode();\n const { qrPairingCode, manualPairingCode } = pairingData;\n\n console.log(QrCode.get(qrPairingCode));\n console.log(\n `QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`,\n );\n console.log(`Manual pairing code: ${manualPairingCode}`);\n } else {\n console.log(\"Device is already commissioned. Waiting for controllers to connect ...\");\n }\n }\n\n async stop() {\n await this.matterServer?.close();\n }\n}\n\nconst device = new BridgedDevice();\ndevice\n .start()\n .then(() => {\n /* done */\n })\n .catch(err => console.error(err));\n\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n device\n .stop()\n .then(() => {\n // Pragmatic way to make sure the storage is correctly closed before the process ends.\n storage\n .close()\n .then(() => process.exit(0))\n .catch(err => console.error(err));\n })\n .catch(err => console.error(err));\n});\n"],
5
+ "mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAoBA,SAAS,qBAAqB,oBAAoB;AAElD,SAAS,gBAAgB;AACzB,SAAS,YAAY,aAAa,kBAAkB,6BAA6B;A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BAAuB,wBAAwB,WAAW,OAAO,IAAI,CAAC;AAC5F,iBAAW,iBAAiB,aAAa;AAAA,QACrC,WAAW;AAAA,QACX,aAAa;AAAA,QACb,cAAc;AAAA,QACd,cAAc,eAAe,QAAQ,IAAI,CAAC;AAAA,QAC1C,WAAW;AAAA,MACf,CAAC;AAAA,IACL;AAEA,wBAAoB,UAAU,UAAU;AAExC,UAAM,KAAK,aAAa,uBAAuB,mBAAmB;AASlE,UAAM,KAAK,aAAa,MAAM;AAS9B,WAAO,KAAK,WAAW;AACvB,QAAI,CAAC,oBAAoB,eAAe,GAAG;AACvC,YAAM,cAAc,oBAAoB,eAAe;AACvD,YAAM,EAAE,eAAe,kBAAkB,IAAI;AAE7C,cAAQ,IAAI,OAAO,IAAI,aAAa,CAAC;AACrC,cAAQ;AAAA,QACJ,gFAAgF,aAAa;AAAA,MACjG;AACA,cAAQ,IAAI,wBAAwB,iBAAiB,EAAE;AAAA,IAC3D,OAAO;AACH,cAAQ,IAAI,wEAAwE;AAAA,IACxF;AAAA,EACJ;AAAA,EAEA,MAAM,OAAO;AACT,UAAM,KAAK,cAAc,MAAM;AAAA,EACnC;AACJ;AAEA,MAAM,SAAS,IAAI,cAAc;AACjC,OACK,MAAM,EACN,KAAK,MAAM;AAEZ,CAAC,EACA,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AAEpC,QAAQ,GAAG,UAAU,MAAM;AAEvB,SACK,KAAK,EACL,KAAK,MAAM;AAER,YACK,MAAM,EACN,KAAK,MAAM,QAAQ,KAAK,CAAC,CAAC,EAC1B,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AAAA,EACxC,CAAC,EACA,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AACxC,CAAC;",
6
+ "names": []
7
+ }
@@ -1,138 +1,127 @@
1
- #!/usr/bin/env node
2
1
  /**
3
2
  * @license
4
- * Copyright 2022 The node-matter Authors
3
+ * Copyright 2022-2024 Matter.js Authors
5
4
  * SPDX-License-Identifier: Apache-2.0
6
5
  */
7
- import { CommissioningServer, MatterServer } from "@project-chip/matter-node.js";
8
- import { VendorId } from "@project-chip/matter-node.js/datatype";
9
- import { DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from "@project-chip/matter-node.js/device";
10
- import { Format, Level, Logger } from "@project-chip/matter-node.js/log";
11
- import { QrCode } from "@project-chip/matter-node.js/schema";
12
- import { StorageBackendDisk, StorageManager } from "@project-chip/matter-node.js/storage";
13
- import { Time } from "@project-chip/matter-node.js/time";
14
- import {
15
- commandExecutor,
16
- getIntParameter,
17
- getParameter,
18
- hasParameter,
19
- requireMinNodeVersion
20
- } from "@project-chip/matter-node.js/util";
21
- const logger = Logger.get("Device");
6
+ import "@project-chip/matter-node.js";
7
+ import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
8
+ import { DeviceTypeId, VendorId } from "@project-chip/matter.js/datatype";
9
+ import { logEndpoint } from "@project-chip/matter.js/device";
10
+ import { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
11
+ import { OnOffPlugInUnitDevice } from "@project-chip/matter.js/devices/OnOffPlugInUnitDevice";
12
+ import { Endpoint, EndpointServer } from "@project-chip/matter.js/endpoint";
13
+ import { Environment, StorageService } from "@project-chip/matter.js/environment";
14
+ import { ServerNode } from "@project-chip/matter.js/node";
15
+ import { Time } from "@project-chip/matter.js/time";
16
+ import { execSync } from "child_process";
22
17
  requireMinNodeVersion(16);
23
- switch (getParameter("loglevel")) {
24
- case "fatal":
25
- Logger.defaultLogLevel = Level.FATAL;
26
- break;
27
- case "error":
28
- Logger.defaultLogLevel = Level.ERROR;
29
- break;
30
- case "warn":
31
- Logger.defaultLogLevel = Level.WARN;
32
- break;
33
- case "info":
34
- Logger.defaultLogLevel = Level.INFO;
35
- break;
18
+ const { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } = await getConfiguration();
19
+ const server = await ServerNode.create({
20
+ // Required: Give the Node a unique ID which is used to store the state of this node
21
+ id: uniqueId,
22
+ // Provide Network relevant configuration like the port
23
+ // Optional when operating only one device on a host, Default port is 5540
24
+ network: {
25
+ port
26
+ },
27
+ // Provide Commissioning relevant settings
28
+ // Optional for development/testing purposes
29
+ commissioning: {
30
+ passcode,
31
+ discriminator
32
+ },
33
+ // Provide Node announcement settings
34
+ // Optional: If Ommitted some development defaults are used
35
+ productDescription: {
36
+ name: deviceName,
37
+ deviceType: DeviceTypeId(isSocket[0] ? OnOffPlugInUnitDevice.deviceType : OnOffLightDevice.deviceType)
38
+ },
39
+ // Provide defaults for the BasicInformation cluster on the Root endpoint
40
+ // Optional: If Omitted some development defaults are used
41
+ basicInformation: {
42
+ vendorName,
43
+ vendorId: VendorId(vendorId),
44
+ nodeLabel: productName,
45
+ productName,
46
+ productLabel: productName,
47
+ productId,
48
+ serialNumber: `matterjs-${uniqueId}`,
49
+ uniqueId
50
+ }
51
+ });
52
+ for (let idx = 0; idx < isSocket.length; idx++) {
53
+ const i = idx + 1;
54
+ const isASocket = isSocket[idx];
55
+ const endpoint = new Endpoint(isASocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: `onoff-${i}` });
56
+ await server.add(endpoint);
57
+ let isIdentifying = false;
58
+ endpoint.events.identify.identifyTime$Change.on((value) => {
59
+ if (value > 0 && !isIdentifying) {
60
+ isIdentifying = true;
61
+ console.log(`OnOff ${i}: Run identify logic, ideally blink a light every 0.5s ...`);
62
+ } else if (value === 0) {
63
+ isIdentifying = false;
64
+ console.log(`OnOff ${i}: Stop identify logic ...`);
65
+ }
66
+ });
67
+ endpoint.events.onOff.onOff$Change.on((value) => {
68
+ executeCommand(value ? `on${i}` : `off${i}`);
69
+ console.log(`OnOff ${i} is now ${value ? "ON" : "OFF"}`);
70
+ });
36
71
  }
37
- switch (getParameter("logformat")) {
38
- case "plain":
39
- Logger.format = Format.PLAIN;
40
- break;
41
- case "html":
42
- Logger.format = Format.HTML;
43
- break;
44
- default:
45
- if (process.stdin?.isTTY)
46
- Logger.format = Format.ANSI;
72
+ logEndpoint(EndpointServer.forEndpoint(server));
73
+ await server.run();
74
+ function executeCommand(scriptParamName) {
75
+ const script = Environment.default.vars.string(scriptParamName);
76
+ if (script === void 0)
77
+ return void 0;
78
+ console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
47
79
  }
48
- const storageLocation = getParameter("store") ?? ".device-node";
49
- const storage = new StorageBackendDisk(storageLocation, hasParameter("clearstorage"));
50
- logger.info(`Storage location: ${storageLocation} (Directory)`);
51
- logger.info(
52
- 'Use the parameter "-store NAME" to specify a different storage location, use -clearstorage to start with an empty storage.'
53
- );
54
- class ComposedDevice {
55
- async start() {
56
- logger.info(`node-matter`);
57
- const storageManager = new StorageManager(storage);
58
- await storageManager.initialize();
59
- const deviceStorage = storageManager.createContext("Device");
60
- if (deviceStorage.has("isSocket")) {
61
- logger.info("Device type found in storage. -type parameter is ignored.");
62
- }
63
- const isSocket = deviceStorage.get("isSocket", getParameter("type") === "socket");
64
- const deviceName = "Matter composed device";
65
- const deviceType = getParameter("type") === "socket" ? DeviceTypes.ON_OFF_PLUGIN_UNIT.code : DeviceTypes.ON_OFF_LIGHT.code;
66
- const vendorName = "matter-node.js";
67
- const passcode = getIntParameter("passcode") ?? deviceStorage.get("passcode", 20202021);
68
- const discriminator = getIntParameter("discriminator") ?? deviceStorage.get("discriminator", 3840);
69
- const vendorId = getIntParameter("vendorid") ?? deviceStorage.get("vendorid", 65521);
70
- const productName = `node-matter OnOff-Bridge`;
71
- const productId = getIntParameter("productid") ?? deviceStorage.get("productid", 32768);
72
- const netInterface = getParameter("netinterface");
73
- const port = getIntParameter("port") ?? 5540;
74
- const uniqueId = getIntParameter("uniqueid") ?? deviceStorage.get("uniqueid", Time.nowMs());
75
- deviceStorage.set("passcode", passcode);
76
- deviceStorage.set("discriminator", discriminator);
77
- deviceStorage.set("vendorid", vendorId);
78
- deviceStorage.set("productid", productId);
79
- deviceStorage.set("isSocket", isSocket);
80
- deviceStorage.set("uniqueid", uniqueId);
81
- this.matterServer = new MatterServer(storageManager, { mdnsInterface: netInterface });
82
- const commissioningServer = new CommissioningServer({
83
- port,
84
- deviceName,
85
- deviceType,
86
- passcode,
87
- discriminator,
88
- basicInformation: {
89
- vendorName,
90
- vendorId: VendorId(vendorId),
91
- nodeLabel: productName,
92
- productName,
93
- productLabel: productName,
94
- productId,
95
- serialNumber: `node-matter-${uniqueId}`
96
- }
97
- });
98
- const numDevices = getIntParameter("num") || 2;
99
- for (let i = 1; i <= numDevices; i++) {
100
- const onOffDevice = getParameter(`type${i}`) === "socket" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();
101
- onOffDevice.addFixedLabel("orientation", getParameter(`orientation${i}`) ?? `orientation ${i}`);
102
- onOffDevice.addOnOffListener((on) => commandExecutor(on ? `on${i}` : `off${i}`)?.());
103
- onOffDevice.addCommandHandler(
104
- "identify",
105
- async ({ request: { identifyTime } }) => console.log(
106
- `Identify called for OnOffDevice ${onOffDevice.name} with id: ${i} and identifyTime: ${identifyTime}`
107
- )
108
- );
109
- commissioningServer.addDevice(onOffDevice);
110
- }
111
- await this.matterServer.addCommissioningServer(commissioningServer);
112
- await this.matterServer.start();
113
- logger.info("Listening");
114
- if (!commissioningServer.isCommissioned()) {
115
- const pairingData = commissioningServer.getPairingCode();
116
- const { qrPairingCode, manualPairingCode } = pairingData;
117
- console.log(QrCode.get(qrPairingCode));
118
- console.log(
119
- `QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`
120
- );
121
- console.log(`Manual pairing code: ${manualPairingCode}`);
122
- } else {
123
- console.log("Device is already commissioned. Waiting for controllers to connect ...");
124
- }
80
+ async function getConfiguration() {
81
+ const environment = Environment.default;
82
+ const storageService = environment.get(StorageService);
83
+ console.log(`Storage location: ${storageService.location} (Directory)`);
84
+ console.log(
85
+ '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.'
86
+ );
87
+ const deviceStorage = (await storageService.open("device")).createContext("data");
88
+ const isSocket2 = Array();
89
+ const numDevices = environment.vars.number("num") || 2;
90
+ if (deviceStorage.has("isSocket")) {
91
+ console.log(`Device types found in storage. --type parameter is ignored.`);
92
+ deviceStorage.get("isSocket").forEach((type) => isSocket2.push(type));
125
93
  }
126
- async stop() {
127
- await this.matterServer?.close();
94
+ for (let i = 1; i < numDevices; i++) {
95
+ if (isSocket2[i - 1] !== void 0)
96
+ continue;
97
+ isSocket2.push(environment.vars.string(`type${i}`) === "socket");
128
98
  }
99
+ const deviceName2 = "Matter test device";
100
+ const vendorName2 = "matter-node.js";
101
+ const passcode2 = environment.vars.number("passcode") ?? deviceStorage.get("passcode", 20202021);
102
+ const discriminator2 = environment.vars.number("discriminator") ?? deviceStorage.get("discriminator", 3840);
103
+ const vendorId2 = environment.vars.number("vendorid") ?? deviceStorage.get("vendorid", 65521);
104
+ const productName2 = `node-matter OnOff ${isSocket2 ? "Socket" : "Light"}`;
105
+ const productId2 = environment.vars.number("productid") ?? deviceStorage.get("productid", 32768);
106
+ const port2 = environment.vars.number("port") ?? 5540;
107
+ const uniqueId2 = environment.vars.string("uniqueid") ?? deviceStorage.get("uniqueid", Time.nowMs().toString());
108
+ deviceStorage.set("passcode", passcode2);
109
+ deviceStorage.set("discriminator", discriminator2);
110
+ deviceStorage.set("vendorid", vendorId2);
111
+ deviceStorage.set("productid", productId2);
112
+ deviceStorage.set("isSocket", isSocket2);
113
+ deviceStorage.set("uniqueid", uniqueId2);
114
+ return {
115
+ isSocket: isSocket2,
116
+ deviceName: deviceName2,
117
+ vendorName: vendorName2,
118
+ passcode: passcode2,
119
+ discriminator: discriminator2,
120
+ vendorId: vendorId2,
121
+ productName: productName2,
122
+ productId: productId2,
123
+ port: port2,
124
+ uniqueId: uniqueId2
125
+ };
129
126
  }
130
- const device = new ComposedDevice();
131
- device.start().then(() => {
132
- }).catch((err) => console.error(err));
133
- process.on("SIGINT", () => {
134
- device.stop().then(() => {
135
- storage.close().then(() => process.exit(0)).catch((err) => console.error(err));
136
- }).catch((err) => console.error(err));
137
- });
138
127
  //# sourceMappingURL=ComposedDeviceNode.js.map