viziot-mqtt-client-nodejs 1.0.7 → 2.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 +21 -21
- package/README.md +99 -78
- package/dist/index.cjs +192 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +65 -0
- package/dist/index.d.ts +65 -0
- package/dist/index.js +154 -0
- package/dist/index.js.map +1 -0
- package/package.json +66 -22
- package/ViziotMQTT.js +0 -211
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2018 VizIoT.com
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2018 VizIoT.com
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,102 +1,123 @@
|
|
|
1
1
|
# viziot-mqtt-client-nodejs
|
|
2
2
|
|
|
3
|
-
<img src="/logo.png" alt="
|
|
3
|
+
<img src="/logo.png" alt="VizIoT.com" height="200"/>
|
|
4
4
|
|
|
5
|
-
MQTT
|
|
5
|
+
A Promise-based MQTT client for the [VizIoT.com](http://viziot.com) IoT platform. It lets a
|
|
6
|
+
Node.js device send data to VizIoT.com and receive parameter/command updates pushed from the
|
|
7
|
+
dashboard. Written in TypeScript and published with type declarations, so it works out of the
|
|
8
|
+
box in both TypeScript and plain JavaScript (CommonJS or ESM) projects.
|
|
6
9
|
|
|
7
|
-
|
|
8
|
-
|
|
10
|
+
> **Upgrading from 1.x?** Version 2.0.0 is a full rewrite with a breaking, Promise-based API.
|
|
11
|
+
> See [CHANGELOG.md](./CHANGELOG.md) for the migration notes.
|
|
9
12
|
|
|
10
|
-
|
|
13
|
+
## Installation
|
|
11
14
|
|
|
12
|
-
|
|
13
|
-
|
|
15
|
+
```sh
|
|
16
|
+
npm install viziot-mqtt-client-nodejs
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Requires Node.js 18 or later.
|
|
20
|
+
|
|
21
|
+
## Quick start
|
|
14
22
|
|
|
15
|
-
|
|
16
|
-
- отправлять раз в минуту время, случайное число (от 1 до 100), и признак отправки данных.
|
|
17
|
-
- управлять отправкой данных через сайт VizIoT.com.
|
|
23
|
+
### TypeScript / ESM
|
|
18
24
|
|
|
19
|
-
|
|
25
|
+
```ts
|
|
26
|
+
import { VizIoTMQTT } from 'viziot-mqtt-client-nodejs';
|
|
20
27
|
|
|
21
|
-
|
|
22
|
-
'use strict';
|
|
23
|
-
//#ключ и пароль устройства
|
|
24
|
-
let keyDevice = '________________';
|
|
25
|
-
let passDevice = '____________________';
|
|
28
|
+
const client = new VizIoTMQTT(deviceKey, devicePassword);
|
|
26
29
|
|
|
27
|
-
|
|
28
|
-
let idIntervalSend = 0;
|
|
29
|
-
let intervalTime = 60000;
|
|
30
|
+
client.on('error', (error) => console.error(error.message));
|
|
30
31
|
|
|
31
|
-
|
|
32
|
-
let viziotMQTTClient = new viziotMQTT(keyDevice, passDevice);
|
|
32
|
+
await client.connect();
|
|
33
33
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
clearInterval(idIntervalSend);
|
|
37
|
-
idIntervalSend = setInterval(function () {
|
|
38
|
-
sendDataToServer();
|
|
39
|
-
}, intervalTime);
|
|
40
|
-
viziotMQTTClient.startListenCommands(function (parameter, value) {
|
|
41
|
-
if(parameter == "sendTestData"){
|
|
42
|
-
sendTestData = value;
|
|
43
|
-
}
|
|
44
|
-
});
|
|
45
|
-
}
|
|
34
|
+
await client.onCommand((parameter, value) => {
|
|
35
|
+
console.log('Received command:', parameter, value);
|
|
46
36
|
});
|
|
47
37
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
}
|
|
65
|
-
}
|
|
38
|
+
await client.send({ temperature: 21.5 });
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### CommonJS
|
|
42
|
+
|
|
43
|
+
```js
|
|
44
|
+
const { VizIoTMQTT } = require('viziot-mqtt-client-nodejs');
|
|
45
|
+
|
|
46
|
+
const client = new VizIoTMQTT(deviceKey, devicePassword);
|
|
47
|
+
|
|
48
|
+
client.connect().then(async () => {
|
|
49
|
+
await client.onCommand((parameter, value) => {
|
|
50
|
+
console.log('Received command:', parameter, value);
|
|
51
|
+
});
|
|
52
|
+
await client.send({ temperature: 21.5 });
|
|
53
|
+
});
|
|
66
54
|
```
|
|
67
55
|
|
|
56
|
+
Runnable versions of both examples live in [examples/](./examples).
|
|
57
|
+
|
|
58
|
+
## API
|
|
59
|
+
|
|
60
|
+
### `new VizIoTMQTT(deviceKey, devicePassword, brokerUrl?)`
|
|
61
|
+
|
|
62
|
+
- `deviceKey` — device key from the VizIoT.com dashboard.
|
|
63
|
+
- `devicePassword` — device password from the VizIoT.com dashboard.
|
|
64
|
+
- `brokerUrl` — optional, defaults to `mqtt://viziot.com:48651`.
|
|
68
65
|
|
|
69
|
-
|
|
70
|
-
## Описание класса
|
|
66
|
+
Throws a `VizIoTError` (code `INVALID_CREDENTIALS`) if the key or password has an invalid format.
|
|
71
67
|
|
|
72
|
-
|
|
73
|
-
* <a href="#connect"><code>viziotMQTT#<b>connect()</b></code></a>
|
|
74
|
-
* <a href="#sendDataToVizIoT"><code>viziotMQTT#<b>sendDataToVizIoT()</b></code></a>
|
|
75
|
-
* <a href="#startListenCommands"><code>viziotMQTT#<b>startListenCommands()</b></code></a>
|
|
76
|
-
|
|
68
|
+
### `client.connect(): Promise<void>`
|
|
77
69
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
- passDevice: пароль устройства с сайта VizIoT.com
|
|
82
|
-
- mqttHost: не обязательный параметр. По умолчанию "mqtt://viziot.com:48651"
|
|
70
|
+
Connects to the broker. The returned promise resolves on the first successful connection and
|
|
71
|
+
rejects if the initial connection attempt fails (e.g. bad credentials). Automatic reconnection
|
|
72
|
+
after a successful connection is handled internally; observe it via the `reconnect` event.
|
|
83
73
|
|
|
84
|
-
<
|
|
85
|
-
### Подключение к серверу viziotMQTTClient.connect([callback])
|
|
86
|
-
- callback: не обязательный параметр. Если указать, то будет вызван, когда MQTT клиент подключится к серверу.
|
|
74
|
+
### `client.onCommand(listener): Promise<void>`
|
|
87
75
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
76
|
+
Subscribes to parameter changes pushed from the VizIoT.com dashboard and registers `listener` as
|
|
77
|
+
a `command` event handler. `listener` is called with `(parameter: string, value: string)`. Safe
|
|
78
|
+
to call multiple times — the underlying MQTT subscription is only issued once.
|
|
79
|
+
|
|
80
|
+
### `client.send(data): Promise<void>`
|
|
81
|
+
|
|
82
|
+
Sends `data` (a plain object, an array, or a JSON string) to VizIoT.com with QoS 1. Rejects with
|
|
83
|
+
a `VizIoTError` if `data` is empty or not JSON-serializable.
|
|
84
|
+
|
|
85
|
+
### `client.disconnect(): Promise<void>`
|
|
86
|
+
|
|
87
|
+
Closes the connection to the broker.
|
|
88
|
+
|
|
89
|
+
### Events
|
|
90
|
+
|
|
91
|
+
`VizIoTMQTT` extends `EventEmitter` and emits:
|
|
92
|
+
|
|
93
|
+
| Event | Payload | Description |
|
|
94
|
+
| ----------- | ---------------------------------- | ------------------------------------------------- |
|
|
95
|
+
| `connect` | — | Emitted on every (re)connection. |
|
|
96
|
+
| `reconnect` | — | A reconnection attempt has started. |
|
|
97
|
+
| `close` | — | The connection was closed. |
|
|
98
|
+
| `offline` | — | The client went offline. |
|
|
99
|
+
| `error` | `error: Error` | A transport-level error occurred. |
|
|
100
|
+
| `command` | `parameter: string, value: string` | A new parameter value was pushed from VizIoT.com. |
|
|
101
|
+
|
|
102
|
+
### Errors
|
|
103
|
+
|
|
104
|
+
Validation errors thrown by this library are instances of `VizIoTError`, with a `code` of
|
|
105
|
+
`INVALID_CREDENTIALS`, `INVALID_PAYLOAD`, `EMPTY_PAYLOAD`, or `NOT_CONNECTED`. Transport-level
|
|
106
|
+
failures (bad credentials rejected by the broker, network issues, etc.) are surfaced as the
|
|
107
|
+
original `Error` from the underlying [`mqtt`](https://www.npmjs.com/package/mqtt) client.
|
|
108
|
+
|
|
109
|
+
## Development
|
|
110
|
+
|
|
111
|
+
```sh
|
|
112
|
+
npm install
|
|
113
|
+
npm run build # bundle src/ to dist/ (CJS + ESM + .d.ts) with tsup
|
|
114
|
+
npm test # run the vitest suite
|
|
115
|
+
npm run lint # eslint
|
|
116
|
+
npm run format # prettier --write
|
|
117
|
+
```
|
|
100
118
|
|
|
119
|
+
See [CONTRIBUTING.md](./CONTRIBUTING.md) for the release/versioning process.
|
|
101
120
|
|
|
121
|
+
## License
|
|
102
122
|
|
|
123
|
+
MIT — see [LICENSE](./LICENSE).
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
VizIoTError: () => VizIoTError,
|
|
34
|
+
VizIoTMQTT: () => VizIoTMQTT
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(index_exports);
|
|
37
|
+
|
|
38
|
+
// src/client.ts
|
|
39
|
+
var import_node_events = require("events");
|
|
40
|
+
var import_mqtt = __toESM(require("mqtt"), 1);
|
|
41
|
+
|
|
42
|
+
// src/errors.ts
|
|
43
|
+
var VizIoTError = class _VizIoTError extends Error {
|
|
44
|
+
code;
|
|
45
|
+
constructor(code, message) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.name = "VizIoTError";
|
|
48
|
+
this.code = code;
|
|
49
|
+
Object.setPrototypeOf(this, _VizIoTError.prototype);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// src/client.ts
|
|
54
|
+
var DEFAULT_BROKER_URL = "mqtt://viziot.com:48651";
|
|
55
|
+
var DEVICE_KEY_LENGTH = 16;
|
|
56
|
+
var DEVICE_PASSWORD_LENGTH = 20;
|
|
57
|
+
var RECONNECT_PERIOD_MS = 5e3;
|
|
58
|
+
function normalizeCredential(value) {
|
|
59
|
+
return value.replace(/[^A-Za-z0-9]/g, "");
|
|
60
|
+
}
|
|
61
|
+
function serializePayload(data) {
|
|
62
|
+
let payload;
|
|
63
|
+
if (typeof data === "string") {
|
|
64
|
+
try {
|
|
65
|
+
payload = JSON.stringify(JSON.parse(data));
|
|
66
|
+
} catch {
|
|
67
|
+
throw new VizIoTError("INVALID_PAYLOAD", "The data string is not valid JSON.");
|
|
68
|
+
}
|
|
69
|
+
} else if (Array.isArray(data) || typeof data === "object" && data !== null) {
|
|
70
|
+
payload = JSON.stringify(data);
|
|
71
|
+
} else {
|
|
72
|
+
throw new VizIoTError(
|
|
73
|
+
"INVALID_PAYLOAD",
|
|
74
|
+
"The data must be a string, an array, or a plain object."
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
if (payload.length <= 2) {
|
|
78
|
+
throw new VizIoTError("EMPTY_PAYLOAD", 'Refusing to send an empty payload ("{}" / "[]").');
|
|
79
|
+
}
|
|
80
|
+
return payload;
|
|
81
|
+
}
|
|
82
|
+
var VizIoTMQTT = class extends import_node_events.EventEmitter {
|
|
83
|
+
brokerUrl;
|
|
84
|
+
deviceKey;
|
|
85
|
+
devicePassword;
|
|
86
|
+
publishTopic;
|
|
87
|
+
subscribeTopic;
|
|
88
|
+
client = null;
|
|
89
|
+
subscribed = false;
|
|
90
|
+
/**
|
|
91
|
+
* @param deviceKey - device key from the VizIoT.com dashboard
|
|
92
|
+
* @param devicePassword - device password from the VizIoT.com dashboard
|
|
93
|
+
* @param brokerUrl - defaults to `mqtt://viziot.com:48651`
|
|
94
|
+
*/
|
|
95
|
+
constructor(deviceKey, devicePassword, brokerUrl = DEFAULT_BROKER_URL) {
|
|
96
|
+
super();
|
|
97
|
+
const key = normalizeCredential(deviceKey);
|
|
98
|
+
const password = normalizeCredential(devicePassword);
|
|
99
|
+
if (key.length !== DEVICE_KEY_LENGTH || password.length !== DEVICE_PASSWORD_LENGTH) {
|
|
100
|
+
throw new VizIoTError(
|
|
101
|
+
"INVALID_CREDENTIALS",
|
|
102
|
+
"Device key or device password has an invalid format."
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
this.deviceKey = key;
|
|
106
|
+
this.devicePassword = password;
|
|
107
|
+
this.brokerUrl = brokerUrl;
|
|
108
|
+
this.publishTopic = `/devices/${key}/packet`;
|
|
109
|
+
this.subscribeTopic = `/devices/${key}/param/+`;
|
|
110
|
+
}
|
|
111
|
+
/** Connects to the VizIoT.com broker. Resolves once the connection is acknowledged. */
|
|
112
|
+
connect() {
|
|
113
|
+
return new Promise((resolve, reject) => {
|
|
114
|
+
const options = {
|
|
115
|
+
username: this.deviceKey,
|
|
116
|
+
password: this.devicePassword,
|
|
117
|
+
reconnectPeriod: RECONNECT_PERIOD_MS
|
|
118
|
+
};
|
|
119
|
+
const client = import_mqtt.default.connect(this.brokerUrl, options);
|
|
120
|
+
const onFirstConnect = () => {
|
|
121
|
+
client.removeListener("error", onFirstError);
|
|
122
|
+
this.emit("connect");
|
|
123
|
+
resolve();
|
|
124
|
+
};
|
|
125
|
+
const onFirstError = (error) => {
|
|
126
|
+
client.removeListener("connect", onFirstConnect);
|
|
127
|
+
client.end(true);
|
|
128
|
+
reject(error);
|
|
129
|
+
};
|
|
130
|
+
client.once("connect", onFirstConnect);
|
|
131
|
+
client.once("error", onFirstError);
|
|
132
|
+
client.on("reconnect", () => this.emit("reconnect"));
|
|
133
|
+
client.on("close", () => this.emit("close"));
|
|
134
|
+
client.on("offline", () => this.emit("offline"));
|
|
135
|
+
client.on("error", (error) => this.emit("error", error));
|
|
136
|
+
client.on("message", (topic, message) => {
|
|
137
|
+
const parameter = topic.slice(this.subscribeTopic.length - 1);
|
|
138
|
+
this.emit("command", parameter, message.toString());
|
|
139
|
+
});
|
|
140
|
+
this.client = client;
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
/** Ends the connection to the broker. */
|
|
144
|
+
disconnect() {
|
|
145
|
+
return new Promise((resolve, reject) => {
|
|
146
|
+
if (!this.client) {
|
|
147
|
+
resolve();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
this.client.end(false, {}, (error) => error ? reject(error) : resolve());
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Subscribes to parameter changes pushed from the VizIoT.com dashboard and registers
|
|
155
|
+
* `listener` on the `command` event. Safe to call multiple times; the underlying MQTT
|
|
156
|
+
* subscription is only made once.
|
|
157
|
+
*/
|
|
158
|
+
async onCommand(listener) {
|
|
159
|
+
if (!this.client) {
|
|
160
|
+
throw new VizIoTError("NOT_CONNECTED", "Call connect() before subscribing to commands.");
|
|
161
|
+
}
|
|
162
|
+
this.on("command", listener);
|
|
163
|
+
if (this.subscribed) {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
await new Promise((resolve, reject) => {
|
|
167
|
+
this.client.subscribe(this.subscribeTopic, (error) => error ? reject(error) : resolve());
|
|
168
|
+
});
|
|
169
|
+
this.subscribed = true;
|
|
170
|
+
}
|
|
171
|
+
/** Sends an object, array, or JSON string to the VizIoT.com server. */
|
|
172
|
+
async send(data) {
|
|
173
|
+
if (!this.client) {
|
|
174
|
+
throw new VizIoTError("NOT_CONNECTED", "Call connect() before sending data.");
|
|
175
|
+
}
|
|
176
|
+
const payload = serializePayload(data);
|
|
177
|
+
await new Promise((resolve, reject) => {
|
|
178
|
+
this.client.publish(
|
|
179
|
+
this.publishTopic,
|
|
180
|
+
payload,
|
|
181
|
+
{ qos: 1 },
|
|
182
|
+
(error) => error ? reject(error) : resolve()
|
|
183
|
+
);
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
188
|
+
0 && (module.exports = {
|
|
189
|
+
VizIoTError,
|
|
190
|
+
VizIoTMQTT
|
|
191
|
+
});
|
|
192
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/errors.ts"],"sourcesContent":["export { VizIoTMQTT } from './client.js';\nexport type { VizIoTPayload, VizIoTMQTTEventMap } from './client.js';\nexport { VizIoTError } from './errors.js';\nexport type { VizIoTErrorCode } from './errors.js';\n","import { EventEmitter } from 'node:events';\nimport mqtt, { type IClientOptions, type MqttClient } from 'mqtt';\nimport { VizIoTError } from './errors.js';\n\nconst DEFAULT_BROKER_URL = 'mqtt://viziot.com:48651';\nconst DEVICE_KEY_LENGTH = 16;\nconst DEVICE_PASSWORD_LENGTH = 20;\nconst RECONNECT_PERIOD_MS = 5000;\n\n/** Data accepted by {@link VizIoTMQTT.send}: a JSON-serializable object/array, or a JSON string. */\nexport type VizIoTPayload = Record<string, unknown> | unknown[] | string;\n\nexport interface VizIoTMQTTEventMap {\n connect: [];\n reconnect: [];\n close: [];\n offline: [];\n error: [error: Error];\n command: [parameter: string, value: string];\n}\n\nfunction normalizeCredential(value: string): string {\n return value.replace(/[^A-Za-z0-9]/g, '');\n}\n\nfunction serializePayload(data: VizIoTPayload): string {\n let payload: string;\n\n if (typeof data === 'string') {\n try {\n payload = JSON.stringify(JSON.parse(data));\n } catch {\n throw new VizIoTError('INVALID_PAYLOAD', 'The data string is not valid JSON.');\n }\n } else if (Array.isArray(data) || (typeof data === 'object' && data !== null)) {\n payload = JSON.stringify(data);\n } else {\n throw new VizIoTError(\n 'INVALID_PAYLOAD',\n 'The data must be a string, an array, or a plain object.',\n );\n }\n\n if (payload.length <= 2) {\n throw new VizIoTError('EMPTY_PAYLOAD', 'Refusing to send an empty payload (\"{}\" / \"[]\").');\n }\n\n return payload;\n}\n\n/**\n * MQTT client for the VizIoT.com IoT platform.\n *\n * Emits the standard connection lifecycle events (`connect`, `reconnect`, `close`,\n * `offline`, `error`) plus a `command` event whenever the platform pushes a new\n * parameter value to the device.\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -- merged below with `declare interface VizIoTMQTT` to type the inherited EventEmitter methods.\nexport class VizIoTMQTT extends EventEmitter {\n readonly brokerUrl: string;\n\n private readonly deviceKey: string;\n private readonly devicePassword: string;\n private readonly publishTopic: string;\n private readonly subscribeTopic: string;\n private client: MqttClient | null = null;\n private subscribed = false;\n\n /**\n * @param deviceKey - device key from the VizIoT.com dashboard\n * @param devicePassword - device password from the VizIoT.com dashboard\n * @param brokerUrl - defaults to `mqtt://viziot.com:48651`\n */\n constructor(deviceKey: string, devicePassword: string, brokerUrl: string = DEFAULT_BROKER_URL) {\n super();\n\n const key = normalizeCredential(deviceKey);\n const password = normalizeCredential(devicePassword);\n\n if (key.length !== DEVICE_KEY_LENGTH || password.length !== DEVICE_PASSWORD_LENGTH) {\n throw new VizIoTError(\n 'INVALID_CREDENTIALS',\n 'Device key or device password has an invalid format.',\n );\n }\n\n this.deviceKey = key;\n this.devicePassword = password;\n this.brokerUrl = brokerUrl;\n this.publishTopic = `/devices/${key}/packet`;\n this.subscribeTopic = `/devices/${key}/param/+`;\n }\n\n /** Connects to the VizIoT.com broker. Resolves once the connection is acknowledged. */\n connect(): Promise<void> {\n return new Promise((resolve, reject) => {\n const options: IClientOptions = {\n username: this.deviceKey,\n password: this.devicePassword,\n reconnectPeriod: RECONNECT_PERIOD_MS,\n };\n\n const client = mqtt.connect(this.brokerUrl, options);\n\n const onFirstConnect = () => {\n client.removeListener('error', onFirstError);\n this.emit('connect');\n resolve();\n };\n const onFirstError = (error: Error) => {\n client.removeListener('connect', onFirstConnect);\n client.end(true);\n reject(error);\n };\n\n client.once('connect', onFirstConnect);\n client.once('error', onFirstError);\n\n client.on('reconnect', () => this.emit('reconnect'));\n client.on('close', () => this.emit('close'));\n client.on('offline', () => this.emit('offline'));\n client.on('error', (error) => this.emit('error', error));\n client.on('message', (topic, message) => {\n const parameter = topic.slice(this.subscribeTopic.length - 1);\n this.emit('command', parameter, message.toString());\n });\n\n this.client = client;\n });\n }\n\n /** Ends the connection to the broker. */\n disconnect(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!this.client) {\n resolve();\n return;\n }\n this.client.end(false, {}, (error) => (error ? reject(error) : resolve()));\n });\n }\n\n /**\n * Subscribes to parameter changes pushed from the VizIoT.com dashboard and registers\n * `listener` on the `command` event. Safe to call multiple times; the underlying MQTT\n * subscription is only made once.\n */\n async onCommand(listener: (parameter: string, value: string) => void): Promise<void> {\n if (!this.client) {\n throw new VizIoTError('NOT_CONNECTED', 'Call connect() before subscribing to commands.');\n }\n\n this.on('command', listener);\n\n if (this.subscribed) {\n return;\n }\n\n await new Promise<void>((resolve, reject) => {\n this.client!.subscribe(this.subscribeTopic, (error) => (error ? reject(error) : resolve()));\n });\n this.subscribed = true;\n }\n\n /** Sends an object, array, or JSON string to the VizIoT.com server. */\n async send(data: VizIoTPayload): Promise<void> {\n if (!this.client) {\n throw new VizIoTError('NOT_CONNECTED', 'Call connect() before sending data.');\n }\n\n const payload = serializePayload(data);\n\n await new Promise<void>((resolve, reject) => {\n this.client!.publish(this.publishTopic, payload, { qos: 1 }, (error) =>\n error ? reject(error) : resolve(),\n );\n });\n }\n}\n\n// Intentional declaration merging to give EventEmitter's `on`/`once`/`emit` precise,\n// per-event types (the same pattern Node's own type definitions use).\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nexport declare interface VizIoTMQTT {\n on<K extends keyof VizIoTMQTTEventMap>(\n event: K,\n listener: (...args: VizIoTMQTTEventMap[K]) => void,\n ): this;\n once<K extends keyof VizIoTMQTTEventMap>(\n event: K,\n listener: (...args: VizIoTMQTTEventMap[K]) => void,\n ): this;\n emit<K extends keyof VizIoTMQTTEventMap>(event: K, ...args: VizIoTMQTTEventMap[K]): boolean;\n}\n","export type VizIoTErrorCode =\n 'INVALID_CREDENTIALS' | 'INVALID_PAYLOAD' | 'EMPTY_PAYLOAD' | 'NOT_CONNECTED';\n\n/**\n * Error thrown for any misuse of the {@link VizIoTMQTT} client\n * (invalid credentials, invalid payloads, calling methods before `connect()`, etc).\n * Transport-level failures (authentication, network, protocol) are surfaced as-is\n * from the underlying `mqtt` client instead.\n */\nexport class VizIoTError extends Error {\n readonly code: VizIoTErrorCode;\n\n constructor(code: VizIoTErrorCode, message: string) {\n super(message);\n this.name = 'VizIoTError';\n this.code = code;\n Object.setPrototypeOf(this, VizIoTError.prototype);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAA6B;AAC7B,kBAA2D;;;ACQpD,IAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA,EAC5B;AAAA,EAET,YAAY,MAAuB,SAAiB;AAClD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,aAAY,SAAS;AAAA,EACnD;AACF;;;ADdA,IAAM,qBAAqB;AAC3B,IAAM,oBAAoB;AAC1B,IAAM,yBAAyB;AAC/B,IAAM,sBAAsB;AAc5B,SAAS,oBAAoB,OAAuB;AAClD,SAAO,MAAM,QAAQ,iBAAiB,EAAE;AAC1C;AAEA,SAAS,iBAAiB,MAA6B;AACrD,MAAI;AAEJ,MAAI,OAAO,SAAS,UAAU;AAC5B,QAAI;AACF,gBAAU,KAAK,UAAU,KAAK,MAAM,IAAI,CAAC;AAAA,IAC3C,QAAQ;AACN,YAAM,IAAI,YAAY,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AGA,MAAM,KAAK,MAAoC;AAC7C,QAAI,CAAC,KAAK,QAAQ;AAChB,YAAM,IAAI,YAAY,iBAAiB,qCAAqC;AAAA,IAC9E;AAEA,UAAM,UAAU,iBAAiB,IAAI;AAErC,UAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,WAAK,OAAQ;AAAA,QAAQ,KAAK;AAAA,QAAc;AAAA,QAAS,EAAE,KAAK,EAAE;AAAA,QAAG,CAAC,UAC5D,QAAQ,OAAO,KAAK,IAAI,QAAQ;AAAA,MAClC;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":["mqtt"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
|
|
3
|
+
/** Data accepted by {@link VizIoTMQTT.send}: a JSON-serializable object/array, or a JSON string. */
|
|
4
|
+
type VizIoTPayload = Record<string, unknown> | unknown[] | string;
|
|
5
|
+
interface VizIoTMQTTEventMap {
|
|
6
|
+
connect: [];
|
|
7
|
+
reconnect: [];
|
|
8
|
+
close: [];
|
|
9
|
+
offline: [];
|
|
10
|
+
error: [error: Error];
|
|
11
|
+
command: [parameter: string, value: string];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* MQTT client for the VizIoT.com IoT platform.
|
|
15
|
+
*
|
|
16
|
+
* Emits the standard connection lifecycle events (`connect`, `reconnect`, `close`,
|
|
17
|
+
* `offline`, `error`) plus a `command` event whenever the platform pushes a new
|
|
18
|
+
* parameter value to the device.
|
|
19
|
+
*/
|
|
20
|
+
declare class VizIoTMQTT extends EventEmitter {
|
|
21
|
+
readonly brokerUrl: string;
|
|
22
|
+
private readonly deviceKey;
|
|
23
|
+
private readonly devicePassword;
|
|
24
|
+
private readonly publishTopic;
|
|
25
|
+
private readonly subscribeTopic;
|
|
26
|
+
private client;
|
|
27
|
+
private subscribed;
|
|
28
|
+
/**
|
|
29
|
+
* @param deviceKey - device key from the VizIoT.com dashboard
|
|
30
|
+
* @param devicePassword - device password from the VizIoT.com dashboard
|
|
31
|
+
* @param brokerUrl - defaults to `mqtt://viziot.com:48651`
|
|
32
|
+
*/
|
|
33
|
+
constructor(deviceKey: string, devicePassword: string, brokerUrl?: string);
|
|
34
|
+
/** Connects to the VizIoT.com broker. Resolves once the connection is acknowledged. */
|
|
35
|
+
connect(): Promise<void>;
|
|
36
|
+
/** Ends the connection to the broker. */
|
|
37
|
+
disconnect(): Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* Subscribes to parameter changes pushed from the VizIoT.com dashboard and registers
|
|
40
|
+
* `listener` on the `command` event. Safe to call multiple times; the underlying MQTT
|
|
41
|
+
* subscription is only made once.
|
|
42
|
+
*/
|
|
43
|
+
onCommand(listener: (parameter: string, value: string) => void): Promise<void>;
|
|
44
|
+
/** Sends an object, array, or JSON string to the VizIoT.com server. */
|
|
45
|
+
send(data: VizIoTPayload): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
declare interface VizIoTMQTT {
|
|
48
|
+
on<K extends keyof VizIoTMQTTEventMap>(event: K, listener: (...args: VizIoTMQTTEventMap[K]) => void): this;
|
|
49
|
+
once<K extends keyof VizIoTMQTTEventMap>(event: K, listener: (...args: VizIoTMQTTEventMap[K]) => void): this;
|
|
50
|
+
emit<K extends keyof VizIoTMQTTEventMap>(event: K, ...args: VizIoTMQTTEventMap[K]): boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type VizIoTErrorCode = 'INVALID_CREDENTIALS' | 'INVALID_PAYLOAD' | 'EMPTY_PAYLOAD' | 'NOT_CONNECTED';
|
|
54
|
+
/**
|
|
55
|
+
* Error thrown for any misuse of the {@link VizIoTMQTT} client
|
|
56
|
+
* (invalid credentials, invalid payloads, calling methods before `connect()`, etc).
|
|
57
|
+
* Transport-level failures (authentication, network, protocol) are surfaced as-is
|
|
58
|
+
* from the underlying `mqtt` client instead.
|
|
59
|
+
*/
|
|
60
|
+
declare class VizIoTError extends Error {
|
|
61
|
+
readonly code: VizIoTErrorCode;
|
|
62
|
+
constructor(code: VizIoTErrorCode, message: string);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export { VizIoTError, type VizIoTErrorCode, VizIoTMQTT, type VizIoTMQTTEventMap, type VizIoTPayload };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
|
|
3
|
+
/** Data accepted by {@link VizIoTMQTT.send}: a JSON-serializable object/array, or a JSON string. */
|
|
4
|
+
type VizIoTPayload = Record<string, unknown> | unknown[] | string;
|
|
5
|
+
interface VizIoTMQTTEventMap {
|
|
6
|
+
connect: [];
|
|
7
|
+
reconnect: [];
|
|
8
|
+
close: [];
|
|
9
|
+
offline: [];
|
|
10
|
+
error: [error: Error];
|
|
11
|
+
command: [parameter: string, value: string];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* MQTT client for the VizIoT.com IoT platform.
|
|
15
|
+
*
|
|
16
|
+
* Emits the standard connection lifecycle events (`connect`, `reconnect`, `close`,
|
|
17
|
+
* `offline`, `error`) plus a `command` event whenever the platform pushes a new
|
|
18
|
+
* parameter value to the device.
|
|
19
|
+
*/
|
|
20
|
+
declare class VizIoTMQTT extends EventEmitter {
|
|
21
|
+
readonly brokerUrl: string;
|
|
22
|
+
private readonly deviceKey;
|
|
23
|
+
private readonly devicePassword;
|
|
24
|
+
private readonly publishTopic;
|
|
25
|
+
private readonly subscribeTopic;
|
|
26
|
+
private client;
|
|
27
|
+
private subscribed;
|
|
28
|
+
/**
|
|
29
|
+
* @param deviceKey - device key from the VizIoT.com dashboard
|
|
30
|
+
* @param devicePassword - device password from the VizIoT.com dashboard
|
|
31
|
+
* @param brokerUrl - defaults to `mqtt://viziot.com:48651`
|
|
32
|
+
*/
|
|
33
|
+
constructor(deviceKey: string, devicePassword: string, brokerUrl?: string);
|
|
34
|
+
/** Connects to the VizIoT.com broker. Resolves once the connection is acknowledged. */
|
|
35
|
+
connect(): Promise<void>;
|
|
36
|
+
/** Ends the connection to the broker. */
|
|
37
|
+
disconnect(): Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* Subscribes to parameter changes pushed from the VizIoT.com dashboard and registers
|
|
40
|
+
* `listener` on the `command` event. Safe to call multiple times; the underlying MQTT
|
|
41
|
+
* subscription is only made once.
|
|
42
|
+
*/
|
|
43
|
+
onCommand(listener: (parameter: string, value: string) => void): Promise<void>;
|
|
44
|
+
/** Sends an object, array, or JSON string to the VizIoT.com server. */
|
|
45
|
+
send(data: VizIoTPayload): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
declare interface VizIoTMQTT {
|
|
48
|
+
on<K extends keyof VizIoTMQTTEventMap>(event: K, listener: (...args: VizIoTMQTTEventMap[K]) => void): this;
|
|
49
|
+
once<K extends keyof VizIoTMQTTEventMap>(event: K, listener: (...args: VizIoTMQTTEventMap[K]) => void): this;
|
|
50
|
+
emit<K extends keyof VizIoTMQTTEventMap>(event: K, ...args: VizIoTMQTTEventMap[K]): boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type VizIoTErrorCode = 'INVALID_CREDENTIALS' | 'INVALID_PAYLOAD' | 'EMPTY_PAYLOAD' | 'NOT_CONNECTED';
|
|
54
|
+
/**
|
|
55
|
+
* Error thrown for any misuse of the {@link VizIoTMQTT} client
|
|
56
|
+
* (invalid credentials, invalid payloads, calling methods before `connect()`, etc).
|
|
57
|
+
* Transport-level failures (authentication, network, protocol) are surfaced as-is
|
|
58
|
+
* from the underlying `mqtt` client instead.
|
|
59
|
+
*/
|
|
60
|
+
declare class VizIoTError extends Error {
|
|
61
|
+
readonly code: VizIoTErrorCode;
|
|
62
|
+
constructor(code: VizIoTErrorCode, message: string);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export { VizIoTError, type VizIoTErrorCode, VizIoTMQTT, type VizIoTMQTTEventMap, type VizIoTPayload };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// src/client.ts
|
|
2
|
+
import { EventEmitter } from "events";
|
|
3
|
+
import mqtt from "mqtt";
|
|
4
|
+
|
|
5
|
+
// src/errors.ts
|
|
6
|
+
var VizIoTError = class _VizIoTError extends Error {
|
|
7
|
+
code;
|
|
8
|
+
constructor(code, message) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "VizIoTError";
|
|
11
|
+
this.code = code;
|
|
12
|
+
Object.setPrototypeOf(this, _VizIoTError.prototype);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// src/client.ts
|
|
17
|
+
var DEFAULT_BROKER_URL = "mqtt://viziot.com:48651";
|
|
18
|
+
var DEVICE_KEY_LENGTH = 16;
|
|
19
|
+
var DEVICE_PASSWORD_LENGTH = 20;
|
|
20
|
+
var RECONNECT_PERIOD_MS = 5e3;
|
|
21
|
+
function normalizeCredential(value) {
|
|
22
|
+
return value.replace(/[^A-Za-z0-9]/g, "");
|
|
23
|
+
}
|
|
24
|
+
function serializePayload(data) {
|
|
25
|
+
let payload;
|
|
26
|
+
if (typeof data === "string") {
|
|
27
|
+
try {
|
|
28
|
+
payload = JSON.stringify(JSON.parse(data));
|
|
29
|
+
} catch {
|
|
30
|
+
throw new VizIoTError("INVALID_PAYLOAD", "The data string is not valid JSON.");
|
|
31
|
+
}
|
|
32
|
+
} else if (Array.isArray(data) || typeof data === "object" && data !== null) {
|
|
33
|
+
payload = JSON.stringify(data);
|
|
34
|
+
} else {
|
|
35
|
+
throw new VizIoTError(
|
|
36
|
+
"INVALID_PAYLOAD",
|
|
37
|
+
"The data must be a string, an array, or a plain object."
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
if (payload.length <= 2) {
|
|
41
|
+
throw new VizIoTError("EMPTY_PAYLOAD", 'Refusing to send an empty payload ("{}" / "[]").');
|
|
42
|
+
}
|
|
43
|
+
return payload;
|
|
44
|
+
}
|
|
45
|
+
var VizIoTMQTT = class extends EventEmitter {
|
|
46
|
+
brokerUrl;
|
|
47
|
+
deviceKey;
|
|
48
|
+
devicePassword;
|
|
49
|
+
publishTopic;
|
|
50
|
+
subscribeTopic;
|
|
51
|
+
client = null;
|
|
52
|
+
subscribed = false;
|
|
53
|
+
/**
|
|
54
|
+
* @param deviceKey - device key from the VizIoT.com dashboard
|
|
55
|
+
* @param devicePassword - device password from the VizIoT.com dashboard
|
|
56
|
+
* @param brokerUrl - defaults to `mqtt://viziot.com:48651`
|
|
57
|
+
*/
|
|
58
|
+
constructor(deviceKey, devicePassword, brokerUrl = DEFAULT_BROKER_URL) {
|
|
59
|
+
super();
|
|
60
|
+
const key = normalizeCredential(deviceKey);
|
|
61
|
+
const password = normalizeCredential(devicePassword);
|
|
62
|
+
if (key.length !== DEVICE_KEY_LENGTH || password.length !== DEVICE_PASSWORD_LENGTH) {
|
|
63
|
+
throw new VizIoTError(
|
|
64
|
+
"INVALID_CREDENTIALS",
|
|
65
|
+
"Device key or device password has an invalid format."
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
this.deviceKey = key;
|
|
69
|
+
this.devicePassword = password;
|
|
70
|
+
this.brokerUrl = brokerUrl;
|
|
71
|
+
this.publishTopic = `/devices/${key}/packet`;
|
|
72
|
+
this.subscribeTopic = `/devices/${key}/param/+`;
|
|
73
|
+
}
|
|
74
|
+
/** Connects to the VizIoT.com broker. Resolves once the connection is acknowledged. */
|
|
75
|
+
connect() {
|
|
76
|
+
return new Promise((resolve, reject) => {
|
|
77
|
+
const options = {
|
|
78
|
+
username: this.deviceKey,
|
|
79
|
+
password: this.devicePassword,
|
|
80
|
+
reconnectPeriod: RECONNECT_PERIOD_MS
|
|
81
|
+
};
|
|
82
|
+
const client = mqtt.connect(this.brokerUrl, options);
|
|
83
|
+
const onFirstConnect = () => {
|
|
84
|
+
client.removeListener("error", onFirstError);
|
|
85
|
+
this.emit("connect");
|
|
86
|
+
resolve();
|
|
87
|
+
};
|
|
88
|
+
const onFirstError = (error) => {
|
|
89
|
+
client.removeListener("connect", onFirstConnect);
|
|
90
|
+
client.end(true);
|
|
91
|
+
reject(error);
|
|
92
|
+
};
|
|
93
|
+
client.once("connect", onFirstConnect);
|
|
94
|
+
client.once("error", onFirstError);
|
|
95
|
+
client.on("reconnect", () => this.emit("reconnect"));
|
|
96
|
+
client.on("close", () => this.emit("close"));
|
|
97
|
+
client.on("offline", () => this.emit("offline"));
|
|
98
|
+
client.on("error", (error) => this.emit("error", error));
|
|
99
|
+
client.on("message", (topic, message) => {
|
|
100
|
+
const parameter = topic.slice(this.subscribeTopic.length - 1);
|
|
101
|
+
this.emit("command", parameter, message.toString());
|
|
102
|
+
});
|
|
103
|
+
this.client = client;
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
/** Ends the connection to the broker. */
|
|
107
|
+
disconnect() {
|
|
108
|
+
return new Promise((resolve, reject) => {
|
|
109
|
+
if (!this.client) {
|
|
110
|
+
resolve();
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
this.client.end(false, {}, (error) => error ? reject(error) : resolve());
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Subscribes to parameter changes pushed from the VizIoT.com dashboard and registers
|
|
118
|
+
* `listener` on the `command` event. Safe to call multiple times; the underlying MQTT
|
|
119
|
+
* subscription is only made once.
|
|
120
|
+
*/
|
|
121
|
+
async onCommand(listener) {
|
|
122
|
+
if (!this.client) {
|
|
123
|
+
throw new VizIoTError("NOT_CONNECTED", "Call connect() before subscribing to commands.");
|
|
124
|
+
}
|
|
125
|
+
this.on("command", listener);
|
|
126
|
+
if (this.subscribed) {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
await new Promise((resolve, reject) => {
|
|
130
|
+
this.client.subscribe(this.subscribeTopic, (error) => error ? reject(error) : resolve());
|
|
131
|
+
});
|
|
132
|
+
this.subscribed = true;
|
|
133
|
+
}
|
|
134
|
+
/** Sends an object, array, or JSON string to the VizIoT.com server. */
|
|
135
|
+
async send(data) {
|
|
136
|
+
if (!this.client) {
|
|
137
|
+
throw new VizIoTError("NOT_CONNECTED", "Call connect() before sending data.");
|
|
138
|
+
}
|
|
139
|
+
const payload = serializePayload(data);
|
|
140
|
+
await new Promise((resolve, reject) => {
|
|
141
|
+
this.client.publish(
|
|
142
|
+
this.publishTopic,
|
|
143
|
+
payload,
|
|
144
|
+
{ qos: 1 },
|
|
145
|
+
(error) => error ? reject(error) : resolve()
|
|
146
|
+
);
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
export {
|
|
151
|
+
VizIoTError,
|
|
152
|
+
VizIoTMQTT
|
|
153
|
+
};
|
|
154
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/errors.ts"],"sourcesContent":["import { EventEmitter } from 'node:events';\nimport mqtt, { type IClientOptions, type MqttClient } from 'mqtt';\nimport { VizIoTError } from './errors.js';\n\nconst DEFAULT_BROKER_URL = 'mqtt://viziot.com:48651';\nconst DEVICE_KEY_LENGTH = 16;\nconst DEVICE_PASSWORD_LENGTH = 20;\nconst RECONNECT_PERIOD_MS = 5000;\n\n/** Data accepted by {@link VizIoTMQTT.send}: a JSON-serializable object/array, or a JSON string. */\nexport type VizIoTPayload = Record<string, unknown> | unknown[] | string;\n\nexport interface VizIoTMQTTEventMap {\n connect: [];\n reconnect: [];\n close: [];\n offline: [];\n error: [error: Error];\n command: [parameter: string, value: string];\n}\n\nfunction normalizeCredential(value: string): string {\n return value.replace(/[^A-Za-z0-9]/g, '');\n}\n\nfunction serializePayload(data: VizIoTPayload): string {\n let payload: string;\n\n if (typeof data === 'string') {\n try {\n payload = JSON.stringify(JSON.parse(data));\n } catch {\n throw new VizIoTError('INVALID_PAYLOAD', 'The data string is not valid JSON.');\n }\n } else if (Array.isArray(data) || (typeof data === 'object' && data !== null)) {\n payload = JSON.stringify(data);\n } else {\n throw new VizIoTError(\n 'INVALID_PAYLOAD',\n 'The data must be a string, an array, or a plain object.',\n );\n }\n\n if (payload.length <= 2) {\n throw new VizIoTError('EMPTY_PAYLOAD', 'Refusing to send an empty payload (\"{}\" / \"[]\").');\n }\n\n return payload;\n}\n\n/**\n * MQTT client for the VizIoT.com IoT platform.\n *\n * Emits the standard connection lifecycle events (`connect`, `reconnect`, `close`,\n * `offline`, `error`) plus a `command` event whenever the platform pushes a new\n * parameter value to the device.\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -- merged below with `declare interface VizIoTMQTT` to type the inherited EventEmitter methods.\nexport class VizIoTMQTT extends EventEmitter {\n readonly brokerUrl: string;\n\n private readonly deviceKey: string;\n private readonly devicePassword: string;\n private readonly publishTopic: string;\n private readonly subscribeTopic: string;\n private client: MqttClient | null = null;\n private subscribed = false;\n\n /**\n * @param deviceKey - device key from the VizIoT.com dashboard\n * @param devicePassword - device password from the VizIoT.com dashboard\n * @param brokerUrl - defaults to `mqtt://viziot.com:48651`\n */\n constructor(deviceKey: string, devicePassword: string, brokerUrl: string = DEFAULT_BROKER_URL) {\n super();\n\n const key = normalizeCredential(deviceKey);\n const password = normalizeCredential(devicePassword);\n\n if (key.length !== DEVICE_KEY_LENGTH || password.length !== DEVICE_PASSWORD_LENGTH) {\n throw new VizIoTError(\n 'INVALID_CREDENTIALS',\n 'Device key or device password has an invalid format.',\n );\n }\n\n this.deviceKey = key;\n this.devicePassword = password;\n this.brokerUrl = brokerUrl;\n this.publishTopic = `/devices/${key}/packet`;\n this.subscribeTopic = `/devices/${key}/param/+`;\n }\n\n /** Connects to the VizIoT.com broker. Resolves once the connection is acknowledged. */\n connect(): Promise<void> {\n return new Promise((resolve, reject) => {\n const options: IClientOptions = {\n username: this.deviceKey,\n password: this.devicePassword,\n reconnectPeriod: RECONNECT_PERIOD_MS,\n };\n\n const client = mqtt.connect(this.brokerUrl, options);\n\n const onFirstConnect = () => {\n client.removeListener('error', onFirstError);\n this.emit('connect');\n resolve();\n };\n const onFirstError = (error: Error) => {\n client.removeListener('connect', onFirstConnect);\n client.end(true);\n reject(error);\n };\n\n client.once('connect', onFirstConnect);\n client.once('error', onFirstError);\n\n client.on('reconnect', () => this.emit('reconnect'));\n client.on('close', () => this.emit('close'));\n client.on('offline', () => this.emit('offline'));\n client.on('error', (error) => this.emit('error', error));\n client.on('message', (topic, message) => {\n const parameter = topic.slice(this.subscribeTopic.length - 1);\n this.emit('command', parameter, message.toString());\n });\n\n this.client = client;\n });\n }\n\n /** Ends the connection to the broker. */\n disconnect(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!this.client) {\n resolve();\n return;\n }\n this.client.end(false, {}, (error) => (error ? reject(error) : resolve()));\n });\n }\n\n /**\n * Subscribes to parameter changes pushed from the VizIoT.com dashboard and registers\n * `listener` on the `command` event. Safe to call multiple times; the underlying MQTT\n * subscription is only made once.\n */\n async onCommand(listener: (parameter: string, value: string) => void): Promise<void> {\n if (!this.client) {\n throw new VizIoTError('NOT_CONNECTED', 'Call connect() before subscribing to commands.');\n }\n\n this.on('command', listener);\n\n if (this.subscribed) {\n return;\n }\n\n await new Promise<void>((resolve, reject) => {\n this.client!.subscribe(this.subscribeTopic, (error) => (error ? reject(error) : resolve()));\n });\n this.subscribed = true;\n }\n\n /** Sends an object, array, or JSON string to the VizIoT.com server. */\n async send(data: VizIoTPayload): Promise<void> {\n if (!this.client) {\n throw new VizIoTError('NOT_CONNECTED', 'Call connect() before sending data.');\n }\n\n const payload = serializePayload(data);\n\n await new Promise<void>((resolve, reject) => {\n this.client!.publish(this.publishTopic, payload, { qos: 1 }, (error) =>\n error ? reject(error) : resolve(),\n );\n });\n }\n}\n\n// Intentional declaration merging to give EventEmitter's `on`/`once`/`emit` precise,\n// per-event types (the same pattern Node's own type definitions use).\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nexport declare interface VizIoTMQTT {\n on<K extends keyof VizIoTMQTTEventMap>(\n event: K,\n listener: (...args: VizIoTMQTTEventMap[K]) => void,\n ): this;\n once<K extends keyof VizIoTMQTTEventMap>(\n event: K,\n listener: (...args: VizIoTMQTTEventMap[K]) => void,\n ): this;\n emit<K extends keyof VizIoTMQTTEventMap>(event: K, ...args: VizIoTMQTTEventMap[K]): boolean;\n}\n","export type VizIoTErrorCode =\n 'INVALID_CREDENTIALS' | 'INVALID_PAYLOAD' | 'EMPTY_PAYLOAD' | 'NOT_CONNECTED';\n\n/**\n * Error thrown for any misuse of the {@link VizIoTMQTT} client\n * (invalid credentials, invalid payloads, calling methods before `connect()`, etc).\n * Transport-level failures (authentication, network, protocol) are surfaced as-is\n * from the underlying `mqtt` client instead.\n */\nexport class VizIoTError extends Error {\n readonly code: VizIoTErrorCode;\n\n constructor(code: VizIoTErrorCode, message: string) {\n super(message);\n this.name = 'VizIoTError';\n this.code = code;\n Object.setPrototypeOf(this, VizIoTError.prototype);\n }\n}\n"],"mappings":";AAAA,SAAS,oBAAoB;AAC7B,OAAO,UAAoD;;;ACQpD,IAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA,EAC5B;AAAA,EAET,YAAY,MAAuB,SAAiB;AAClD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,aAAY,SAAS;AAAA,EACnD;AACF;;;ADdA,IAAM,qBAAqB;AAC3B,IAAM,oBAAoB;AAC1B,IAAM,yBAAyB;AAC/B,IAAM,sBAAsB;AAc5B,SAAS,oBAAoB,OAAuB;AAClD,SAAO,MAAM,QAAQ,iBAAiB,EAAE;AAC1C;AAEA,SAAS,iBAAiB,MAA6B;AACrD,MAAI;AAEJ,MAAI,OAAO,SAAS,UAAU;AAC5B,QAAI;AACF,gBAAU,KAAK,UAAU,KAAK,MAAM,IAAI,CAAC;AAAA,IAC3C,QAAQ;AACN,YAAM,IAAI,YAAY,mBAAmB,oCAAoC;AAAA,IAC/E;AAAA,EACF,WAAW,MAAM,QAAQ,IAAI,KAAM,OAAO,SAAS,YAAY,SAAS,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AC9E;AAEA,UAAM,UAAU,iBAAiB,IAAI;AAErC,UAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,WAAK,OAAQ;AAAA,QAAQ,KAAK;AAAA,QAAc;AAAA,QAAS,EAAE,KAAK,EAAE;AAAA,QAAG,CAAC,UAC5D,QAAQ,OAAO,KAAK,IAAI,QAAQ;AAAA,MAClC;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,25 +1,69 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
"
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
"keywords": [
|
|
17
|
-
"mqtt client",
|
|
18
|
-
"viziot client",
|
|
19
|
-
"viziot mqtt client",
|
|
20
|
-
"viziot mqtt client for Node.JS"
|
|
21
|
-
],
|
|
22
|
-
"dependencies": {
|
|
23
|
-
"mqtt": "^2.18.8"
|
|
2
|
+
"name": "viziot-mqtt-client-nodejs",
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Promise-based MQTT client for the VizIoT.com IoT platform, written in TypeScript with first-class support for both TypeScript and JavaScript (CommonJS/ESM) projects.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Trunov Alexandr <viziot.com@gmail.com> (http://viziot.com)",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./dist/index.cjs",
|
|
9
|
+
"module": "./dist/index.js",
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js",
|
|
15
|
+
"require": "./dist/index.cjs"
|
|
24
16
|
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"logo.png"
|
|
21
|
+
],
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=18"
|
|
24
|
+
},
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "tsup",
|
|
28
|
+
"dev": "tsup --watch",
|
|
29
|
+
"typecheck": "tsc --noEmit",
|
|
30
|
+
"test": "vitest run",
|
|
31
|
+
"test:watch": "vitest",
|
|
32
|
+
"test:coverage": "vitest run --coverage",
|
|
33
|
+
"lint": "eslint .",
|
|
34
|
+
"format": "prettier --write .",
|
|
35
|
+
"format:check": "prettier --check .",
|
|
36
|
+
"prepublishOnly": "npm run lint && npm run typecheck && npm run test && npm run build"
|
|
37
|
+
},
|
|
38
|
+
"homepage": "http://VizIoT.com",
|
|
39
|
+
"repository": {
|
|
40
|
+
"type": "git",
|
|
41
|
+
"url": "git+https://github.com/VizIoT-com/viziot-mqtt-client-nodejs.git"
|
|
42
|
+
},
|
|
43
|
+
"bugs": {
|
|
44
|
+
"url": "https://github.com/VizIoT-com/viziot-mqtt-client-nodejs/issues"
|
|
45
|
+
},
|
|
46
|
+
"keywords": [
|
|
47
|
+
"mqtt",
|
|
48
|
+
"mqtt-client",
|
|
49
|
+
"iot",
|
|
50
|
+
"viziot",
|
|
51
|
+
"typescript"
|
|
52
|
+
],
|
|
53
|
+
"dependencies": {
|
|
54
|
+
"mqtt": "^5.16.0"
|
|
55
|
+
},
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@eslint/js": "^10.0.1",
|
|
58
|
+
"@types/node": "^22.20.3",
|
|
59
|
+
"@vitest/coverage-v8": "^5.0.1",
|
|
60
|
+
"eslint": "^10.10.0",
|
|
61
|
+
"eslint-config-prettier": "^10.1.8",
|
|
62
|
+
"globals": "^17.12.0",
|
|
63
|
+
"prettier": "^3.9.7",
|
|
64
|
+
"tsup": "^8.5.1",
|
|
65
|
+
"typescript": "^5.9.3",
|
|
66
|
+
"typescript-eslint": "^8.70.0",
|
|
67
|
+
"vitest": "^5.0.1"
|
|
68
|
+
}
|
|
25
69
|
}
|
package/ViziotMQTT.js
DELETED
|
@@ -1,211 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
// ==================================================================================
|
|
3
|
-
// VizIoTMQTT.js
|
|
4
|
-
// ----------------------------------------------------------------------------------
|
|
5
|
-
// Description: MQTT client node.js for web site VizIoT.com
|
|
6
|
-
// Copyright: (c) 2017 - 2018
|
|
7
|
-
// Author: VizIoT.com
|
|
8
|
-
// ----------------------------------------------------------------------------------
|
|
9
|
-
// Contributors: Trunov Alexandr
|
|
10
|
-
// ----------------------------------------------------------------------------------
|
|
11
|
-
// License: MIT
|
|
12
|
-
// ==================================================================================
|
|
13
|
-
|
|
14
|
-
const defaultHost = 'mqtt://viziot.com:48651';
|
|
15
|
-
let mqtt = require('mqtt');
|
|
16
|
-
var errorsVizIoT = {
|
|
17
|
-
0: '',
|
|
18
|
-
1: 'Ключ или пароль устройства записаны в неправильном формате',
|
|
19
|
-
2: "Ошибка! Параметр не является массивом или объектом",
|
|
20
|
-
3: "Ошибка! Данные для отправки не могут == null",
|
|
21
|
-
4: "Ошибка! Параметр не является массивом или объектом",
|
|
22
|
-
5: "Ошибка! Попытка отправить пустые данные",
|
|
23
|
-
6: "Ошибка! Не указан callback"
|
|
24
|
-
|
|
25
|
-
};
|
|
26
|
-
var errorsMQTT = {
|
|
27
|
-
0: '',
|
|
28
|
-
1: 'Unacceptable protocol version',
|
|
29
|
-
2: 'Identifier rejected',
|
|
30
|
-
3: 'Server unavailable',
|
|
31
|
-
4: 'Bad username or password',
|
|
32
|
-
5: 'Ошибка авторизации. Проверьте ключ и пароль устройства.',
|
|
33
|
-
16: 'No matching subscribers',
|
|
34
|
-
17: 'No subscription existed',
|
|
35
|
-
128: 'Unspecified error',
|
|
36
|
-
129: 'Malformed Packet',
|
|
37
|
-
130: 'Protocol Error',
|
|
38
|
-
131: 'Implementation specific error',
|
|
39
|
-
132: 'Unsupported Protocol Version',
|
|
40
|
-
133: 'Client Identifier not valid',
|
|
41
|
-
134: 'Bad User Name or Password',
|
|
42
|
-
135: 'Not authorized',
|
|
43
|
-
136: 'Server unavailable',
|
|
44
|
-
137: 'Server busy',
|
|
45
|
-
138: 'Banned',
|
|
46
|
-
139: 'Server shutting down',
|
|
47
|
-
140: 'Bad authentication method',
|
|
48
|
-
141: 'Keep Alive timeout',
|
|
49
|
-
142: 'Session taken over',
|
|
50
|
-
143: 'Topic Filter invalid',
|
|
51
|
-
144: 'Topic Name invalid',
|
|
52
|
-
145: 'Packet identifier in use',
|
|
53
|
-
146: 'Packet Identifier not found',
|
|
54
|
-
147: 'Receive Maximum exceeded',
|
|
55
|
-
148: 'Topic Alias invalid',
|
|
56
|
-
149: 'Packet too large',
|
|
57
|
-
150: 'Message rate too high',
|
|
58
|
-
151: 'Quota exceeded',
|
|
59
|
-
152: 'Administrative action',
|
|
60
|
-
153: 'Payload format invalid',
|
|
61
|
-
154: 'Retain not supported',
|
|
62
|
-
155: 'QoS not supported',
|
|
63
|
-
156: 'Use another server',
|
|
64
|
-
157: 'Server moved',
|
|
65
|
-
158: 'Shared Subscriptions not supported',
|
|
66
|
-
159: 'Connection rate exceeded',
|
|
67
|
-
160: 'Maximum connect time',
|
|
68
|
-
161: 'Subscription Identifiers not supported',
|
|
69
|
-
162: 'Wildcard Subscriptions not supported'
|
|
70
|
-
};
|
|
71
|
-
module.exports = class VizIoTMQTT {
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Инициализация Объекта VizIoTMQTT
|
|
75
|
-
* @param deviceKey - ключ устройства с сайта VizIoT.com
|
|
76
|
-
* @param devicePass - пароль устройства с сайта VizIoT.com
|
|
77
|
-
* @param mqttHost - можно не указывать. По умолчанию "mqtt://viziot.com:48651"
|
|
78
|
-
*/
|
|
79
|
-
constructor(deviceKey, devicePass, mqttHost) {
|
|
80
|
-
if(mqttHost == undefined){
|
|
81
|
-
this.hostBroker = defaultHost;
|
|
82
|
-
}else{
|
|
83
|
-
this.hostBroker = mqttHost;
|
|
84
|
-
}
|
|
85
|
-
this.keyAndPassIsOk = false;
|
|
86
|
-
deviceKey = deviceKey.replace(/[^A-Za-z0-9]/g, "");
|
|
87
|
-
devicePass = devicePass.replace(/[^A-Za-z0-9]/g, "");
|
|
88
|
-
if(deviceKey.length == 16 && devicePass.length == 20){
|
|
89
|
-
this.key = deviceKey;
|
|
90
|
-
this.pass = devicePass;
|
|
91
|
-
this.topicForPublish = '/devices/' + deviceKey + '/packet';
|
|
92
|
-
this.topicForSubscribe = '/devices/' + deviceKey + '/param/+';
|
|
93
|
-
this.keyAndPassIsOk = true;
|
|
94
|
-
}else{
|
|
95
|
-
console.log(errorsVizIoT[1]);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
connect(callback) {
|
|
100
|
-
if(typeof callback != "function"){
|
|
101
|
-
// console.log(new Error(errorsVizIoT[6]));
|
|
102
|
-
callback = function () {
|
|
103
|
-
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
if(this.keyAndPassIsOk){
|
|
107
|
-
let dataForConnectToBroker = {
|
|
108
|
-
'username': this.key,
|
|
109
|
-
'password': this.pass,
|
|
110
|
-
'reconnectPeriod': 5000
|
|
111
|
-
};
|
|
112
|
-
|
|
113
|
-
this.mqttClient = mqtt.connect(this.hostBroker, dataForConnectToBroker);
|
|
114
|
-
this.mqttClient.on('connect', function (connect) {
|
|
115
|
-
console.log("Соединение с MQTT брокером VizIoT.com установлено.");
|
|
116
|
-
callback();
|
|
117
|
-
});
|
|
118
|
-
this.mqttClient.on('reconnect', function () {
|
|
119
|
-
console.log("Пере подключение к MQTT брокеру VizIoT.com.");
|
|
120
|
-
});
|
|
121
|
-
this.mqttClient.on('close', function () {
|
|
122
|
-
console.log("Подключение к MQTT брокеру VizIoT.com закрыто.");
|
|
123
|
-
});
|
|
124
|
-
this.mqttClient.on('offline', function () {
|
|
125
|
-
// console.log("MQTT 'offline'");
|
|
126
|
-
});
|
|
127
|
-
this.mqttClient.on('error', function (error) {
|
|
128
|
-
if (error) {
|
|
129
|
-
console.log(errorsMQTT[error.code]);
|
|
130
|
-
}
|
|
131
|
-
});
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/**
|
|
136
|
-
* Например
|
|
137
|
-
* VizIoTClient.startListenMessages(function (topic, message) {
|
|
138
|
-
* .....
|
|
139
|
-
* })
|
|
140
|
-
* callback Параметры
|
|
141
|
-
* parameter - ключ команды или параметра
|
|
142
|
-
* value - значение параметра
|
|
143
|
-
* @param callback
|
|
144
|
-
*/
|
|
145
|
-
startListenCommands(callback) {
|
|
146
|
-
if(typeof callback != "function"){
|
|
147
|
-
console.log(new Error(errorsVizIoT[6]));
|
|
148
|
-
return false;
|
|
149
|
-
}
|
|
150
|
-
let strLengthForDelitfromTopic = this.topicForSubscribe.length;
|
|
151
|
-
this.mqttClient.on('message', function (topic, message, packet) {
|
|
152
|
-
let parameter = topic.substring(strLengthForDelitfromTopic-1);
|
|
153
|
-
let value = message.toString();
|
|
154
|
-
callback(parameter, value);
|
|
155
|
-
});
|
|
156
|
-
this.mqttClient.subscribe(this.topicForSubscribe, function (err, granted){
|
|
157
|
-
if(err) console.log("subscribe", err, granted);
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/**
|
|
162
|
-
* в функцию передается массив или объект для отправки на Сервер VizIoT
|
|
163
|
-
* @param data
|
|
164
|
-
* @param callback
|
|
165
|
-
*/
|
|
166
|
-
sendDataToVizIoT(data, callback){
|
|
167
|
-
if(typeof callback != "function"){
|
|
168
|
-
callback = function (err) {
|
|
169
|
-
if(err){
|
|
170
|
-
console.log("Ошибка в sendDataToVizIoT!", err);
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
let packet = "";
|
|
175
|
-
switch (typeof data){
|
|
176
|
-
case "string":
|
|
177
|
-
try {
|
|
178
|
-
packet = JSON.parse(data);
|
|
179
|
-
packet = JSON.stringify(packet);
|
|
180
|
-
} catch (err) {
|
|
181
|
-
callback(errorsVizIoT[2], false);
|
|
182
|
-
return false;
|
|
183
|
-
}
|
|
184
|
-
break;
|
|
185
|
-
case "object":
|
|
186
|
-
if(data != null){
|
|
187
|
-
packet = JSON.stringify(data);
|
|
188
|
-
}else{
|
|
189
|
-
callback(errorsVizIoT[3], false);
|
|
190
|
-
return false;
|
|
191
|
-
}
|
|
192
|
-
break;
|
|
193
|
-
default:
|
|
194
|
-
callback(errorsVizIoT[4], false);
|
|
195
|
-
return false;
|
|
196
|
-
break;
|
|
197
|
-
}
|
|
198
|
-
if(packet.length <= 2){
|
|
199
|
-
callback(errorsVizIoT[5], false);
|
|
200
|
-
return false;
|
|
201
|
-
}
|
|
202
|
-
this.mqttClient.publish(this.topicForPublish, packet, {'qos': 1}, function (err) {
|
|
203
|
-
if (err) {
|
|
204
|
-
callback(err, false);
|
|
205
|
-
}else{
|
|
206
|
-
callback(undefined, true);
|
|
207
|
-
}
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
};
|