@project-chip/matter-node.js-examples 0.7.5-alpha.0-20240222-8696097f → 0.8.0-alpha.0-20240309-64eaef67
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +44 -0
- package/dist/esm/examples/BridgedDeviceNode.js +147 -0
- package/dist/esm/examples/BridgedDeviceNode.js.map +7 -0
- package/dist/esm/examples/{BridgedDevicesNode.js → BridgedDevicesNodeLegacy.js} +2 -2
- package/dist/esm/examples/BridgedDevicesNodeLegacy.js.map +7 -0
- package/dist/esm/examples/ComposedDeviceNode.js +116 -127
- package/dist/esm/examples/ComposedDeviceNode.js.map +3 -3
- package/dist/esm/examples/ComposedDeviceNodeLegacy.js +138 -0
- package/dist/esm/examples/ComposedDeviceNodeLegacy.js.map +7 -0
- package/dist/esm/examples/ControllerNode.js +24 -20
- package/dist/esm/examples/ControllerNode.js.map +2 -2
- package/dist/esm/examples/ControllerNodeLegacy.js +227 -0
- package/dist/esm/examples/ControllerNodeLegacy.js.map +7 -0
- package/dist/esm/examples/DeviceNode.js +118 -159
- package/dist/esm/examples/DeviceNode.js.map +2 -2
- package/dist/esm/examples/DeviceNodeFull.js +253 -0
- package/dist/esm/examples/DeviceNodeFull.js.map +7 -0
- package/dist/esm/examples/DeviceNodeFullLegacy.js +171 -0
- package/dist/esm/examples/DeviceNodeFullLegacy.js.map +7 -0
- package/dist/esm/examples/IlluminatedRollerShade.js +85 -0
- package/dist/esm/examples/IlluminatedRollerShade.js.map +7 -0
- package/dist/esm/examples/LightDevice.js +34 -0
- package/dist/esm/examples/LightDevice.js.map +7 -0
- package/dist/esm/examples/MultiDeviceNode.js +133 -134
- package/dist/esm/examples/MultiDeviceNode.js.map +3 -3
- package/dist/esm/examples/MultiDeviceNodeLegacy.js +146 -0
- package/dist/esm/examples/MultiDeviceNodeLegacy.js.map +7 -0
- package/dist/esm/examples/SensorDeviceNode.js +167 -0
- package/dist/esm/examples/SensorDeviceNode.js.map +7 -0
- package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js +115 -0
- package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js.map +7 -0
- package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js +115 -0
- package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js.map +7 -0
- package/dist/esm/examples/cluster/{DummyWifiNetworkCommissioningClusterServer.js → DummyWifiNetworkCommissioningServerLegacy.js} +16 -14
- package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js.map +7 -0
- package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js +110 -0
- package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js.map +7 -0
- package/dist/esm/tutorial/example01.js +5 -0
- package/dist/esm/tutorial/example01.js.map +7 -0
- package/dist/esm/tutorial/example02.js +7 -0
- package/dist/esm/tutorial/example02.js.map +7 -0
- package/dist/esm/tutorial/example03.js +15 -0
- package/dist/esm/tutorial/example03.js.map +7 -0
- package/dist/esm/tutorial/example04.js +10 -0
- package/dist/esm/tutorial/example04.js.map +7 -0
- package/dist/esm/tutorial/example05.js +14 -0
- package/dist/esm/tutorial/example05.js.map +7 -0
- package/package.json +9 -6
- package/src/examples/BridgedDeviceNode.ts +260 -0
- package/src/examples/{BridgedDevicesNode.ts → BridgedDevicesNodeLegacy.ts} +6 -1
- package/src/examples/ComposedDeviceNode.ts +173 -223
- package/src/examples/ComposedDeviceNodeLegacy.ts +252 -0
- package/src/examples/ControllerNode.ts +28 -22
- package/src/examples/ControllerNodeLegacy.ts +354 -0
- package/src/examples/DeviceNode.ts +173 -273
- package/src/examples/DeviceNodeFull.ts +440 -0
- package/src/examples/DeviceNodeFullLegacy.ts +307 -0
- package/src/examples/IlluminatedRollerShade.ts +130 -0
- package/src/examples/LightDevice.ts +60 -0
- package/src/examples/MultiDeviceNode.ts +184 -236
- package/src/examples/MultiDeviceNodeLegacy.ts +267 -0
- package/src/examples/SensorDeviceNode.ts +236 -0
- package/src/examples/cluster/DummyThreadNetworkCommissioningServer.ts +156 -0
- package/src/examples/cluster/DummyWifiNetworkCommissioningServer.ts +153 -0
- package/src/examples/cluster/{DummyWifiNetworkCommissioningClusterServer.ts → DummyWifiNetworkCommissioningServerLegacy.ts} +16 -13
- package/src/examples/cluster/MyFancyOwnFunctionality.ts +185 -0
- package/src/tsconfig.json +9 -1
- package/src/tutorial/example01.ts +6 -0
- package/src/tutorial/example02.ts +9 -0
- package/src/tutorial/example03.ts +19 -0
- package/src/tutorial/example04.ts +13 -0
- package/src/tutorial/example05.ts +19 -0
- package/dist/esm/examples/BridgedDevicesNode.js.map +0 -7
- package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningClusterServer.js.map +0 -7
@@ -0,0 +1,85 @@
|
|
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 { WindowCoveringServer } from "@project-chip/matter.js/behaviors/window-covering";
|
8
|
+
import { OnOffLightDevice, OnOffLightRequirements } from "@project-chip/matter.js/devices/OnOffLightDevice";
|
9
|
+
import { WindowCoveringDevice } from "@project-chip/matter.js/devices/WindowCoveringDevice";
|
10
|
+
import { ServerNode } from "@project-chip/matter.js/node";
|
11
|
+
const LiftingWindowCoveringServer = WindowCoveringServer.with("Lift", "AbsolutePosition", "PositionAwareLift");
|
12
|
+
class RollerShade extends LiftingWindowCoveringServer {
|
13
|
+
get currentPos() {
|
14
|
+
return this.state.currentPositionLiftPercent100ths ?? 0;
|
15
|
+
}
|
16
|
+
get targetPos() {
|
17
|
+
return this.state.targetPositionLiftPercent100ths ?? 0;
|
18
|
+
}
|
19
|
+
set targetPos(position) {
|
20
|
+
this.state.targetPositionLiftPercent100ths = position ?? 0;
|
21
|
+
}
|
22
|
+
async initialize() {
|
23
|
+
this.reactTo(this.events.targetPositionLiftPercent100ths$Change, this.writeTargetToMotor);
|
24
|
+
await this.readTargetFromMotor();
|
25
|
+
if (this.targetPos === null) {
|
26
|
+
this.targetPos = this.currentPos;
|
27
|
+
}
|
28
|
+
}
|
29
|
+
upOrOpen() {
|
30
|
+
this.targetPos = 0;
|
31
|
+
}
|
32
|
+
downOrClose() {
|
33
|
+
this.targetPos = 1e4;
|
34
|
+
}
|
35
|
+
stopMotion() {
|
36
|
+
this.targetPos = this.currentPos;
|
37
|
+
}
|
38
|
+
goToLiftPercentage(request) {
|
39
|
+
this.targetPos = request.liftPercent100thsValue;
|
40
|
+
}
|
41
|
+
async writeTargetToMotor() {
|
42
|
+
console.log("Window covering target position is now", `${this.targetPos / 100}%`);
|
43
|
+
}
|
44
|
+
async readTargetFromMotor() {
|
45
|
+
this.state.currentPositionLiftPercent100ths = 0;
|
46
|
+
}
|
47
|
+
set currentPos(value) {
|
48
|
+
this.state.currentPositionLiftPercent100ths = value;
|
49
|
+
}
|
50
|
+
}
|
51
|
+
class ValanceLight extends OnOffLightRequirements.OnOffServer {
|
52
|
+
initialize() {
|
53
|
+
this.reactTo(this.events.onOff$Change, this.#stateChanged);
|
54
|
+
}
|
55
|
+
#stateChanged(value) {
|
56
|
+
console.log(`Valance is now ${value ? "illuminated" : "dark"}`);
|
57
|
+
}
|
58
|
+
}
|
59
|
+
const node = new ServerNode({
|
60
|
+
id: "excelsior1000",
|
61
|
+
productDescription: {},
|
62
|
+
commissioning: {
|
63
|
+
passcode: 20202021,
|
64
|
+
discriminator: 3840
|
65
|
+
},
|
66
|
+
basicInformation: {
|
67
|
+
vendorName: "Acme Corporation",
|
68
|
+
productName: "Excelsior 1000 EZ-Nite\u2122",
|
69
|
+
vendorId: 65521,
|
70
|
+
productId: 32768,
|
71
|
+
serialNumber: "1234-12345-123"
|
72
|
+
},
|
73
|
+
parts: [
|
74
|
+
{
|
75
|
+
type: WindowCoveringDevice.with(RollerShade),
|
76
|
+
id: "shade"
|
77
|
+
},
|
78
|
+
{
|
79
|
+
type: OnOffLightDevice.with(ValanceLight),
|
80
|
+
id: "valance"
|
81
|
+
}
|
82
|
+
]
|
83
|
+
});
|
84
|
+
await node.run();
|
85
|
+
//# sourceMappingURL=IlluminatedRollerShade.js.map
|
@@ -0,0 +1,7 @@
|
|
1
|
+
{
|
2
|
+
"version": 3,
|
3
|
+
"sources": ["../../../src/examples/IlluminatedRollerShade.ts"],
|
4
|
+
"sourcesContent": ["/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter-node.js\";\n\nimport { GoToLiftPercentageRequest, WindowCoveringServer } from \"@project-chip/matter.js/behaviors/window-covering\";\nimport { OnOffLightDevice, OnOffLightRequirements } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { WindowCoveringDevice } from \"@project-chip/matter.js/devices/WindowCoveringDevice\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\n\n/**\n * This example demonstrates implementation of a \"composed\" device comprising multiple sub-devices\n *\n * Our example device, the Excelsior 1000 EZ-Nite\u2122, is a roller shade with an illuminated valance.\n */\n\nconst LiftingWindowCoveringServer = WindowCoveringServer.with(\"Lift\", \"AbsolutePosition\", \"PositionAwareLift\");\n\n/**\n * Implementation of the Matter WindowCovering cluster for the shade motor.\n *\n * TODO - some of this should probably move to WindowCoveringServer\n */\nclass RollerShade extends LiftingWindowCoveringServer {\n get currentPos() {\n return this.state.currentPositionLiftPercent100ths ?? 0;\n }\n\n get targetPos() {\n return this.state.targetPositionLiftPercent100ths ?? 0;\n }\n\n set targetPos(position: number) {\n this.state.targetPositionLiftPercent100ths = position ?? 0;\n }\n\n override async initialize() {\n this.reactTo(this.events.targetPositionLiftPercent100ths$Change, this.writeTargetToMotor);\n\n await this.readTargetFromMotor();\n if (this.targetPos === null) {\n this.targetPos = this.currentPos;\n }\n }\n\n override upOrOpen() {\n // 0 = 0%, fully open\n this.targetPos = 0;\n }\n\n override downOrClose() {\n // 10000 = 100%, fully closed\n this.targetPos = 10000;\n }\n\n override stopMotion() {\n this.targetPos = this.currentPos;\n }\n\n override goToLiftPercentage(this: RollerShade, request: GoToLiftPercentageRequest) {\n this.targetPos = request.liftPercent100thsValue;\n }\n\n protected async writeTargetToMotor() {\n // For this contrived example we just log the target position and don't actually animate our fake roller shade\n console.log(\"Window covering target position is now\", `${this.targetPos / 100}%`);\n }\n\n protected async readTargetFromMotor() {\n // Our fake shade is stuck open\n this.state.currentPositionLiftPercent100ths = 0;\n }\n\n protected set currentPos(value: number) {\n this.state.currentPositionLiftPercent100ths = value;\n }\n}\n\n/**\n * Implementation of the OnOff cluster for our valance light.\n */\nclass ValanceLight extends OnOffLightRequirements.OnOffServer {\n override initialize() {\n this.reactTo(this.events.onOff$Change, this.#stateChanged);\n }\n\n #stateChanged(value: boolean) {\n console.log(`Valance is now ${value ? \"illuminated\" : \"dark\"}`);\n }\n}\n\n/**\n * Our Matter node.\n */\nconst node = new ServerNode({\n id: \"excelsior1000\",\n\n productDescription: {},\n\n commissioning: {\n passcode: 20202021,\n discriminator: 3840,\n },\n\n basicInformation: {\n vendorName: \"Acme Corporation\",\n productName: \"Excelsior 1000 EZ-Nite\u2122\",\n vendorId: 0xfff1,\n productId: 0x8000,\n serialNumber: \"1234-12345-123\",\n },\n\n parts: [\n {\n type: WindowCoveringDevice.with(RollerShade),\n id: \"shade\",\n },\n\n {\n type: OnOffLightDevice.with(ValanceLight),\n id: \"valance\",\n },\n ],\n});\n\nawait node.run();\n"],
|
5
|
+
"mappings": "AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,OAAO;AAEP,SAAoC,4BAA4B;AAChE,SAAS,kBAAkB,8BAA8B;AACzD,SAAS,4BAA4B;AACrC,SAAS,kBAAkB;AAQ3B,MAAM,8BAA8B,qBAAqB,KAAK,QAAQ,oBAAoB,mBAAmB;AAO7G,MAAM,oBAAoB,4BAA4B;AAAA,EAClD,IAAI,aAAa;AACb,WAAO,KAAK,MAAM,oCAAoC;AAAA,EAC1D;AAAA,EAEA,IAAI,YAA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,EAClB;AAAA,EAEA,OAAO;AAAA,IACH;AAAA,MACI,MAAM,qBAAqB,KAAK,WAAW;AAAA,MAC3C,IAAI;AAAA,IACR;AAAA,IAEA;AAAA,MACI,MAAM,iBAAiB,KAAK,YAAY;AAAA,MACxC,IAAI;AAAA,IACR;AAAA,EACJ;AACJ,CAAC;AAED,MAAM,KAAK,IAAI;",
|
6
|
+
"names": []
|
7
|
+
}
|
@@ -0,0 +1,34 @@
|
|
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 { OnOffLightDevice, OnOffLightRequirements } from "@project-chip/matter.js/devices/OnOffLightDevice";
|
8
|
+
import { ServerNode } from "@project-chip/matter.js/node";
|
9
|
+
class ReportingOnOffServer extends OnOffLightRequirements.OnOffServer {
|
10
|
+
// Intercept the "on" command to the Matter On/Off cluster to print a log message.
|
11
|
+
async on() {
|
12
|
+
console.log("Turning light ON");
|
13
|
+
await super.on();
|
14
|
+
}
|
15
|
+
// This is the functional inverse of on() above.
|
16
|
+
//
|
17
|
+
// For demonstration purposes we update state ourselves rather than deferring to matter.js's default "off" handler
|
18
|
+
// via super.off().
|
19
|
+
off() {
|
20
|
+
console.log("Turning light OFF");
|
21
|
+
this.state.onOff = false;
|
22
|
+
}
|
23
|
+
// Use event handlers to log on/off state reactively, after it changes.
|
24
|
+
initialize() {
|
25
|
+
this.events.onOff$Change.on((value) => {
|
26
|
+
console.log(`Light is now ${value ? "ON" : "OFF"}`);
|
27
|
+
});
|
28
|
+
}
|
29
|
+
}
|
30
|
+
const ExampleLight = OnOffLightDevice.with(ReportingOnOffServer);
|
31
|
+
const node = await ServerNode.create();
|
32
|
+
await node.add(ExampleLight);
|
33
|
+
await node.run();
|
34
|
+
//# sourceMappingURL=LightDevice.js.map
|
@@ -0,0 +1,7 @@
|
|
1
|
+
{
|
2
|
+
"version": 3,
|
3
|
+
"sources": ["../../../src/examples/LightDevice.ts"],
|
4
|
+
"sourcesContent": ["/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// This demonstrates bringing a \"light\" device online with matter.js.\n\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter-node.js\";\n\nimport { OnOffLightDevice, OnOffLightRequirements } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\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 ReportingOnOffServer extends OnOffLightRequirements.OnOffServer {\n // Intercept the \"on\" command to the Matter On/Off cluster to print a log message.\n override async on() {\n console.log(\"Turning light 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 off() {\n console.log(\"Turning light 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$Change.on(value => {\n console.log(`Light is now ${value ? \"ON\" : \"OFF\"}`);\n });\n }\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.\nconst ExampleLight = OnOffLightDevice.with(ReportingOnOffServer);\n\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// IlluminatedRollerShade.ts for a more detailed example.\nconst node = await ServerNode.create();\n\n// Nodes are a composition of endpoints. Add a single endpoint to the node, our example light device.\nawait node.add(ExampleLight);\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.\nawait node.run();\n"],
|
5
|
+
"mappings": "AAAA;AAAA;AAAA;AAAA;AAAA;AASA,OAAO;AAEP,SAAS,kBAAkB,8BAA8B;AACzD,SAAS,kBAAkB;AAI3B,MAAM,6BAA6B,uBAAuB,YAAY;AAAA;AAAA,EAElE,MAAe,KAAK;AAChB,YAAQ,IAAI,kBAAkB;AAC9B,UAAM,MAAM,GAAG;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMS,MAAM;AACX,YAAQ,IAAI,mBAAmB;AAC/B,SAAK,MAAM,QAAQ;AAAA,EACvB;AAAA;AAAA,EAGS,aAAa;AAClB,SAAK,OAAO,aAAa,GAAG,WAAS;AACjC,cAAQ,IAAI,gBAAgB,QAAQ,OAAO,KAAK,EAAE;AAAA,IACtD,CAAC;AAAA,EACL;AACJ;AAKA,MAAM,eAAe,iBAAiB,KAAK,oBAAoB;AAO/D,MAAM,OAAO,MAAM,WAAW,OAAO;AAGrC,MAAM,KAAK,IAAI,YAAY;AAM3B,MAAM,KAAK,IAAI;",
|
6
|
+
"names": []
|
7
|
+
}
|
@@ -1,146 +1,145 @@
|
|
1
|
-
#!/usr/bin/env node
|
2
1
|
/**
|
3
2
|
* @license
|
4
|
-
* Copyright 2022
|
3
|
+
* Copyright 2022-2024 Matter.js Authors
|
5
4
|
* SPDX-License-Identifier: Apache-2.0
|
6
5
|
*/
|
7
|
-
import
|
8
|
-
import {
|
9
|
-
import {
|
10
|
-
import {
|
11
|
-
import {
|
12
|
-
import {
|
13
|
-
import {
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
requireMinNodeVersion
|
19
|
-
} from "@project-chip/matter-node.js/util";
|
20
|
-
import { VendorId } from "@project-chip/matter.js/datatype";
|
21
|
-
const logger = Logger.get("MultiDevice");
|
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
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
31
|
-
|
32
|
-
|
33
|
-
|
34
|
-
|
35
|
-
|
18
|
+
const devices = await getConfiguration();
|
19
|
+
for (let idx = 1; idx < devices.length; idx++) {
|
20
|
+
const {
|
21
|
+
isSocket,
|
22
|
+
deviceName,
|
23
|
+
vendorName,
|
24
|
+
passcode,
|
25
|
+
discriminator,
|
26
|
+
vendorId,
|
27
|
+
productName,
|
28
|
+
productId,
|
29
|
+
port,
|
30
|
+
uniqueId
|
31
|
+
} = devices[idx];
|
32
|
+
const i = idx + 1;
|
33
|
+
const server = await ServerNode.create({
|
34
|
+
// Required: Give the Node a unique ID which is used to store the state of this node
|
35
|
+
id: uniqueId,
|
36
|
+
// Provide Network relevant configuration like the port
|
37
|
+
// Optional when operating only one device on a host, Default port is 5540
|
38
|
+
network: {
|
39
|
+
port
|
40
|
+
},
|
41
|
+
// Provide Commissioning relevant settings
|
42
|
+
// Optional for development/testing purposes
|
43
|
+
commissioning: {
|
44
|
+
passcode,
|
45
|
+
discriminator
|
46
|
+
},
|
47
|
+
// Provide Node announcement settings
|
48
|
+
// Optional: If Ommitted some development defaults are used
|
49
|
+
productDescription: {
|
50
|
+
name: deviceName,
|
51
|
+
deviceType: DeviceTypeId(isSocket ? OnOffPlugInUnitDevice.deviceType : OnOffLightDevice.deviceType)
|
52
|
+
},
|
53
|
+
// Provide defaults for the BasicInformation cluster on the Root endpoint
|
54
|
+
// Optional: If Omitted some development defaults are used
|
55
|
+
basicInformation: {
|
56
|
+
vendorName,
|
57
|
+
vendorId: VendorId(vendorId),
|
58
|
+
nodeLabel: productName,
|
59
|
+
productName,
|
60
|
+
productLabel: productName,
|
61
|
+
productId,
|
62
|
+
serialNumber: `matterjs-${uniqueId}`,
|
63
|
+
uniqueId
|
64
|
+
}
|
65
|
+
});
|
66
|
+
console.log(
|
67
|
+
`Added device ${i} on port ${port} and unique id ${uniqueId}: Passcode: ${passcode}, Discriminator: ${discriminator}`
|
68
|
+
);
|
69
|
+
const endpoint = new Endpoint(isSocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: "onoff" });
|
70
|
+
await server.add(endpoint);
|
71
|
+
let isIdentifying = false;
|
72
|
+
endpoint.events.identify.identifyTime$Change.on((value) => {
|
73
|
+
if (value > 0 && !isIdentifying) {
|
74
|
+
isIdentifying = true;
|
75
|
+
console.log(`Run identify logic, ideally blink a light every 0.5s ...`);
|
76
|
+
} else if (value === 0) {
|
77
|
+
isIdentifying = false;
|
78
|
+
console.log(`Stop identify logic ...`);
|
79
|
+
}
|
80
|
+
});
|
81
|
+
endpoint.events.onOff.onOff$Change.on((value) => {
|
82
|
+
executeCommand(value ? `on${i}` : `off${i}`);
|
83
|
+
console.log(`OnOff ${i} is now ${value ? "ON" : "OFF"}`);
|
84
|
+
});
|
85
|
+
logEndpoint(EndpointServer.forEndpoint(server));
|
86
|
+
console.log("----------------------------");
|
87
|
+
console.log(`QR Code for Device ${i} on port ${port}:`);
|
88
|
+
console.log("----------------------------");
|
89
|
+
await server.bringOnline();
|
36
90
|
}
|
37
|
-
|
38
|
-
|
39
|
-
|
40
|
-
|
41
|
-
|
42
|
-
Logger.format = Format.HTML;
|
43
|
-
break;
|
44
|
-
default:
|
45
|
-
if (process.stdin?.isTTY)
|
46
|
-
Logger.format = Format.ANSI;
|
91
|
+
function executeCommand(scriptParamName) {
|
92
|
+
const script = Environment.default.vars.string(scriptParamName);
|
93
|
+
if (script === void 0)
|
94
|
+
return void 0;
|
95
|
+
console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
|
47
96
|
}
|
48
|
-
|
49
|
-
const
|
50
|
-
|
51
|
-
|
52
|
-
|
53
|
-
|
54
|
-
|
55
|
-
|
56
|
-
|
57
|
-
|
58
|
-
|
59
|
-
|
60
|
-
|
61
|
-
|
62
|
-
const
|
63
|
-
|
64
|
-
|
65
|
-
let defaultPort = 5550;
|
66
|
-
const numDevices = getIntParameter("num") || 2;
|
67
|
-
for (let i = 1; i <= numDevices; i++) {
|
68
|
-
if (deviceStorage.has(`isSocket${i}`)) {
|
69
|
-
logger.info("Device type found in storage. -type parameter is ignored.");
|
70
|
-
}
|
71
|
-
const isSocket = deviceStorage.get(`isSocket${i}`, getParameter(`type${i}`) === "socket");
|
72
|
-
const deviceName = `Matter ${getParameter(`type${i}`) ?? "light"} device ${i}`;
|
73
|
-
const deviceType = getParameter(`type${i}`) === "socket" ? DeviceTypes.ON_OFF_PLUGIN_UNIT.code : DeviceTypes.ON_OFF_LIGHT.code;
|
74
|
-
const vendorName = "matter-node.js";
|
75
|
-
const passcode = getIntParameter(`passcode${i}`) ?? deviceStorage.get(`passcode${i}`, defaultPasscode++);
|
76
|
-
const discriminator = getIntParameter(`discriminator${i}`) ?? deviceStorage.get(`discriminator${i}`, defaultDiscriminator++);
|
77
|
-
const vendorId = getIntParameter(`vendorid${i}`) ?? deviceStorage.get(`vendorid${i}`, 65521);
|
78
|
-
const productName = `node-matter OnOff-Device ${i}`;
|
79
|
-
const productId = getIntParameter(`productid${i}`) ?? deviceStorage.get(`productid${i}`, 32768);
|
80
|
-
const port = getIntParameter(`port${i}`) ?? defaultPort++;
|
81
|
-
const uniqueId = getIntParameter(`uniqueid${i}`) ?? deviceStorage.get(`uniqueid${i}`, `${i}-${Time.nowMs()}`);
|
82
|
-
deviceStorage.set(`passcode${i}`, passcode);
|
83
|
-
deviceStorage.set(`discriminator${i}`, discriminator);
|
84
|
-
deviceStorage.set(`vendorid${i}`, vendorId);
|
85
|
-
deviceStorage.set(`productid${i}`, productId);
|
86
|
-
deviceStorage.set(`isSocket${i}`, isSocket);
|
87
|
-
deviceStorage.set(`uniqueid${i}`, uniqueId);
|
88
|
-
const commissioningServer = new CommissioningServer({
|
89
|
-
port,
|
90
|
-
deviceName,
|
91
|
-
deviceType,
|
92
|
-
passcode,
|
93
|
-
discriminator,
|
94
|
-
basicInformation: {
|
95
|
-
vendorName,
|
96
|
-
vendorId: VendorId(vendorId),
|
97
|
-
nodeLabel: productName,
|
98
|
-
productName,
|
99
|
-
productLabel: productName,
|
100
|
-
productId,
|
101
|
-
serialNumber: `node-matter-${uniqueId}`
|
102
|
-
}
|
103
|
-
});
|
104
|
-
console.log(
|
105
|
-
`Added device ${i} on port ${port} and unique id ${uniqueId}: Passcode: ${passcode}, Discriminator: ${discriminator}`
|
106
|
-
);
|
107
|
-
const onOffDevice = getParameter(`type${i}`) === "socket" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();
|
108
|
-
onOffDevice.addFixedLabel("orientation", getParameter(`orientation${i}`) ?? `orientation ${i}`);
|
109
|
-
onOffDevice.addOnOffListener((on) => commandExecutor(on ? `on${i}` : `off${i}`)?.());
|
110
|
-
commissioningServer.addDevice(onOffDevice);
|
111
|
-
await this.matterServer.addCommissioningServer(commissioningServer);
|
112
|
-
commissioningServers.push(commissioningServer);
|
97
|
+
async function getConfiguration() {
|
98
|
+
const environment = Environment.default;
|
99
|
+
const storageService = environment.get(StorageService);
|
100
|
+
console.log(`Storage location: ${storageService.location} (Directory)`);
|
101
|
+
console.log(
|
102
|
+
'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.'
|
103
|
+
);
|
104
|
+
const deviceStorage = (await storageService.open("device")).createContext("data");
|
105
|
+
let defaultPasscode = 20202021;
|
106
|
+
let defaultDiscriminator = 3840;
|
107
|
+
let defaultPort = 5550;
|
108
|
+
const devices2 = [];
|
109
|
+
const numDevices = environment.vars.number("num") ?? 2;
|
110
|
+
for (let i = 1; i <= numDevices; i++) {
|
111
|
+
const isSocket = deviceStorage.get(`isSocket${i}`, environment.vars.string(`type${i}`) === "socket");
|
112
|
+
if (deviceStorage.has(`isSocket${i}`)) {
|
113
|
+
console.log(`Device type ${isSocket ? "socket" : "light"} found in storage. --type parameter is ignored.`);
|
113
114
|
}
|
114
|
-
|
115
|
-
|
116
|
-
|
117
|
-
|
118
|
-
|
119
|
-
|
120
|
-
|
121
|
-
|
122
|
-
|
123
|
-
|
124
|
-
|
125
|
-
|
126
|
-
|
127
|
-
|
128
|
-
|
129
|
-
|
130
|
-
|
131
|
-
|
115
|
+
const deviceName = `Matter ${environment.vars.string(`type${i}`) ?? "light"} device ${i}`;
|
116
|
+
const vendorName = "matter-node.js";
|
117
|
+
const passcode = environment.vars.number(`passcode${i}`) ?? deviceStorage.get(`passcode${i}`, defaultPasscode++);
|
118
|
+
const discriminator = environment.vars.number(`discriminator${i}`) ?? deviceStorage.get(`discriminator${i}`, defaultDiscriminator++);
|
119
|
+
const vendorId = environment.vars.number(`vendorid${i}`) ?? deviceStorage.get(`vendorid${i}`, 65521);
|
120
|
+
const productName = `node-matter OnOff-Device ${i}`;
|
121
|
+
const productId = environment.vars.number(`productid${i}`) ?? deviceStorage.get(`productid${i}`, 32768);
|
122
|
+
const port = environment.vars.number(`port${i}`) ?? defaultPort++;
|
123
|
+
const uniqueId = environment.vars.string(`uniqueid${i}`) ?? deviceStorage.get(`uniqueid${i}`, `${i}-${Time.nowMs()}`);
|
124
|
+
deviceStorage.set(`passcode${i}`, passcode);
|
125
|
+
deviceStorage.set(`discriminator${i}`, discriminator);
|
126
|
+
deviceStorage.set(`vendorid${i}`, vendorId);
|
127
|
+
deviceStorage.set(`productid${i}`, productId);
|
128
|
+
deviceStorage.set(`isSocket${i}`, isSocket);
|
129
|
+
deviceStorage.set(`uniqueid${i}`, uniqueId);
|
130
|
+
devices2.push({
|
131
|
+
isSocket,
|
132
|
+
deviceName,
|
133
|
+
vendorName,
|
134
|
+
passcode,
|
135
|
+
discriminator,
|
136
|
+
vendorId,
|
137
|
+
productName,
|
138
|
+
productId,
|
139
|
+
port,
|
140
|
+
uniqueId
|
132
141
|
});
|
133
142
|
}
|
134
|
-
|
135
|
-
await this.matterServer?.close();
|
136
|
-
}
|
143
|
+
return devices2;
|
137
144
|
}
|
138
|
-
const device = new Device();
|
139
|
-
device.start().then(() => {
|
140
|
-
}).catch((err) => console.error(err));
|
141
|
-
process.on("SIGINT", () => {
|
142
|
-
device.stop().then(() => {
|
143
|
-
storage.close().then(() => process.exit(0)).catch((err) => console.error(err));
|
144
|
-
}).catch((err) => console.error(err));
|
145
|
-
});
|
146
145
|
//# sourceMappingURL=MultiDeviceNode.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/MultiDeviceNode.ts"],
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022 The node-matter 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. When you want to add a composed devices to a Aggregator you need to\n * add all endpoints of the composed device to an \"ComposedDevice\" instance! (not shown in this 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 { CommissioningServer, MatterServer } from \"@project-chip/matter-node.js\";\n\nimport { 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\";\nimport { VendorId } from \"@project-chip/matter.js/datatype\";\n\nconst logger = Logger.get(\"MultiDevice\");\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 Device {\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 const netInterface = getParameter(\"netinterface\");\n\n const deviceStorage = storageManager.createContext(\"Device\");\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 /**\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 commissioningServers = new Array<CommissioningServer>();\n\n let defaultPasscode = 20202021;\n let defaultDiscriminator = 3840;\n let defaultPort = 5550;\n\n const numDevices = getIntParameter(\"num\") || 2;\n for (let i = 1; i <= numDevices; i++) {\n if (deviceStorage.has(`isSocket${i}`)) {\n logger.info(\"Device type found in storage. -type parameter is ignored.\");\n }\n const isSocket = deviceStorage.get(`isSocket${i}`, getParameter(`type${i}`) === \"socket\");\n const deviceName = `Matter ${getParameter(`type${i}`) ?? \"light\"} device ${i}`;\n const deviceType =\n getParameter(`type${i}`) === \"socket\"\n ? DeviceTypes.ON_OFF_PLUGIN_UNIT.code\n : DeviceTypes.ON_OFF_LIGHT.code;\n const vendorName = \"matter-node.js\";\n const passcode = getIntParameter(`passcode${i}`) ?? deviceStorage.get(`passcode${i}`, defaultPasscode++);\n const discriminator =\n getIntParameter(`discriminator${i}`) ?? deviceStorage.get(`discriminator${i}`, defaultDiscriminator++);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = getIntParameter(`vendorid${i}`) ?? deviceStorage.get(`vendorid${i}`, 0xfff1);\n const productName = `node-matter OnOff-Device ${i}`;\n const productId = getIntParameter(`productid${i}`) ?? deviceStorage.get(`productid${i}`, 0x8000);\n\n const port = getIntParameter(`port${i}`) ?? defaultPort++;\n\n const uniqueId =\n getIntParameter(`uniqueid${i}`) ?? deviceStorage.get(`uniqueid${i}`, `${i}-${Time.nowMs()}`);\n\n deviceStorage.set(`passcode${i}`, passcode);\n deviceStorage.set(`discriminator${i}`, discriminator);\n deviceStorage.set(`vendorid${i}`, vendorId);\n deviceStorage.set(`productid${i}`, productId);\n deviceStorage.set(`isSocket${i}`, isSocket);\n deviceStorage.set(`uniqueid${i}`, uniqueId);\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 console.log(\n `Added device ${i} on port ${port} and unique id ${uniqueId}: Passcode: ${passcode}, Discriminator: ${discriminator}`,\n );\n\n const onOffDevice =\n getParameter(`type${i}`) === \"socket\" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n onOffDevice.addFixedLabel(\"orientation\", getParameter(`orientation${i}`) ?? `orientation ${i}`);\n onOffDevice.addOnOffListener(on => commandExecutor(on ? `on${i}` : `off${i}`)?.());\n commissioningServer.addDevice(onOffDevice);\n\n await this.matterServer.addCommissioningServer(commissioningServer);\n\n commissioningServers.push(commissioningServer);\n }\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 console.log();\n commissioningServers.forEach((commissioningServer, index) => {\n console.log(\"----------------------------\");\n console.log(`Device ${index + 1}:`);\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 console.log();\n });\n }\n\n async stop() {\n await this.matterServer?.close();\n }\n}\n\nconst device = new Device();\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": ";
|
6
|
-
"names": []
|
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 { 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 { Time } from \"@project-chip/matter.js/time\";\nimport { execSync } from \"child_process\";\n\nrequireMinNodeVersion(16);\n\nconst devices = await getConfiguration();\nfor (let idx = 1; idx < devices.length; idx++) {\n const {\n isSocket,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n } = devices[idx];\n const i = idx + 1;\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 console.log(\n `Added device ${i} on port ${port} and unique id ${uniqueId}: Passcode: ${passcode}, Discriminator: ${discriminator}`,\n );\n\n const endpoint = new Endpoint(isSocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: \"onoff\" });\n await server.add(endpoint);\n\n /**\n * Register state change handlers 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 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(`Run identify logic, ideally blink a light every 0.5s ...`);\n } else if (value === 0) {\n isIdentifying = false;\n console.log(`Stop identify logic ...`);\n }\n });\n\n endpoint.events.onOff.onOff$Change.on(value => {\n executeCommand(value ? `on${i}` : `off${i}`);\n console.log(`OnOff ${i} 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 console.log(\"----------------------------\");\n console.log(`QR Code for Device ${i} on port ${port}:`);\n console.log(\"----------------------------\");\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.bringOnline();\n}\n\n/*********************************************************************************************************\n * Convenience Methods\n *********************************************************************************************************/\n\n/**\n * Defines a shell command from an environment variable and execute it and log the response\n */\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 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 let defaultPasscode = 20202021;\n let defaultDiscriminator = 3840;\n let defaultPort = 5550;\n\n const devices = [];\n const numDevices = environment.vars.number(\"num\") ?? 2;\n for (let i = 1; i <= numDevices; i++) {\n const isSocket = deviceStorage.get(`isSocket${i}`, environment.vars.string(`type${i}`) === \"socket\");\n if (deviceStorage.has(`isSocket${i}`)) {\n console.log(`Device type ${isSocket ? \"socket\" : \"light\"} found in storage. --type parameter is ignored.`);\n }\n const deviceName = `Matter ${environment.vars.string(`type${i}`) ?? \"light\"} device ${i}`;\n const vendorName = \"matter-node.js\";\n const passcode =\n environment.vars.number(`passcode${i}`) ?? deviceStorage.get(`passcode${i}`, defaultPasscode++);\n const discriminator =\n environment.vars.number(`discriminator${i}`) ??\n deviceStorage.get(`discriminator${i}`, defaultDiscriminator++);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = environment.vars.number(`vendorid${i}`) ?? deviceStorage.get(`vendorid${i}`, 0xfff1);\n const productName = `node-matter OnOff-Device ${i}`;\n const productId = environment.vars.number(`productid${i}`) ?? deviceStorage.get(`productid${i}`, 0x8000);\n\n const port = environment.vars.number(`port${i}`) ?? defaultPort++;\n\n const uniqueId =\n environment.vars.string(`uniqueid${i}`) ?? deviceStorage.get(`uniqueid${i}`, `${i}-${Time.nowMs()}`);\n\n // Persist basic data to keep them also on restart\n deviceStorage.set(`passcode${i}`, passcode);\n deviceStorage.set(`discriminator${i}`, discriminator);\n deviceStorage.set(`vendorid${i}`, vendorId);\n deviceStorage.set(`productid${i}`, productId);\n deviceStorage.set(`isSocket${i}`, isSocket);\n deviceStorage.set(`uniqueid${i}`, uniqueId);\n\n devices.push({\n isSocket,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n });\n }\n\n return devices;\n}\n"],
|
5
|
+
"mappings": "AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,OAAO;AAEP,SAAS,6BAA6B;AACtC,SAAS,cAAc,gBAAgB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AACtC,SAAS,UAAU,sBAAsB;AACzC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AACrB,SAAS,gBAAgB;AAEzB,sBAAsB,EAAE;AAExB,MAAM,UAAU,MAAM,iBAAiB;AACvC,SAAS,MAAM,GAAG,MAAM,QAAQ,QAAQ,OAAO;AAC3C,QAAM;AAAA,IACF;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ,IAAI,QAAQ,GAAG;AACf,QAAM,IAAI,MAAM;AAKhB,QAAM,SAAS,MAAM,WAAW,OAAO;AAAA;AAAA,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