mqtt-json-rpc 1.3.7 → 2.1.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/mqtt-json-rpc.js DELETED
@@ -1,299 +0,0 @@
1
- /*
2
- ** MQTT-JSON-RPC -- JSON-RPC protocol over MQTT communication
3
- ** Copyright (c) 2018-2023 Dr. Ralf S. Engelschall <rse@engelschall.com>
4
- **
5
- ** Permission is hereby granted, free of charge, to any person obtaining
6
- ** a copy of this software and associated documentation files (the
7
- ** "Software"), to deal in the Software without restriction, including
8
- ** without limitation the rights to use, copy, modify, merge, publish,
9
- ** distribute, sublicense, and/or sell copies of the Software, and to
10
- ** permit persons to whom the Software is furnished to do so, subject to
11
- ** the following conditions:
12
- **
13
- ** The above copyright notice and this permission notice shall be included
14
- ** in all copies or substantial portions of the Software.
15
- **
16
- ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
- ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
- ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
- ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
- ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
- ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
- ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
- */
24
-
25
- /* external requirements */
26
- const UUID = require("pure-uuid")
27
- const JSONRPC = require("jsonrpc-lite")
28
- const Encodr = require("encodr")
29
-
30
- /* the API class */
31
- class API {
32
- constructor (mqtt, options = {}) {
33
- /* determine options */
34
- this.options = Object.assign({
35
- encoding: "json",
36
- timeout: 10 * 1000
37
- }, options)
38
-
39
- /* remember the underlying MQTT Client instance */
40
- this.mqtt = mqtt
41
-
42
- /* make an encoder */
43
- this.encodr = new Encodr(this.options.encoding)
44
-
45
- /* generate unique client identifier */
46
- this.cid = (new UUID(1)).format("std")
47
-
48
- /* internal states */
49
- this.registry = {}
50
- this.requests = {}
51
- this.subscriptions = {}
52
-
53
- /* hook into the MQTT message processing */
54
- this.mqtt.on("message", (topic, message) => {
55
- this._onServer(topic, message)
56
- this._onClient(topic, message)
57
- })
58
- }
59
-
60
- /* just pass-through the entire MQTT Client API */
61
- on (...args) { return this.mqtt.on(...args) }
62
- addListener (...args) { return this.mqtt.addListener(...args) }
63
- removeListener (...args) { return this.mqtt.removeListener(...args) }
64
- publish (...args) { return this.mqtt.publish(...args) }
65
- subscribe (...args) { return this.mqtt.subscribe(...args) }
66
- unsubscribe (...args) { return this.mqtt.unsubscribe(...args) }
67
- end (...args) { return this.mqtt.end(...args) }
68
- removeOutgoingMessage (...args) { return this.mqtt.removeOutgoingMessage(...args) }
69
- reconnect (...args) { return this.mqtt.reconnect(...args) }
70
- handleMessage (...args) { return this.mqtt.handleMessage(...args) }
71
- get connected () { return this.mqtt.connected }
72
- set connected (value) { this.mqtt.connected = value }
73
- getLastMessageId (...args) { return this.mqtt.getLastMessageId(...args) }
74
- get reconnecting () { return this.mqtt.reconnecting }
75
- set reconnecting (value) { this.mqtt.reconnecting = value }
76
-
77
- /*
78
- * RPC server/response side
79
- */
80
-
81
- /* check for the registration of an RPC method */
82
- registered (method) {
83
- return (this.registry[method] !== undefined)
84
- }
85
-
86
- /* register an RPC method */
87
- register (method, callback) {
88
- if (this.registry[method] !== undefined)
89
- throw new Error(`register: method "${method}" already registered`)
90
- this.registry[method] = callback
91
- return new Promise((resolve, reject) => {
92
- this.mqtt.subscribe(`${method}/request`, { qos: 2 }, (err, granted) => {
93
- if (err)
94
- reject(err)
95
- else
96
- resolve(granted)
97
- })
98
- })
99
- }
100
-
101
- /* unregister an RPC method */
102
- unregister (method) {
103
- if (this.registry[method] === undefined)
104
- throw new Error(`unregister: method "${method}" not registered`)
105
- delete this.registry[method]
106
- return new Promise((resolve, reject) => {
107
- this.mqtt.unsubscribe(`${method}/request`, (err, packet) => {
108
- if (err)
109
- reject(err)
110
- else
111
- resolve(packet)
112
- })
113
- })
114
- }
115
-
116
- /* handle incoming RPC method request */
117
- _onServer (topic, message) {
118
- /* ensure we handle only MQTT RPC requests */
119
- let m
120
- if ((m = topic.match(/^(.+)\/request$/)) === null)
121
- return
122
- const method = m[1]
123
-
124
- /* ensure we handle only JSON-RPC payloads */
125
- const parsed = JSONRPC.parseObject(this.encodr.decode(message))
126
- if (!(typeof parsed === "object" && typeof parsed.type === "string"))
127
- return
128
-
129
- /* ensure we handle a consistent JSON-RPC method request */
130
- if (parsed.payload.method !== method)
131
- return
132
-
133
- /* dispatch according to JSON-RPC type */
134
- if (parsed.type === "notification") {
135
- /* just deliver notification */
136
- if (typeof this.registry[method] === "function")
137
- this.registry[method](...parsed.payload.params)
138
- }
139
- else if (parsed.type === "request") {
140
- /* deliver request and send response */
141
- let response
142
- if (typeof this.registry[method] === "function")
143
- response = Promise.resolve().then(() => this.registry[method](...parsed.payload.params))
144
- else
145
- response = Promise.reject(JSONRPC.JsonRpcError.methodNotFound({ method, id: parsed.payload.id }))
146
- response.then((response) => {
147
- /* create JSON-RPC success response */
148
- return JSONRPC.success(parsed.payload.id, response)
149
- }, (error) => {
150
- /* create JSON-RPC error response */
151
- return this._buildError(parsed.payload, error)
152
- }).then((response) => {
153
- /* send MQTT response message */
154
- response = this.encodr.encode(response)
155
- const m = parsed.payload.id.match(/^(.+):.+$/)
156
- const cid = m[1]
157
- this.mqtt.publish(`${method}/response/${cid}`, response, { qos: 0 })
158
- })
159
- }
160
- }
161
-
162
- /*
163
- * RPC client/request side
164
- */
165
-
166
- /* notify peer ("fire and forget") */
167
- notify (method, ...params) {
168
- let request = JSONRPC.notification(method, params)
169
- request = this.encodr.encode(request)
170
- this.mqtt.publish(`${method}/request`, request, { qos: 0 })
171
- }
172
-
173
- /* call peer ("request and response") */
174
- call (method, ...params) {
175
- /* remember callback and create JSON-RPC request */
176
- const rid = `${this.cid}:${(new UUID(1)).format("std")}`
177
- const promise = new Promise((resolve, reject) => {
178
- let timer = setTimeout(() => {
179
- reject(new Error("communication timeout"))
180
- timer = null
181
- }, this.options.timeout)
182
- this.requests[rid] = (err, result) => {
183
- if (timer !== null) {
184
- clearTimeout(timer)
185
- timer = null
186
- }
187
- if (err) reject(err)
188
- else resolve(result)
189
- }
190
- })
191
- let request = JSONRPC.request(rid, method, params)
192
-
193
- /* subscribe for response */
194
- this._responseSubscribe(method)
195
-
196
- /* send MQTT request message */
197
- request = this.encodr.encode(request)
198
- this.mqtt.publish(`${method}/request`, request, { qos: 2 }, (err) => {
199
- if (err) {
200
- /* handle request failure */
201
- this._responseUnsubscribe(method)
202
- this.requests[rid](err, undefined)
203
- }
204
- })
205
-
206
- return promise
207
- }
208
-
209
- /* handle incoming RPC method response */
210
- _onClient (topic, message) {
211
- /* ensure we handle only MQTT RPC responses */
212
- let m
213
- if ((m = topic.match(/^(.+)\/response\/(.+)$/)) === null)
214
- return
215
- const [ , method, cid ] = m
216
-
217
- /* ensure we really handle only MQTT RPC responses for us */
218
- if (cid !== this.cid)
219
- return
220
-
221
- /* ensure we handle only JSON-RPC payloads */
222
- const parsed = JSONRPC.parseObject(this.encodr.decode(message))
223
- if (!(typeof parsed === "object" && typeof parsed.type === "string"))
224
- return
225
-
226
- /* dispatch according to JSON-RPC type */
227
- if (parsed.type === "success" || parsed.type === "error") {
228
- const rid = parsed.payload.id
229
- if (typeof this.requests[rid] === "function") {
230
- /* call callback function */
231
- if (parsed.type === "success")
232
- this.requests[rid](undefined, parsed.payload.result)
233
- else
234
- this.requests[rid](parsed.payload.error, undefined)
235
-
236
- /* unsubscribe from response */
237
- delete this.requests[rid]
238
- this._responseUnsubscribe(method)
239
- }
240
- }
241
- }
242
-
243
- /* subscribe to RPC response */
244
- _responseSubscribe (method) {
245
- const topic = `${method}/response/${this.cid}`
246
- if (this.subscriptions[topic] === undefined) {
247
- this.subscriptions[topic] = 0
248
- this.mqtt.subscribe(topic, { qos: 2 })
249
- }
250
- this.subscriptions[topic]++
251
- }
252
-
253
- /* unsubscribe from RPC response */
254
- _responseUnsubscribe (method) {
255
- const topic = `${method}/response/${this.cid}`
256
- this.subscriptions[topic]--
257
- if (this.subscriptions[topic] === 0) {
258
- delete this.subscriptions[topic]
259
- this.mqtt.unsubscribe(topic)
260
- }
261
- }
262
-
263
- /* determine RPC error */
264
- _buildError (payload, error) {
265
- let rpcError
266
- switch (typeof error) {
267
- case "undefined":
268
- rpcError = new JSONRPC.JsonRpcError("undefined error", 0)
269
- break
270
- case "string":
271
- rpcError = new JSONRPC.JsonRpcError(error, -1)
272
- break
273
- case "number":
274
- case "bigint":
275
- rpcError = new JSONRPC.JsonRpcError("application error", error)
276
- break
277
- case "object":
278
- if (error === null)
279
- rpcError = new JSONRPC.JsonRpcError("undefined error", 0)
280
- else {
281
- if (error instanceof JSONRPC.JsonRpcError)
282
- rpcError = error
283
- else if (error instanceof Error)
284
- rpcError = new JSONRPC.JsonRpcError(error.toString(), -100, error)
285
- else
286
- rpcError = new JSONRPC.JsonRpcError("application error", -100, error)
287
- }
288
- break
289
- default:
290
- rpcError = new JSONRPC.JsonRpcError("unspecified error", 0, { data: error })
291
- break
292
- }
293
- return JSONRPC.error(payload.id, rpcError)
294
- }
295
- }
296
-
297
- /* export the standard way */
298
- module.exports = API
299
-
@@ -1,33 +0,0 @@
1
-
2
- module.exports = function (grunt) {
3
- grunt.loadNpmTasks("grunt-browserify")
4
- grunt.initConfig({
5
- browserify: {
6
- "sample": {
7
- files: {
8
- "sample.bundle.js": [ "./sample.js" ]
9
- },
10
- options: {
11
- transform: [
12
- [ "babelify", {
13
- presets: [
14
- [ "@babel/preset-env", {
15
- "targets": {
16
- "browsers": "last 2 versions, > 1%, ie 11"
17
- }
18
- } ]
19
- ]
20
- } ],
21
- // "aliasify"
22
- ],
23
- browserifyOptions: {
24
- standalone: "Sample",
25
- debug: false
26
- }
27
- }
28
- }
29
- }
30
- })
31
- grunt.registerTask("default", [ "browserify" ])
32
- }
33
-