@zucker-framework/gateway 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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/NOTICE ADDED
@@ -0,0 +1,22 @@
1
+ Zucker Framework
2
+ Copyright 2026 Lind and Zucker Framework contributors
3
+
4
+ Licensed under the Apache License, Version 2.0. See LICENSE.
5
+
6
+ The framework includes TypeScript adaptations and enhancements of concepts and
7
+ implementations from hsweb-framework and jetlinks-community, both distributed
8
+ under the Apache License, Version 2.0. Individual packages use different subsets
9
+ of the framework. The TypeScript adaptations and Node.js integrations were
10
+ modified for Zucker Framework; they are not the original upstream distribution.
11
+
12
+ hsweb-framework
13
+ https://github.com/hs-web/hsweb-framework
14
+ Copyright 2020 http://hsweb.me
15
+
16
+ jetlinks-community
17
+ https://github.com/jetlinks/jetlinks-community
18
+
19
+ See THIRD_PARTY_NOTICES for license texts and attribution for bundled dependencies
20
+ and reference implementations relevant to this package. External dependencies
21
+ remain subject to their own licenses. This NOTICE is informational and does not
22
+ modify any license or grant rights to upstream trademarks.
@@ -0,0 +1,4 @@
1
+ @zucker-framework/gateway
2
+
3
+ No separately recorded third-party implementation is bundled in this package.
4
+ External dependencies retain their own licenses; see NOTICE for framework attribution.
@@ -0,0 +1,304 @@
1
+ import { Transport } from '@zucker-framework/network';
2
+ import { UpstreamMessage, DownstreamMessage, ThingManager, ThingsDataService } from '@zucker-framework/things';
3
+ import { Logger } from '@nestjs/common';
4
+
5
+ /**
6
+ * 设备会话 — 对应 jetlinks DeviceSession
7
+ *
8
+ * 代表一个已连接设备的网络会话,负责消息的收发与状态跟踪。
9
+ */
10
+
11
+ /**
12
+ * 设备会话状态
13
+ */
14
+ declare enum SessionState {
15
+ /** 会话正常,设备在线 */
16
+ CONNECTED = "connected",
17
+ /** 会话已关闭 */
18
+ CLOSED = "closed",
19
+ /** 会话空闲(超时告警) */
20
+ IDLE = "idle"
21
+ }
22
+ /**
23
+ * 设备会话接口 — 对应 jetlinks DeviceSession
24
+ */
25
+ interface DeviceSession {
26
+ /** 会话唯一 ID */
27
+ readonly sessionId: string;
28
+ /** 关联的设备(物)ID */
29
+ readonly thingId: string;
30
+ /** 所属网关 ID */
31
+ readonly gatewayId: string;
32
+ /** 传输协议 */
33
+ readonly transport: Transport;
34
+ /** 会话创建时间 */
35
+ readonly connectTime: number;
36
+ /** 最后活跃时间 */
37
+ lastPingTime: number;
38
+ /** 当前状态 */
39
+ state: SessionState;
40
+ /**
41
+ * 发送下行消息(原始字节/对象)到设备
42
+ * 对应 jetlinks DeviceSession.send()
43
+ */
44
+ send(payload: unknown): Promise<void>;
45
+ /**
46
+ * 关闭会话
47
+ * 对应 jetlinks DeviceSession.close()
48
+ */
49
+ close(): Promise<void>;
50
+ /**
51
+ * 更新心跳
52
+ * 对应 jetlinks DeviceSession.ping()
53
+ */
54
+ ping(): void;
55
+ /**
56
+ * 是否存活
57
+ * 对应 jetlinks DeviceSession.isAlive()
58
+ */
59
+ isAlive(): boolean;
60
+ }
61
+ /**
62
+ * 子设备会话 — 对应 jetlinks ChildDeviceSession
63
+ *
64
+ * 通过父设备(如网关设备)代理的子设备会话。
65
+ */
66
+ interface ChildDeviceSession extends DeviceSession {
67
+ /** 父设备 ID */
68
+ readonly parentThingId: string;
69
+ }
70
+
71
+ /**
72
+ * 消息编解码器 — 对应 jetlinks ProtocolSupport / MessageCodec
73
+ *
74
+ * 负责原始协议消息 ↔ ThingMessage 的互转。
75
+ * 不同协议(MQTT/HTTP/TCP)提供不同的 Codec 实现。
76
+ */
77
+
78
+ /**
79
+ * 上行消息解码上下文 — 对应 jetlinks MessageDecodeContext
80
+ */
81
+ interface DecodeContext {
82
+ /** 接收到的原始消息 */
83
+ payload: unknown;
84
+ /** 原始主题/路径/端点(MQTT topic、HTTP path 等) */
85
+ topic?: string;
86
+ /** 请求头/消息头 */
87
+ headers?: Record<string, string>;
88
+ /** 关联的设备会话 */
89
+ session: DeviceSession;
90
+ }
91
+ /**
92
+ * 下行消息编码上下文 — 对应 jetlinks MessageEncodeContext
93
+ */
94
+ interface EncodeContext {
95
+ /** 要发送的平台消息 */
96
+ message: DownstreamMessage;
97
+ /** 关联的设备会话 */
98
+ session: DeviceSession;
99
+ }
100
+ /**
101
+ * 编码结果
102
+ */
103
+ interface EncodedMessage {
104
+ /** 编码后的载荷 */
105
+ payload: unknown;
106
+ /** 目标主题/路径 */
107
+ topic?: string;
108
+ /** 附加头信息 */
109
+ headers?: Record<string, string>;
110
+ }
111
+ /**
112
+ * 消息编解码器接口 — 对应 jetlinks DeviceMessageCodec / ProtocolSupport
113
+ */
114
+ interface MessageCodec {
115
+ /**
116
+ * 解码上行消息(原始 → ThingMessage[])
117
+ * 对应 jetlinks DeviceMessageCodec.decode()
118
+ * 一条原始消息可能解析出多条逻辑消息(如批量属性上报)
119
+ */
120
+ decode(context: DecodeContext): Promise<UpstreamMessage[]>;
121
+ /**
122
+ * 编码下行消息(ThingMessage → 原始)
123
+ * 对应 jetlinks DeviceMessageCodec.encode()
124
+ */
125
+ encode(context: EncodeContext): Promise<EncodedMessage>;
126
+ }
127
+ /**
128
+ * 协议支持描述 — 对应 jetlinks ProtocolSupport
129
+ */
130
+ interface ProtocolSupport {
131
+ /** 协议唯一 ID */
132
+ readonly id: string;
133
+ /** 协议名称 */
134
+ readonly name: string;
135
+ /** 支持的传输协议 schema 列表,如 ['mqtt', 'http', 'tcp'] */
136
+ readonly transports: string[];
137
+ /** 获取对应传输协议的编解码器 */
138
+ getCodec(transport: string): MessageCodec | undefined;
139
+ }
140
+ /**
141
+ * 协议注册表 — 对应 jetlinks ProtocolSupportManager
142
+ */
143
+ declare class ProtocolRegistry {
144
+ private readonly protocols;
145
+ register(protocol: ProtocolSupport): void;
146
+ unregister(id: string): void;
147
+ get(id: string): ProtocolSupport | undefined;
148
+ getAll(): ProtocolSupport[];
149
+ }
150
+
151
+ /**
152
+ * 设备网关接口 — 对应 jetlinks DeviceGateway
153
+ *
154
+ * 网关是协议层(network)与业务层(things)的桥接器:
155
+ * - 接收设备连接,建立 DeviceSession
156
+ * - 调用 MessageCodec 解码上行消息,发布到消息总线
157
+ * - 接收下行消息,编码后通过 DeviceSession 发送给设备
158
+ */
159
+
160
+ /**
161
+ * 网关状态
162
+ */
163
+ declare enum GatewayState {
164
+ STARTING = "starting",
165
+ RUNNING = "running",
166
+ PAUSED = "paused",
167
+ STOPPED = "stopped"
168
+ }
169
+ /**
170
+ * 网关配置
171
+ */
172
+ interface DeviceGatewayConfig {
173
+ id: string;
174
+ name: string;
175
+ /** 关联的 network 配置 ID */
176
+ networkId: string;
177
+ /** 使用的协议 ID */
178
+ protocolId: string;
179
+ /** 传输 schema(与 protocol.getCodec(schema) 对应)*/
180
+ transport: string;
181
+ }
182
+ /**
183
+ * 设备网关接口 — 对应 jetlinks DeviceGateway
184
+ */
185
+ interface DeviceGateway {
186
+ readonly config: DeviceGatewayConfig;
187
+ readonly state: GatewayState;
188
+ /** 启动网关 */
189
+ start(): Promise<void>;
190
+ /** 暂停(不再接受新连接,已有连接保持)*/
191
+ pause(): Promise<void>;
192
+ /** 停止网关并关闭所有连接 */
193
+ shutdown(): Promise<void>;
194
+ /** 获取活跃会话数量 */
195
+ getSessionCount(): number;
196
+ /** 获取指定设备的会话 */
197
+ getSession(thingId: string): DeviceSession | undefined;
198
+ /** 发送下行消息到指定设备 */
199
+ sendDownstream(thingId: string, payload: unknown): Promise<void>;
200
+ }
201
+ /**
202
+ * 抽象网关基类 — 提供会话管理 + 消息路由公共逻辑
203
+ * 子类只需实现协议特定的 start/pause/shutdown
204
+ *
205
+ * 对应 jetlinks AbstractDeviceGateway
206
+ */
207
+ declare abstract class AbstractDeviceGateway implements DeviceGateway {
208
+ readonly config: DeviceGatewayConfig;
209
+ protected readonly protocol: ProtocolSupport;
210
+ protected readonly thingManager: ThingManager;
211
+ protected readonly dataService: ThingsDataService;
212
+ protected readonly logger: Logger;
213
+ protected readonly sessions: Map<string, DeviceSession>;
214
+ state: GatewayState;
215
+ constructor(config: DeviceGatewayConfig, protocol: ProtocolSupport, thingManager: ThingManager, dataService: ThingsDataService);
216
+ abstract start(): Promise<void>;
217
+ abstract pause(): Promise<void>;
218
+ abstract shutdown(): Promise<void>;
219
+ getSessionCount(): number;
220
+ getSession(thingId: string): DeviceSession | undefined;
221
+ sendDownstream(thingId: string, payload: unknown): Promise<void>;
222
+ /**
223
+ * 处理设备连接 — 注册会话并触发上线
224
+ */
225
+ protected onSessionConnected(session: DeviceSession): Promise<void>;
226
+ /**
227
+ * 处理设备断开 — 移除会话并触发离线
228
+ */
229
+ protected onSessionClosed(session: DeviceSession): Promise<void>;
230
+ /**
231
+ * 处理上行原始消息 — 解码后路由到对应处理器
232
+ * 对应 jetlinks AbstractDeviceGateway.doMessage()
233
+ */
234
+ protected handleIncoming(context: DecodeContext): Promise<void>;
235
+ /**
236
+ * 将解码后的消息路由到业务处理 — 对应 jetlinks DeviceMessageBus.publish()
237
+ */
238
+ private routeMessage;
239
+ /**
240
+ * 关闭所有会话
241
+ */
242
+ protected closeAllSessions(): Promise<void>;
243
+ }
244
+
245
+ /**
246
+ * HTTP 网关实现
247
+ *
248
+ * 用法:
249
+ * ```typescript
250
+ * const gateway = new HttpDeviceGateway(config, protocol, thingManager, dataService);
251
+ * await gateway.start();
252
+ *
253
+ * // 当收到 HTTP 请求时:
254
+ * await gateway.handleRequest('device-001', requestBody);
255
+ * ```
256
+ */
257
+ declare class HttpDeviceGateway extends AbstractDeviceGateway {
258
+ constructor(config: DeviceGatewayConfig, protocol: ProtocolSupport, thingManager: ThingManager, dataService: ThingsDataService);
259
+ start(): Promise<void>;
260
+ pause(): Promise<void>;
261
+ shutdown(): Promise<void>;
262
+ /**
263
+ * 处理来自设备的 HTTP 请求
264
+ * 由 NestJS Controller 调用
265
+ *
266
+ * @param thingId 设备 ID(从路径参数或认证信息中提取)
267
+ * @param body 请求体
268
+ */
269
+ handleRequest(thingId: string, body: unknown): Promise<void>;
270
+ }
271
+
272
+ declare class GatewayManager {
273
+ readonly protocolRegistry: ProtocolRegistry;
274
+ private readonly logger;
275
+ private readonly gateways;
276
+ constructor(protocolRegistry: ProtocolRegistry);
277
+ register(gateway: DeviceGateway): void;
278
+ unregister(gatewayId: string): void;
279
+ get(gatewayId: string): DeviceGateway | undefined;
280
+ getAll(): DeviceGateway[];
281
+ /** 启动所有已注册的网关 */
282
+ startAll(): Promise<void>;
283
+ /** 停止所有网关 */
284
+ shutdownAll(): Promise<void>;
285
+ /** 汇总统计 */
286
+ getSummary(): {
287
+ total: number;
288
+ running: number;
289
+ stopped: number;
290
+ totalSessions: number;
291
+ };
292
+ }
293
+
294
+ /**
295
+ * GatewayModule — 协议网关 NestJS 模块
296
+ *
297
+ * 提供:
298
+ * - ProtocolRegistry(协议注册表)
299
+ * - GatewayManager(网关生命周期管理)
300
+ */
301
+ declare class GatewayModule {
302
+ }
303
+
304
+ export { AbstractDeviceGateway, type ChildDeviceSession, type DecodeContext, type DeviceGateway, type DeviceGatewayConfig, type DeviceSession, type EncodeContext, type EncodedMessage, GatewayManager, GatewayModule, GatewayState, HttpDeviceGateway, type MessageCodec, ProtocolRegistry, type ProtocolSupport, SessionState };