@project-chip/matter-node.js-examples 0.5.0

Sign up to get free protection for your applications and to get access to all the features.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,215 @@
1
+ # matter-node.js-examples
2
+
3
+ [![license](https://img.shields.io/badge/license-Apache2-green.svg?style=flat)](https://raw.githubusercontent.com/mfucci/node-matter/master/LICENSE)
4
+
5
+ This project provides a set of reference implementations to offer several types of Matter device nodes or also a controller.
6
+
7
+ > This package requires Node 16+ for the required Crypto primitives
8
+
9
+ # matter-node.js Usage examples / Reference implementations
10
+
11
+ To better show how to use the library we provide some reference implementations in the examples directory. They are usable as CLI scripts without changes in the first place but are very simple. They are meant to be used as a starting point for your own implementation, or to experiment with Matter at all in a first place.
12
+
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
+
15
+ ## Installation
16
+
17
+ ### From NPM
18
+
19
+ ```bash
20
+ npm i -g @project-chip/matter-node.js-examples
21
+ ```
22
+
23
+ ### Use from Cloned MatterServer.js Repository
24
+
25
+ When you clone the matter.js repository you can also use matter-node.js. To do this you need to execute `npm install` in the matter.js root directory once to install all dependencies and build all packages.
26
+
27
+ Then after `cd packages/matter-node.js-examples` you can use `npm run matter-device` to run the matter-node.js server. Please see the next section for more details.
28
+
29
+ ## CLI usage
30
+
31
+ ### Common CLI parameter for all examples
32
+ The following CLI parameters are the same for all examples:
33
+
34
+ * -clearstorage: the storage location will be reset on start of the process. The sorage location is set via parameter "-store" (see concrete examples below)
35
+ * -loglevel: the log level to use (default: debug, possible values: fatal, error, warn, info, debug)
36
+ * -logformat: the log format to use (default: ansi (if executed in a shell/tty), else plain, possible values: ansi, plain, html)
37
+
38
+ ### Start a simple Matter Device Node
39
+
40
+ > The code for this example is in [src/examples/DeviceNode.ts](./src/examples/DeviceNode.ts).
41
+
42
+ To run from the build files:
43
+
44
+ ```bash
45
+ matter-device
46
+ ```
47
+
48
+ To run directly from Typescript files with on the fly compilation:
49
+
50
+ ```bash
51
+ npm run matter-device
52
+ ```
53
+
54
+ This starts a MatterServer (DeviceNode) server listening on port 5540 and announce it as socket device.
55
+
56
+ This first version only includes the OnOff cluster (on/off smart thing, like a plug or a bulb).
57
+ You can use -on and -off parameter to run a script to control something.
58
+ For instance, on a Raspberry Pi, this will turn on / off the red LED:
59
+
60
+ ```bash
61
+ matter-device -type socket -on "echo 255 > /sys/class/leds/led1/brightness" -off "echo 0 > /sys/class/leds/led1/brightness"
62
+ ```
63
+
64
+ or when starting from TS files:
65
+
66
+ ```bash
67
+ npm run matter-device -- -type socket -on "echo 255 > /sys/class/leds/led1/brightness" -off "echo 0 > /sys/class/leds/led1/brightness"
68
+ ```
69
+ (Please note the "--" to separate commandline parameters between the npm run and the executed script.
70
+
71
+ The following parameters are available:
72
+ * -passcode: the passcode to use for pairing (default: 20202021)
73
+ * -discriminator: the discriminator to use for pairing (default: 3840, value between 0 and 4095)
74
+ * -vendorid: the vendor ID as number to use for pairing (default: 65521 (0xFFF1))
75
+ * -productid: the product ID as number to use for pairing (default: 32768 (0x8000))
76
+ * -uniqueid: a unique ID for this device to be used in naming and to store structure information (default: ms time now)
77
+ * -type: the device type to use for pairing (default: light, alternative value is "socket")
78
+ * -announceinterface: limit mdns announcements to the provided network interface, e.g. "en0" (default: all interfaces available)
79
+ * -ble: enable BLE support (default: false) If this is enabled the device will announce itself _only_ via BLE if not commissioned and also presents a "Wifi only" device for commissioning to show this feature!
80
+ * -ble-hci-id: Optionally, HCI ID to use (Linux only, default 0)
81
+ * -port: the port to listen on for the device (default: 5540)
82
+ * -store: the storage location (directory) to use for storing the pairing information (default: .device-node). Ideally use names starting with a ".". Delete the directory or provide an alternative name to reset the device
83
+ * -on: the command to run when the device is turned on (see example above)
84
+ * -off: the command to run when the device is turned off (see example above)
85
+
86
+ Additionally, there are some Testing parameters:
87
+ * -ble-wifi-scan-ssid: The Wi-Fi SSID returned by the "ScanNetworks" call of the Wifi Network commissioning cluster used when using BLE commissioning (default: "TestSSID"). Ideally use a really existing SSID that also the commissioner (Apple, Alexa, ...) knows to make it easier to commission. Else you could get errors while commissioning.
88
+ * -ble-wifi-scan-bssid: The Wi-Fi BSSID returned by the "ScanNetworks" call of the Wifi Network commissioning cluster used when using BLE commissioning (default: "00:00:00:00:00:00").
89
+
90
+ ### Start a Matter Bridge
91
+
92
+ > The code for this example is in [src/examples/BridgedDevicesNode.ts](./src/examples/BridgedDevicesNode.ts).
93
+
94
+ A Bridge is used to expose multiple devices at once.
95
+
96
+ The usage and parameter are comparable to above. but the bridge adds support for multiple types and on/off commands:
97
+
98
+ The usage is as above but with modified parameters:
99
+ * -num X: number of devices to expose (default 2)
100
+ * -typeX socket: type of the devices to expose as device number X (default Light bulb)
101
+ * -onX "script": script to run when the device number X is turned on
102
+ * -offX "script": script to run when the device number X is turned off
103
+
104
+ **Please especially use the -uniqueidX parameters to assign unique own IDs to the single deices in order to remember their structure in the bridge. Such an ID should never be reused if you ever remove or add new devices! If you do not use -uniqueidX then the order you added them here is not allowed to ever change.**
105
+
106
+ ```bash
107
+ matter-bridge -num 2 -on1 "echo 255 > /sys/class/leds/led1/brightness" -off1 "echo 0 > /sys/class/leds/led1/brightness" -type2 socket -on2 "echo 255 > /sys/class/leds/led2/brightness" -off2 "echo 0 > /sys/class/leds/led2/brightness"
108
+ ```
109
+
110
+ or when starting from TS files:
111
+
112
+ ```bash
113
+ npm run matter-bridge -- -num 2 -on1 "echo 255 > /sys/class/leds/led1/brightness" -off1 "echo 0 > /sys/class/leds/led1/brightness" -type2 socket -on2 "echo 255 > /sys/class/leds/led2/brightness" -off2 "echo 0 > /sys/class/leds/led2/brightness"
114
+ ```
115
+ (Please note the "--" to separate commandline parameters between the npm run and the executed script.
116
+
117
+ The above command exposes two devices under the bridge, one as light, one as socket and executes the respective commands when the devices are turned on or off.
118
+
119
+ ### Start a Matter Composed Device
120
+
121
+ > The code for this example is in [src/examples/ComposedDeviceNode.ts](./src/examples/ComposedDeviceNode.ts).
122
+
123
+ A composed device is one device with multiple different device types combined. This is useful for devices that have multiple functions, e.g. a light bulb with a temperature sensor.
124
+
125
+ The parameters are like with the bridge but with an added "-type light/socket" parameter to define the type of the composed device itself.
126
+
127
+ ```bash
128
+ matter-composeddevice -type socket -num 2 -on1 "echo 255 > /sys/class/leds/led1/brightness" -off1 "echo 0 > /sys/class/leds/led1/brightness" -type2 socket -on2 "echo 255 > /sys/class/leds/led2/brightness" -off2 "echo 0 > /sys/class/leds/led2/brightness"
129
+ ```
130
+
131
+ or when starting from TS files:
132
+
133
+ ```bash
134
+ npm run matter-composeddevice -- -type socket -num 2 -on1 "echo 255 > /sys/class/leds/led1/brightness" -off1 "echo 0 > /sys/class/leds/led1/brightness" -type2 socket -on2 "echo 255 > /sys/class/leds/led2/brightness" -off2 "echo 0 > /sys/class/leds/led2/brightness"
135
+ ```
136
+ (Please note the "--" to separate commandline parameters between the npm run and the executed script.
137
+
138
+ The above command exposes a composed device with a socket and a light device and executes the respective commands when the devices are turned on or off.
139
+
140
+ ### Start multiple Matter Devices in one process
141
+
142
+ > The code for this example is in [src/examples/MultiDeviceNode.ts](./src/examples/MultiDeviceNode.ts).
143
+
144
+ matter.js also allows it to start multiple devices in one process. With this especially the MDNS functionalities are shared between these processes and it should use less resources. How many devices you acn add in one process depends on the load they produce and how many devices run in the single Node.js thread.
145
+
146
+ The parameters are like with the composed device or bridge.
147
+
148
+ ```bash
149
+ matter-multidevice -type socket -num 2 -on1 "echo 255 > /sys/class/leds/led1/brightness" -off1 "echo 0 > /sys/class/leds/led1/brightness" -type2 socket -on2 "echo 255 > /sys/class/leds/led2/brightness" -off2 "echo 0 > /sys/class/leds/led2/brightness"
150
+ ```
151
+
152
+ or when starting from TS files:
153
+
154
+ ```bash
155
+ npm run matter-multidevice -- -type socket -num 2 -on1 "echo 255 > /sys/class/leds/led1/brightness" -off1 "echo 0 > /sys/class/leds/led1/brightness" -type2 socket -on2 "echo 255 > /sys/class/leds/led2/brightness" -off2 "echo 0 > /sys/class/leds/led2/brightness"
156
+ ```
157
+ (Please note the "--" to separate commandline parameters between the npm run and the executed script.
158
+
159
+ The above command exposes two single light devices (one socket and on light) and executes the respective commands when the devices are turned on or off.
160
+
161
+ ### Start a Matter Controller
162
+
163
+ > The code for this example is in [src/examples/ControllerNode.ts](./src/examples/ControllerNode.ts).
164
+
165
+ **Experimental**
166
+ The current controller implementation is no CLI tool, but shows the pairing of devices and resuming the connection and also showcase the existing low-level controller API. It is just intended to be used for debugging, during development! The code contains some commented-out examples of how to use the low level controller API.
167
+ Please **do not** use this for production, we will replace the API soon!
168
+
169
+ The controller currently is not discovering the device to pair, but directly connects to the IP/port defined bin the command line parameters.
170
+
171
+ To run from the build files:
172
+
173
+ ```bash
174
+ matter-controller -pairingcode 12345678901
175
+ ```
176
+
177
+ To run directly from Typescript files with on the fly compilation:
178
+
179
+ ```bash
180
+ npm run matter-controller -- -pairingcode 12345678901
181
+ ```
182
+
183
+ This will commission a MatterServer device (for debugging/capability showing purpose only for now).
184
+
185
+ The following parameters are available and used to initially commission a device (they can be omitted after this):
186
+ * If the IP and Port of the device is known (should be only the case in testing cases) you can use the following parameters:
187
+ * -ip: the IP address of the device to commission (can be used but discovery via pairingcode or discriminator or also just pin (passode) is most likely better)
188
+ * -port the port of the device to commission (default: 5540)
189
+ * Device identification options:
190
+ * -pairingcode: code to use for pairing (-longDiscriminator and -pin will be ignored) - usually the code below the QR Code on the device or displayed in the app!
191
+ * -longDiscriminator: the discriminator to use for pairing (default: 3840, value between 0 and 4095)
192
+ * -pin: the pin to use for pairing (default: 20202021)
193
+ * When the device to commission is not already in the IP network and also not an Ethernet device commission can be done via ble. In this case the following parameters are used:
194
+ * -ble: enable BLE support (default: false) If this is enabled the controller will try to connect via BLE first (15s timeout) and then via IP if not commissioned yet!
195
+ * -ble-hci-id: Optionally, HCI ID to use (Linux only, default 0)
196
+ * -ble-wifi-ssid: SSID/Name of the Wifi network to connect to - The device will scan especially for this network and commissioning will fail if not found
197
+ * -ble-wifi-credentials: Credentials for the Wifi network to connect to
198
+ * -ble-thread-networkname: Name of the Thread network to connect to - The device will verify that a thread network with this name is reachable by the device and commissioning will fail if not found
199
+ * -ble-thread-operationaldataset: Operational dataset as hex string to use for commissioning (of using OTBR use `ot-ctl dataset active -x` to get the value)
200
+ * Storage configuration parameter
201
+ * -store: the storage location (directory) to use for storing the pairing information (default: .controller-node). Ideally use names with "." at the beginning. Delete the directory or provide an alternative name to reset the controller
202
+ * -clearstorage: the storage location will be reset on start of the process
203
+
204
+ ## Development on basis of the examples
205
+
206
+ The code of the examples is written so that you can use them as basis for your own scripts also outside of this library in your own package. YOu just need to add a dependency to @project-chip/matter-node.js. The examples are already using these imports for more easy adoption.
207
+
208
+ ### Development Device/Composed-device/Bridge
209
+
210
+ The code is structured by comment blocks to better see what belongs to what. It always has code which is just collecting relevant information and data, then the code which is setting up the device and then the code which is starting the device.
211
+
212
+ ## Building
213
+
214
+ * `npm run build`: Build all code and create CommonJS and ES6 variants in dist directory. This will built incrementally and only build the changed files.
215
+ * `npm run build-clean`: Clean the dist directory and build all code from scratch
@@ -0,0 +1,218 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * @license
5
+ * Copyright 2022 The node-matter Authors
6
+ * SPDX-License-Identifier: Apache-2.0
7
+ */
8
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10
+ return new (P || (P = Promise))(function (resolve, reject) {
11
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
12
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
13
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
14
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
15
+ });
16
+ };
17
+ var _a, _b;
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ /**
20
+ * This example shows how to create a device bridge that exposed multiple devices.
21
+ * It can be used as CLI script and starting point for your own device node implementation.
22
+ */
23
+ /**
24
+ * Import needed modules from @project-chip/matter-node.js
25
+ */
26
+ // Include this first to auto-register Crypto, Network and Time Node.js implementations
27
+ const matter_node_js_1 = require("@project-chip/matter-node.js");
28
+ const device_1 = require("@project-chip/matter-node.js/device");
29
+ const log_1 = require("@project-chip/matter-node.js/log");
30
+ const storage_1 = require("@project-chip/matter-node.js/storage");
31
+ const time_1 = require("@project-chip/matter-node.js/time");
32
+ const util_1 = require("@project-chip/matter-node.js/util");
33
+ const datatype_1 = require("@project-chip/matter.js/datatype");
34
+ const logger = log_1.Logger.get("Device");
35
+ (0, util_1.requireMinNodeVersion)(16);
36
+ /** Configure logging */
37
+ switch ((0, util_1.getParameter)("loglevel")) {
38
+ case "fatal":
39
+ log_1.Logger.defaultLogLevel = log_1.Level.FATAL;
40
+ break;
41
+ case "error":
42
+ log_1.Logger.defaultLogLevel = log_1.Level.ERROR;
43
+ break;
44
+ case "warn":
45
+ log_1.Logger.defaultLogLevel = log_1.Level.WARN;
46
+ break;
47
+ case "info":
48
+ log_1.Logger.defaultLogLevel = log_1.Level.INFO;
49
+ break;
50
+ }
51
+ switch ((0, util_1.getParameter)("logformat")) {
52
+ case "plain":
53
+ log_1.Logger.format = log_1.Format.PLAIN;
54
+ break;
55
+ case "html":
56
+ log_1.Logger.format = log_1.Format.HTML;
57
+ break;
58
+ default:
59
+ if ((_a = process.stdin) === null || _a === void 0 ? void 0 : _a.isTTY)
60
+ log_1.Logger.format = log_1.Format.ANSI;
61
+ }
62
+ const storageLocation = (_b = (0, util_1.getParameter)("store")) !== null && _b !== void 0 ? _b : ".device-node";
63
+ const storage = new storage_1.StorageBackendDisk(storageLocation, (0, util_1.hasParameter)("clearstorage"));
64
+ logger.info(`Storage location: ${storageLocation} (Directory)`);
65
+ logger.info('Use the parameter "-store NAME" to specify a different storage location, use -clearstorage to start with an empty storage.');
66
+ class BridgedDevice {
67
+ start() {
68
+ var _a, _b, _c, _d, _e, _f;
69
+ return __awaiter(this, void 0, void 0, function* () {
70
+ logger.info(`node-matter`);
71
+ /**
72
+ * Initialize the storage system.
73
+ *
74
+ * The storage manager is then also used by the Matter server, so this code block in general is required,
75
+ * but you can choose a different storage backend as long as it implements the required API.
76
+ */
77
+ const storageManager = new storage_1.StorageManager(storage);
78
+ yield storageManager.initialize();
79
+ /**
80
+ * Collect all needed data
81
+ *
82
+ * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data
83
+ * come from.
84
+ *
85
+ * Note: This example also uses the initialized storage system to store the device parameter data for convenience
86
+ * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts
87
+ * (so maybe better not ;-)).
88
+ */
89
+ const deviceStorage = storageManager.createContext("Device");
90
+ const deviceName = "Matter Bridge device";
91
+ const deviceType = device_1.DeviceTypes.AGGREGATOR.code;
92
+ const vendorName = "matter-node.js";
93
+ const passcode = (_a = (0, util_1.getIntParameter)("passcode")) !== null && _a !== void 0 ? _a : deviceStorage.get("passcode", 20202021);
94
+ const discriminator = (_b = (0, util_1.getIntParameter)("discriminator")) !== null && _b !== void 0 ? _b : deviceStorage.get("discriminator", 3840);
95
+ // product name / id and vendor id should match what is in the device certificate
96
+ const vendorId = (_c = (0, util_1.getIntParameter)("vendorid")) !== null && _c !== void 0 ? _c : deviceStorage.get("vendorid", 0xfff1);
97
+ const productName = `node-matter OnOff-Bridge`;
98
+ const productId = (_d = (0, util_1.getIntParameter)("productid")) !== null && _d !== void 0 ? _d : deviceStorage.get("productid", 0x8000);
99
+ const netAnnounceInterface = (0, util_1.getParameter)("announceinterface");
100
+ const port = (_e = (0, util_1.getIntParameter)("port")) !== null && _e !== void 0 ? _e : 5540;
101
+ const uniqueId = (_f = (0, util_1.getIntParameter)("uniqueid")) !== null && _f !== void 0 ? _f : deviceStorage.get("uniqueid", time_1.Time.nowMs());
102
+ deviceStorage.set("passcode", passcode);
103
+ deviceStorage.set("discriminator", discriminator);
104
+ deviceStorage.set("vendorid", vendorId);
105
+ deviceStorage.set("productid", productId);
106
+ deviceStorage.set("uniqueid", uniqueId);
107
+ /**
108
+ * Create Matter Server and CommissioningServer Node
109
+ *
110
+ * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a
111
+ * commissioningServer to it and add the just created device instance to it.
112
+ * The CommissioningServer node defines the port where the server listens for the UDP packages of the Matter protocol
113
+ * and initializes deice specific certificates and such.
114
+ *
115
+ * The below logic also adds command handlers for commands of clusters that normally are handled internally
116
+ * like testEventTrigger (General Diagnostic Cluster) that can be implemented with the logic when these commands
117
+ * are called.
118
+ */
119
+ this.matterServer = new matter_node_js_1.MatterServer(storageManager, netAnnounceInterface);
120
+ const commissioningServer = new matter_node_js_1.CommissioningServer({
121
+ port,
122
+ deviceName,
123
+ deviceType,
124
+ passcode,
125
+ discriminator,
126
+ basicInformation: {
127
+ vendorName,
128
+ vendorId: (0, datatype_1.VendorId)(vendorId),
129
+ nodeLabel: productName,
130
+ productName,
131
+ productLabel: productName,
132
+ productId,
133
+ serialNumber: `node-matter-${uniqueId}`,
134
+ },
135
+ });
136
+ /**
137
+ * Create Device instance and add needed Listener
138
+ *
139
+ * Create an instance of the matter device class you want to use.
140
+ * This example uses the OnOffLightDevice or OnOffPluginUnitDevice depending on the value of the type parameter.
141
+ * To execute the on/off scripts defined as parameters a listener for the onOff attribute is registered via the
142
+ * device specific API.
143
+ *
144
+ * The below logic also adds command handlers for commands of clusters that normally are handled device internally
145
+ * like identify that can be implemented with the logic when these commands are called.
146
+ */
147
+ const aggregator = new device_1.Aggregator();
148
+ const numDevices = (0, util_1.getIntParameter)("num") || 2;
149
+ for (let i = 1; i <= numDevices; i++) {
150
+ const onOffDevice = (0, util_1.getParameter)(`type${i}`) === "socket" ? new device_1.OnOffPluginUnitDevice() : new device_1.OnOffLightDevice();
151
+ onOffDevice.addOnOffListener(on => { var _a; return (_a = (0, util_1.commandExecutor)(on ? `on${i}` : `off${i}`)) === null || _a === void 0 ? void 0 : _a(); });
152
+ onOffDevice.addCommandHandler("identify", ({ request: { identifyTime } }) => __awaiter(this, void 0, void 0, function* () {
153
+ return console.log(`Identify called for OnOffDevice ${onOffDevice.name} with id: ${i} and identifyTime: ${identifyTime}`);
154
+ }));
155
+ const name = `OnOff ${onOffDevice instanceof device_1.OnOffPluginUnitDevice ? "Socket" : "Light"} ${i}`;
156
+ aggregator.addBridgedDevice(onOffDevice, {
157
+ nodeLabel: name,
158
+ productName: name,
159
+ productLabel: name,
160
+ serialNumber: `node-matter-${uniqueId}-${i}`,
161
+ reachable: true,
162
+ });
163
+ }
164
+ commissioningServer.addDevice(aggregator);
165
+ this.matterServer.addCommissioningServer(commissioningServer);
166
+ /**
167
+ * Start the Matter Server
168
+ *
169
+ * After everything was plugged together we can start the server. When not delayed announcement is set for the
170
+ * CommissioningServer node then this command also starts the announcement of the device into the network.
171
+ */
172
+ yield this.matterServer.start();
173
+ /**
174
+ * Print Pairing Information
175
+ *
176
+ * If the device is not already commissioned (this info is stored in the storage system) then get and print the
177
+ * pairing details. This includes the QR code that can be scanned by the Matter app to pair the device.
178
+ */
179
+ logger.info("Listening");
180
+ if (!commissioningServer.isCommissioned()) {
181
+ const pairingData = commissioningServer.getPairingCode();
182
+ const { qrCode, qrPairingCode, manualPairingCode } = pairingData;
183
+ console.log(qrCode);
184
+ console.log(`QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`);
185
+ console.log(`Manual pairing code: ${manualPairingCode}`);
186
+ }
187
+ else {
188
+ console.log("Device is already commissioned. Waiting for controllers to connect ...");
189
+ }
190
+ });
191
+ }
192
+ stop() {
193
+ var _a;
194
+ return __awaiter(this, void 0, void 0, function* () {
195
+ yield ((_a = this.matterServer) === null || _a === void 0 ? void 0 : _a.close());
196
+ });
197
+ }
198
+ }
199
+ const device = new BridgedDevice();
200
+ device
201
+ .start()
202
+ .then(() => {
203
+ /* done */
204
+ })
205
+ .catch(err => console.error(err));
206
+ process.on("SIGINT", () => {
207
+ device
208
+ .stop()
209
+ .then(() => {
210
+ // Pragmatic way to make sure the storage is correctly closed before the process ends.
211
+ storage
212
+ .close()
213
+ .then(() => process.exit(0))
214
+ .catch(err => console.error(err));
215
+ })
216
+ .catch(err => console.error(err));
217
+ });
218
+ //# sourceMappingURL=BridgedDevicesNode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BridgedDevicesNode.js","sourceRoot":"","sources":["../../src/examples/BridgedDevicesNode.ts"],"names":[],"mappings":";;AACA;;;;GAIG;;;;;;;;;;;;AAEH;;;GAGG;AAEH;;GAEG;AACH,uFAAuF;AACvF,iEAAiF;AAEjF,gEAAuH;AACvH,0DAAyE;AACzE,kEAA0F;AAC1F,4DAAyD;AACzD,4DAM2C;AAC3C,+DAA4D;AAE5D,MAAM,MAAM,GAAG,YAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AAEpC,IAAA,4BAAqB,EAAC,EAAE,CAAC,CAAC;AAE1B,wBAAwB;AACxB,QAAQ,IAAA,mBAAY,EAAC,UAAU,CAAC,EAAE;IAC9B,KAAK,OAAO;QACR,YAAM,CAAC,eAAe,GAAG,WAAK,CAAC,KAAK,CAAC;QACrC,MAAM;IACV,KAAK,OAAO;QACR,YAAM,CAAC,eAAe,GAAG,WAAK,CAAC,KAAK,CAAC;QACrC,MAAM;IACV,KAAK,MAAM;QACP,YAAM,CAAC,eAAe,GAAG,WAAK,CAAC,IAAI,CAAC;QACpC,MAAM;IACV,KAAK,MAAM;QACP,YAAM,CAAC,eAAe,GAAG,WAAK,CAAC,IAAI,CAAC;QACpC,MAAM;CACb;AAED,QAAQ,IAAA,mBAAY,EAAC,WAAW,CAAC,EAAE;IAC/B,KAAK,OAAO;QACR,YAAM,CAAC,MAAM,GAAG,YAAM,CAAC,KAAK,CAAC;QAC7B,MAAM;IACV,KAAK,MAAM;QACP,YAAM,CAAC,MAAM,GAAG,YAAM,CAAC,IAA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