Comparing version 5.0.0-beta.0 to 5.0.0-beta.1
@@ -333,3 +333,3 @@ 'use strict' | ||
this.on('connect', function () { | ||
const queue = this.queue | ||
const queue = that.queue | ||
@@ -376,6 +376,6 @@ function deliver () { | ||
debug('close :: connected set to `false`') | ||
this.connected = false | ||
that.connected = false | ||
debug('close :: clearing connackTimer') | ||
clearTimeout(this.connackTimer) | ||
clearTimeout(that.connackTimer) | ||
@@ -388,8 +388,8 @@ debug('close :: clearing ping timer') | ||
if (this.topicAliasRecv) { | ||
this.topicAliasRecv.clear() | ||
if (that.topicAliasRecv) { | ||
that.topicAliasRecv.clear() | ||
} | ||
debug('close :: calling _setupReconnect') | ||
this._setupReconnect() | ||
that._setupReconnect() | ||
}) | ||
@@ -1201,5 +1201,6 @@ EventEmitter.call(this) | ||
* @param {Function} cbStorePut - called when message is put into outgoingStore | ||
* @param {Boolean} noStore - send without put to the store | ||
* @api private | ||
*/ | ||
MqttClient.prototype._sendPacket = function (packet, cb, cbStorePut) { | ||
MqttClient.prototype._sendPacket = function (packet, cb, cbStorePut, noStore) { | ||
debug('_sendPacket :: (%s) :: start', this.options.clientId) | ||
@@ -1231,2 +1232,12 @@ cbStorePut = cbStorePut || nop | ||
// If "noStore" is true, the message is sent without being recorded in the store. | ||
// Messages that have not received puback or pubcomp remain in the store after disconnection | ||
// and are resent from the store upon reconnection. | ||
// For resend upon reconnection, "noStore" is set to true. This is because the message is already stored in the store. | ||
// This is to avoid interrupting other processes while recording to the store. | ||
if (noStore) { | ||
sendPacket(this, packet, cb) | ||
return | ||
} | ||
switch (packet.cmd) { | ||
@@ -1814,3 +1825,2 @@ case 'publish': | ||
} | ||
that._storeProcessing = true | ||
@@ -1827,2 +1837,4 @@ const packet = outStore.read(1) | ||
that._storeProcessing = true | ||
// Skip already processed store packets | ||
@@ -1850,3 +1862,3 @@ if (that._packetIdsDuringStoreProcessing[packet.messageId]) { | ||
if (that.messageIdProvider.register(packet.messageId)) { | ||
that._sendPacket(packet) | ||
that._sendPacket(packet, undefined, undefined, true) | ||
} else { | ||
@@ -1853,0 +1865,0 @@ debug('messageId: %d has already used.', packet.messageId) |
{ | ||
"name": "mqtt", | ||
"description": "A library for the MQTT protocol", | ||
"version": "5.0.0-beta.0", | ||
"version": "5.0.0-beta.1", | ||
"contributors": [ | ||
@@ -139,3 +139,4 @@ "Adam Rudd <adamvrr@gmail.com>", | ||
"terser": "^5.14.2", | ||
"typescript": "^4.5.5" | ||
"typescript": "^4.5.5", | ||
"mqtt-level-store": "^3.1.0" | ||
}, | ||
@@ -142,0 +143,0 @@ "standard": { |
571
README.md
@@ -1,5 +0,4 @@ | ||
![mqtt.js](https://raw.githubusercontent.com/mqttjs/MQTT.js/137ee0e3940c1f01049a30248c70f24dc6e6f829/MQTT.js.png) | ||
======= | ||
# ![mqtt.js](https://raw.githubusercontent.com/mqttjs/MQTT.js/137ee0e3940c1f01049a30248c70f24dc6e6f829/MQTT.js.png) | ||
![Github Test Status](https://github.com/mqttjs/MQTT.js/workflows/MQTT.js%20CI/badge.svg) [![codecov](https://codecov.io/gh/mqttjs/MQTT.js/branch/master/graph/badge.svg)](https://codecov.io/gh/mqttjs/MQTT.js) | ||
![Github Test Status](https://github.com/mqttjs/MQTT.js/workflows/MQTT.js%20CI/badge.svg) [![codecov](https://codecov.io/gh/mqttjs/MQTT.js/branch/master/graph/badge.svg)](https://codecov.io/gh/mqttjs/MQTT.js) | ||
@@ -9,17 +8,21 @@ MQTT.js is a client library for the [MQTT](http://mqtt.org/) protocol, written | ||
> MQTT [5.0.0-beta.0](https://github.com/mqttjs/MQTT.js/releases/tag/v5.0.0-beta.0) is now available! Try it out and give us feedback! `npm i mqtt@5.0.0-beta.0` | ||
## Table of Contents | ||
* [__MQTT.js vNext__](#vnext) | ||
* [Upgrade notes](#notes) | ||
* [Installation](#install) | ||
* [Example](#example) | ||
* [Import Styles](#example) | ||
* [Command Line Tools](#cli) | ||
* [API](#api) | ||
* [Browser](#browser) | ||
* [About QoS](#qos) | ||
* [TypeScript](#typescript) | ||
* [Weapp and Ali support](#weapp-alipay) | ||
* [Contributing](#contributing) | ||
* [License](#license) | ||
- [**MQTT.js vNext**](#vnext) | ||
- [Upgrade notes](#notes) | ||
- [Installation](#install) | ||
- [Example](#example) | ||
- [Import Styles](#example) | ||
- [Command Line Tools](#cli) | ||
- [API](#api) | ||
- [Browser](#browser) | ||
- [About QoS](#qos) | ||
- [TypeScript](#typescript) | ||
- [Weapp and Ali support](#weapp-alipay) | ||
- [Contributing](#contributing) | ||
- [Sponsor](#sponsor) | ||
- [License](#license) | ||
MQTT.js is an OPEN Open Source Project, see the [Contributing](#contributing) section to find out what this means. | ||
@@ -31,12 +34,17 @@ | ||
<a name="vnext"></a> | ||
## Next major version of MQTT.js | ||
There is work being done on the next generation of MQTT.js (vNext). We invite the community to provide their contributions [this repository](https://github.com/mqttjs/mqttjs-v5) | ||
<a name="notes"></a> | ||
## Important notes for existing users | ||
__v4.0.0__ (Released 04/2020) removes support for all end of life node versions, and now supports node v12 and v14. It also adds improvements to | ||
**v5.0.0** (**BETA** 06/2023) removes support for all end of life node versions (v12 and v14), and now supports node v18 and v20. | ||
**v4.0.0** (Released 04/2020) removes support for all end of life node versions, and now supports node v12 and v14. It also adds improvements to | ||
debug logging, along with some feature additions. | ||
As a __breaking change__, by default a error handler is built into the MQTT.js client, so if any | ||
As a **breaking change**, by default a error handler is built into the MQTT.js client, so if any | ||
errors are emitted and the user has not created an event handler on the client for errors, the client will | ||
@@ -46,14 +54,14 @@ not break as a result of unhandled errors. Additionally, typical TLS errors like `ECONNREFUSED`, `ECONNRESET` have been | ||
__v3.0.0__ adds support for MQTT 5, support for node v10.x, and many fixes to improve reliability. | ||
**v3.0.0** adds support for MQTT 5, support for node v10.x, and many fixes to improve reliability. | ||
__Note:__ MQTT v5 support is experimental as it has not been implemented by brokers yet. | ||
**Note:** MQTT v5 support is experimental as it has not been implemented by brokers yet. | ||
__v2.0.0__ removes support for node v0.8, v0.10 and v0.12, and it is 3x faster in sending | ||
**v2.0.0** removes support for node v0.8, v0.10 and v0.12, and it is 3x faster in sending | ||
packets. It also removes all the deprecated functionality in v1.0.0, | ||
mainly `mqtt.createConnection` and `mqtt.Server`. From v2.0.0, | ||
subscriptions are restored upon reconnection if `clean: true`. | ||
v1.x.x is now in *LTS*, and it will keep being supported as long as | ||
v1.x.x is now in _LTS_, and it will keep being supported as long as | ||
there are v0.8, v0.10 and v0.12 users. | ||
As a __breaking change__, the `encoding` option in the old client is | ||
As a **breaking change**, the `encoding` option in the old client is | ||
removed, and now everything is UTF-8 with the exception of the | ||
@@ -63,6 +71,6 @@ `password` in the CONNECT message and `payload` in the PUBLISH message, | ||
Another __breaking change__ is that MQTT.js now defaults to MQTT v3.1.1, | ||
Another **breaking change** is that MQTT.js now defaults to MQTT v3.1.1, | ||
so to support old brokers, please read the [client options doc](#client). | ||
__v1.0.0__ improves the overall architecture of the project, which is now | ||
**v1.0.0** improves the overall architecture of the project, which is now | ||
split into three components: MQTT.js keeps the Client, | ||
@@ -78,2 +86,3 @@ [mqtt-connection](http://npm.im/mqtt-connection) includes the barebone | ||
<a name="install"></a> | ||
## Installation | ||
@@ -86,2 +95,3 @@ | ||
<a name="example"></a> | ||
## Example | ||
@@ -92,21 +102,22 @@ | ||
```js | ||
const mqtt = require('mqtt') | ||
const client = mqtt.connect('mqtt://test.mosquitto.org') | ||
const mqtt = require("mqtt"); | ||
const client = mqtt.connect("mqtt://test.mosquitto.org"); | ||
client.on('connect', function () { | ||
client.subscribe('presence', function (err) { | ||
client.on("connect", function () { | ||
client.subscribe("presence", function (err) { | ||
if (!err) { | ||
client.publish('presence', 'Hello mqtt') | ||
client.publish("presence", "Hello mqtt"); | ||
} | ||
}) | ||
}) | ||
}); | ||
}); | ||
client.on('message', function (topic, message) { | ||
client.on("message", function (topic, message) { | ||
// message is Buffer | ||
console.log(message.toString()) | ||
client.end() | ||
}) | ||
console.log(message.toString()); | ||
client.end(); | ||
}); | ||
``` | ||
output: | ||
``` | ||
@@ -128,21 +139,30 @@ Hello mqtt | ||
<a name="import_styles"></a> | ||
## Import styles | ||
### CommonJS (Require) | ||
```js | ||
const mqtt = require('mqtt') // require mqtt | ||
const client = mqtt.connect('est.mosquitto.org') // create a client | ||
const mqtt = require("mqtt"); // require mqtt | ||
const client = mqtt.connect("est.mosquitto.org"); // create a client | ||
``` | ||
### ES6 Modules (Import) | ||
#### Aliased wildcard import | ||
```js | ||
import * as mqtt from "mqtt" // import everything inside the mqtt module and give it the namespace "mqtt" | ||
let client = mqtt.connect('mqtt://test.mosquitto.org') // create a client | ||
import * as mqtt from "mqtt"; // import everything inside the mqtt module and give it the namespace "mqtt" | ||
let client = mqtt.connect("mqtt://test.mosquitto.org"); // create a client | ||
``` | ||
#### Importing individual components | ||
```js | ||
import { connect } from "mqtt" // import connect from mqtt | ||
let client = connect('mqtt://test.mosquitto.org') // create a client | ||
import { connect } from "mqtt"; // import connect from mqtt | ||
let client = connect("mqtt://test.mosquitto.org"); // create a client | ||
``` | ||
<a name="promises"></a> | ||
## Promise support | ||
@@ -153,2 +173,3 @@ | ||
<a name="cli"></a> | ||
## Command Line Tools | ||
@@ -179,5 +200,7 @@ | ||
<a name="debug"></a> | ||
## Debug Logs | ||
MQTT.js uses the [debug](https://www.npmjs.com/package/debug#cmd) package for debugging purposes. To enable debug logs, add the following environment variable on runtime : | ||
```ps | ||
@@ -190,2 +213,3 @@ # (example using PowerShell, the VS Code default) | ||
<a name="reconnecting"></a> | ||
## About Reconnection | ||
@@ -212,2 +236,3 @@ | ||
Example (update clientId & username on each reconnect): | ||
``` | ||
@@ -227,2 +252,3 @@ const transformWsUrl = (url, options, client) => { | ||
``` | ||
Now every time a new WebSocket connection is opened (hopefully not too often), | ||
@@ -236,3 +262,2 @@ we will get a fresh signed url or fresh auth token data. | ||
#### Enabling Reconnection with `reconnectPeriod` option | ||
@@ -249,8 +274,11 @@ | ||
<a name="topicalias"></a> | ||
## About Topic Alias Management | ||
### Enabling automatic Topic Alias using | ||
If the client sets the option `autoUseTopicAlias:true` then MQTT.js uses existing topic alias automatically. | ||
example scenario: | ||
``` | ||
@@ -268,3 +296,3 @@ 1. PUBLISH topic:'t1', ta:1 (register) | ||
### Enabling automatic Topic Alias assign | ||
### Enabling automatic Topic Alias assign | ||
@@ -275,2 +303,3 @@ If the client sets the option `autoAssignTopicAlias:true` then MQTT.js uses existing topic alias automatically. | ||
example scenario: | ||
``` | ||
@@ -288,24 +317,27 @@ The broker returns CONNACK (TopicAliasMaximum:3) | ||
<a name="api"></a> | ||
## API | ||
* <a href="#connect"><code>mqtt.<b>connect()</b></code></a> | ||
* <a href="#client"><code>mqtt.<b>Client()</b></code></a> | ||
* <a href="#publish"><code>mqtt.Client#<b>publish()</b></code></a> | ||
* <a href="#subscribe"><code>mqtt.Client#<b>subscribe()</b></code></a> | ||
* <a href="#unsubscribe"><code>mqtt.Client#<b>unsubscribe()</b></code></a> | ||
* <a href="#end"><code>mqtt.Client#<b>end()</b></code></a> | ||
* <a href="#removeOutgoingMessage"><code>mqtt.Client#<b>removeOutgoingMessage()</b></code></a> | ||
* <a href="#reconnect"><code>mqtt.Client#<b>reconnect()</b></code></a> | ||
* <a href="#handleMessage"><code>mqtt.Client#<b>handleMessage()</b></code></a> | ||
* <a href="#connected"><code>mqtt.Client#<b>connected</b></code></a> | ||
* <a href="#reconnecting"><code>mqtt.Client#<b>reconnecting</b></code></a> | ||
* <a href="#getLastMessageId"><code>mqtt.Client#<b>getLastMessageId()</b></code></a> | ||
* <a href="#store"><code>mqtt.<b>Store()</b></code></a> | ||
* <a href="#put"><code>mqtt.Store#<b>put()</b></code></a> | ||
* <a href="#del"><code>mqtt.Store#<b>del()</b></code></a> | ||
* <a href="#createStream"><code>mqtt.Store#<b>createStream()</b></code></a> | ||
* <a href="#close"><code>mqtt.Store#<b>close()</b></code></a> | ||
- <a href="#connect"><code>mqtt.<b>connect()</b></code></a> | ||
- <a href="#client"><code>mqtt.<b>Client()</b></code></a> | ||
- <a href="#publish"><code>mqtt.Client#<b>publish()</b></code></a> | ||
- <a href="#subscribe"><code>mqtt.Client#<b>subscribe()</b></code></a> | ||
- <a href="#unsubscribe"><code>mqtt.Client#<b>unsubscribe()</b></code></a> | ||
- <a href="#end"><code>mqtt.Client#<b>end()</b></code></a> | ||
- <a href="#removeOutgoingMessage"><code>mqtt.Client#<b>removeOutgoingMessage()</b></code></a> | ||
- <a href="#reconnect"><code>mqtt.Client#<b>reconnect()</b></code></a> | ||
- <a href="#handleMessage"><code>mqtt.Client#<b>handleMessage()</b></code></a> | ||
- <a href="#connected"><code>mqtt.Client#<b>connected</b></code></a> | ||
- <a href="#reconnecting"><code>mqtt.Client#<b>reconnecting</b></code></a> | ||
- <a href="#getLastMessageId"><code>mqtt.Client#<b>getLastMessageId()</b></code></a> | ||
- <a href="#store"><code>mqtt.<b>Store()</b></code></a> | ||
- <a href="#put"><code>mqtt.Store#<b>put()</b></code></a> | ||
- <a href="#del"><code>mqtt.Store#<b>del()</b></code></a> | ||
- <a href="#createStream"><code>mqtt.Store#<b>createStream()</b></code></a> | ||
- <a href="#close"><code>mqtt.Store#<b>close()</b></code></a> | ||
------------------------------------------------------- | ||
--- | ||
<a name="connect"></a> | ||
### mqtt.connect([url], options) | ||
@@ -329,4 +361,6 @@ | ||
------------------------------------------------------- | ||
--- | ||
<a name="client"></a> | ||
### mqtt.Client(streamBuilder, options) | ||
@@ -340,68 +374,68 @@ | ||
* Regular server pings | ||
* QoS flow | ||
* Automatic reconnections | ||
* Start publishing before being connected | ||
- Regular server pings | ||
- QoS flow | ||
- Automatic reconnections | ||
- Start publishing before being connected | ||
The arguments are: | ||
* `streamBuilder` is a function that returns a subclass of the `Stream` class that supports | ||
the `connect` event. Typically a `net.Socket`. | ||
* `options` is the client connection options (see: the [connect packet](https://github.com/mcollina/mqtt-packet#connect)). Defaults: | ||
* `wsOptions`: is the WebSocket connection options. Default is `{}`. | ||
It's specific for WebSockets. For possible options have a look at: https://github.com/websockets/ws/blob/master/doc/ws.md. | ||
* `keepalive`: `60` seconds, set to `0` to disable | ||
* `reschedulePings`: reschedule ping messages after sending packets (default `true`) | ||
* `clientId`: `'mqttjs_' + Math.random().toString(16).substr(2, 8)` | ||
* `protocolId`: `'MQTT'` | ||
* `protocolVersion`: `4` | ||
* `clean`: `true`, set to false to receive QoS 1 and 2 messages while | ||
- `streamBuilder` is a function that returns a subclass of the `Stream` class that supports | ||
the `connect` event. Typically a `net.Socket`. | ||
- `options` is the client connection options (see: the [connect packet](https://github.com/mcollina/mqtt-packet#connect)). Defaults: | ||
- `wsOptions`: is the WebSocket connection options. Default is `{}`. | ||
It's specific for WebSockets. For possible options have a look at: https://github.com/websockets/ws/blob/master/doc/ws.md. | ||
- `keepalive`: `60` seconds, set to `0` to disable | ||
- `reschedulePings`: reschedule ping messages after sending packets (default `true`) | ||
- `clientId`: `'mqttjs_' + Math.random().toString(16).substr(2, 8)` | ||
- `protocolId`: `'MQTT'` | ||
- `protocolVersion`: `4` | ||
- `clean`: `true`, set to false to receive QoS 1 and 2 messages while | ||
offline | ||
* `reconnectPeriod`: `1000` milliseconds, interval between two | ||
- `reconnectPeriod`: `1000` milliseconds, interval between two | ||
reconnections. Disable auto reconnect by setting to `0`. | ||
* `connectTimeout`: `30 * 1000` milliseconds, time to wait before a | ||
- `connectTimeout`: `30 * 1000` milliseconds, time to wait before a | ||
CONNACK is received | ||
* `username`: the username required by your broker, if any | ||
* `password`: the password required by your broker, if any | ||
* `incomingStore`: a [Store](#store) for the incoming packets | ||
* `outgoingStore`: a [Store](#store) for the outgoing packets | ||
* `queueQoSZero`: if connection is broken, queue outgoing QoS zero messages (default `true`) | ||
* `customHandleAcks`: MQTT 5 feature of custom handling puback and pubrec packets. Its callback: | ||
```js | ||
customHandleAcks: function(topic, message, packet, done) {/*some logic wit colling done(error, reasonCode)*/} | ||
``` | ||
* `autoUseTopicAlias`: enabling automatic Topic Alias using functionality | ||
* `autoAssignTopicAlias`: enabling automatic Topic Alias assign functionality | ||
* `properties`: properties MQTT 5.0. | ||
`object` that supports the following properties: | ||
* `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`, | ||
* `receiveMaximum`: representing the Receive Maximum value `number`, | ||
* `maximumPacketSize`: representing the Maximum Packet Size the Client is willing to accept `number`, | ||
* `topicAliasMaximum`: representing the Topic Alias Maximum value indicates the highest value that the Client will accept as a Topic Alias sent by the Server `number`, | ||
* `requestResponseInformation`: The Client uses this value to request the Server to return Response Information in the CONNACK `boolean`, | ||
* `requestProblemInformation`: The Client uses this value to indicate whether the Reason String or User Properties are sent in the case of failures `boolean`, | ||
* `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`, | ||
* `authenticationMethod`: the name of the authentication method used for extended authentication `string`, | ||
* `authenticationData`: Binary Data containing authentication data `binary` | ||
* `authPacket`: settings for auth packet `object` | ||
* `will`: a message that will sent by the broker automatically when | ||
the client disconnect badly. The format is: | ||
* `topic`: the topic to publish | ||
* `payload`: the message to publish | ||
* `qos`: the QoS | ||
* `retain`: the retain flag | ||
* `properties`: properties of will by MQTT 5.0: | ||
* `willDelayInterval`: representing the Will Delay Interval in seconds `number`, | ||
* `payloadFormatIndicator`: Will Message is UTF-8 Encoded Character Data or not `boolean`, | ||
* `messageExpiryInterval`: value is the lifetime of the Will Message in seconds and is sent as the Publication Expiry Interval when the Server publishes the Will Message `number`, | ||
* `contentType`: describing the content of the Will Message `string`, | ||
* `responseTopic`: String which is used as the Topic Name for a response message `string`, | ||
* `correlationData`: The Correlation Data is used by the sender of the Request Message to identify which request the Response Message is for when it is received `binary`, | ||
* `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object` | ||
* `transformWsUrl` : optional `(url, options, client) => url` function | ||
For ws/wss protocols only. Can be used to implement signing | ||
urls which upon reconnect can have become expired. | ||
* `resubscribe` : if connection is broken and reconnects, | ||
subscribed topics are automatically subscribed again (default `true`) | ||
* `messageIdProvider`: custom messageId provider. when `new UniqueMessageIdProvider()` is set, then non conflict messageId is provided. | ||
- `username`: the username required by your broker, if any | ||
- `password`: the password required by your broker, if any | ||
- `incomingStore`: a [Store](#store) for the incoming packets | ||
- `outgoingStore`: a [Store](#store) for the outgoing packets | ||
- `queueQoSZero`: if connection is broken, queue outgoing QoS zero messages (default `true`) | ||
- `customHandleAcks`: MQTT 5 feature of custom handling puback and pubrec packets. Its callback: | ||
```js | ||
customHandleAcks: function(topic, message, packet, done) {/*some logic wit colling done(error, reasonCode)*/} | ||
``` | ||
- `autoUseTopicAlias`: enabling automatic Topic Alias using functionality | ||
- `autoAssignTopicAlias`: enabling automatic Topic Alias assign functionality | ||
- `properties`: properties MQTT 5.0. | ||
`object` that supports the following properties: | ||
- `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`, | ||
- `receiveMaximum`: representing the Receive Maximum value `number`, | ||
- `maximumPacketSize`: representing the Maximum Packet Size the Client is willing to accept `number`, | ||
- `topicAliasMaximum`: representing the Topic Alias Maximum value indicates the highest value that the Client will accept as a Topic Alias sent by the Server `number`, | ||
- `requestResponseInformation`: The Client uses this value to request the Server to return Response Information in the CONNACK `boolean`, | ||
- `requestProblemInformation`: The Client uses this value to indicate whether the Reason String or User Properties are sent in the case of failures `boolean`, | ||
- `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`, | ||
- `authenticationMethod`: the name of the authentication method used for extended authentication `string`, | ||
- `authenticationData`: Binary Data containing authentication data `binary` | ||
- `authPacket`: settings for auth packet `object` | ||
- `will`: a message that will sent by the broker automatically when | ||
the client disconnect badly. The format is: | ||
- `topic`: the topic to publish | ||
- `payload`: the message to publish | ||
- `qos`: the QoS | ||
- `retain`: the retain flag | ||
- `properties`: properties of will by MQTT 5.0: | ||
- `willDelayInterval`: representing the Will Delay Interval in seconds `number`, | ||
- `payloadFormatIndicator`: Will Message is UTF-8 Encoded Character Data or not `boolean`, | ||
- `messageExpiryInterval`: value is the lifetime of the Will Message in seconds and is sent as the Publication Expiry Interval when the Server publishes the Will Message `number`, | ||
- `contentType`: describing the content of the Will Message `string`, | ||
- `responseTopic`: String which is used as the Topic Name for a response message `string`, | ||
- `correlationData`: The Correlation Data is used by the sender of the Request Message to identify which request the Response Message is for when it is received `binary`, | ||
- `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object` | ||
- `transformWsUrl` : optional `(url, options, client) => url` function | ||
For ws/wss protocols only. Can be used to implement signing | ||
urls which upon reconnect can have become expired. | ||
- `resubscribe` : if connection is broken and reconnects, | ||
subscribed topics are automatically subscribed again (default `true`) | ||
- `messageIdProvider`: custom messageId provider. when `new UniqueMessageIdProvider()` is set, then non conflict messageId is provided. | ||
@@ -433,6 +467,7 @@ In case mqtts (mqtt over tls) is required, the `options` object is | ||
Emitted on successful (re)connection (i.e. connack rc=0). | ||
* `connack` received connack packet. When `clean` connection option is `false` and server has a previous session | ||
for `clientId` connection option, then `connack.sessionPresent` flag is `true`. When that is the case, | ||
you may rely on stored session and prefer not to send subscribe commands for the client. | ||
- `connack` received connack packet. When `clean` connection option is `false` and server has a previous session | ||
for `clientId` connection option, then `connack.sessionPresent` flag is `true`. When that is the case, | ||
you may rely on stored session and prefer not to send subscribe commands for the client. | ||
#### Event `'reconnect'` | ||
@@ -471,6 +506,6 @@ | ||
* `ECONNREFUSED` | ||
* `ECONNRESET` | ||
* `EADDRINUSE` | ||
* `ENOTFOUND` | ||
- `ECONNREFUSED` | ||
- `ECONNRESET` | ||
- `EADDRINUSE` | ||
- `ENOTFOUND` | ||
@@ -490,5 +525,6 @@ #### Event `'end'` | ||
Emitted when the client receives a publish packet | ||
* `topic` topic of the received packet | ||
* `message` payload of the received packet | ||
* `packet` received packet, as defined in | ||
- `topic` topic of the received packet | ||
- `message` payload of the received packet | ||
- `packet` received packet, as defined in | ||
[mqtt-packet](https://github.com/mcollina/mqtt-packet#publish) | ||
@@ -502,3 +538,4 @@ | ||
as well as packets used by MQTT for managing subscriptions and connections | ||
* `packet` received packet, as defined in | ||
- `packet` received packet, as defined in | ||
[mqtt-packet](https://github.com/mcollina/mqtt-packet) | ||
@@ -513,7 +550,10 @@ | ||
and connections | ||
* `packet` received packet, as defined in | ||
- `packet` received packet, as defined in | ||
[mqtt-packet](https://github.com/mcollina/mqtt-packet) | ||
------------------------------------------------------- | ||
--- | ||
<a name="publish"></a> | ||
### mqtt.Client#publish(topic, message, [options], [callback]) | ||
@@ -523,23 +563,25 @@ | ||
* `topic` is the topic to publish to, `String` | ||
* `message` is the message to publish, `Buffer` or `String` | ||
* `options` is the options to publish with, including: | ||
* `qos` QoS level, `Number`, default `0` | ||
* `retain` retain flag, `Boolean`, default `false` | ||
* `dup` mark as duplicate flag, `Boolean`, default `false` | ||
* `properties`: MQTT 5.0 properties `object` | ||
* `payloadFormatIndicator`: Payload is UTF-8 Encoded Character Data or not `boolean`, | ||
* `messageExpiryInterval`: the lifetime of the Application Message in seconds `number`, | ||
* `topicAlias`: value that is used to identify the Topic instead of using the Topic Name `number`, | ||
* `responseTopic`: String which is used as the Topic Name for a response message `string`, | ||
* `correlationData`: used by the sender of the Request Message to identify which request the Response Message is for when it is received `binary`, | ||
* `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`, | ||
* `subscriptionIdentifier`: representing the identifier of the subscription `number`, | ||
* `contentType`: String describing the content of the Application Message `string` | ||
* `cbStorePut` - `function ()`, fired when message is put into `outgoingStore` if QoS is `1` or `2`. | ||
* `callback` - `function (err)`, fired when the QoS handling completes, | ||
- `topic` is the topic to publish to, `String` | ||
- `message` is the message to publish, `Buffer` or `String` | ||
- `options` is the options to publish with, including: | ||
- `qos` QoS level, `Number`, default `0` | ||
- `retain` retain flag, `Boolean`, default `false` | ||
- `dup` mark as duplicate flag, `Boolean`, default `false` | ||
- `properties`: MQTT 5.0 properties `object` | ||
- `payloadFormatIndicator`: Payload is UTF-8 Encoded Character Data or not `boolean`, | ||
- `messageExpiryInterval`: the lifetime of the Application Message in seconds `number`, | ||
- `topicAlias`: value that is used to identify the Topic instead of using the Topic Name `number`, | ||
- `responseTopic`: String which is used as the Topic Name for a response message `string`, | ||
- `correlationData`: used by the sender of the Request Message to identify which request the Response Message is for when it is received `binary`, | ||
- `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`, | ||
- `subscriptionIdentifier`: representing the identifier of the subscription `number`, | ||
- `contentType`: String describing the content of the Application Message `string` | ||
- `cbStorePut` - `function ()`, fired when message is put into `outgoingStore` if QoS is `1` or `2`. | ||
- `callback` - `function (err)`, fired when the QoS handling completes, | ||
or at the next tick if QoS 0. An error occurs if client is disconnecting. | ||
------------------------------------------------------- | ||
--- | ||
<a name="subscribe"></a> | ||
### mqtt.Client#subscribe(topic/topic array/topic object, [options], [callback]) | ||
@@ -549,23 +591,25 @@ | ||
* `topic` is a `String` topic to subscribe to or an `Array` of | ||
- `topic` is a `String` topic to subscribe to or an `Array` of | ||
topics to subscribe to. It can also be an object, it has as object | ||
keys the topic name and as value the QoS, like `{'test1': {qos: 0}, 'test2': {qos: 1}}`. | ||
MQTT `topic` wildcard characters are supported (`+` - for single level and `#` - for multi level) | ||
* `options` is the options to subscribe with, including: | ||
* `qos` QoS subscription level, default 0 | ||
* `nl` No Local MQTT 5.0 flag (If the value is true, Application Messages MUST NOT be forwarded to a connection with a ClientID equal to the ClientID of the publishing connection) | ||
* `rap` Retain as Published MQTT 5.0 flag (If true, Application Messages forwarded using this subscription keep the RETAIN flag they were published with. If false, Application Messages forwarded using this subscription have the RETAIN flag set to 0.) | ||
* `rh` Retain Handling MQTT 5.0 (This option specifies whether retained messages are sent when the subscription is established.) | ||
* `properties`: `object` | ||
* `subscriptionIdentifier`: representing the identifier of the subscription `number`, | ||
* `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object` | ||
* `callback` - `function (err, granted)` | ||
- `options` is the options to subscribe with, including: | ||
- `qos` QoS subscription level, default 0 | ||
- `nl` No Local MQTT 5.0 flag (If the value is true, Application Messages MUST NOT be forwarded to a connection with a ClientID equal to the ClientID of the publishing connection) | ||
- `rap` Retain as Published MQTT 5.0 flag (If true, Application Messages forwarded using this subscription keep the RETAIN flag they were published with. If false, Application Messages forwarded using this subscription have the RETAIN flag set to 0.) | ||
- `rh` Retain Handling MQTT 5.0 (This option specifies whether retained messages are sent when the subscription is established.) | ||
- `properties`: `object` | ||
- `subscriptionIdentifier`: representing the identifier of the subscription `number`, | ||
- `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object` | ||
- `callback` - `function (err, granted)` | ||
callback fired on suback where: | ||
* `err` a subscription error or an error that occurs when client is disconnecting | ||
* `granted` is an array of `{topic, qos}` where: | ||
* `topic` is a subscribed to topic | ||
* `qos` is the granted QoS level on it | ||
- `err` a subscription error or an error that occurs when client is disconnecting | ||
- `granted` is an array of `{topic, qos}` where: | ||
- `topic` is a subscribed to topic | ||
- `qos` is the granted QoS level on it | ||
------------------------------------------------------- | ||
--- | ||
<a name="unsubscribe"></a> | ||
### mqtt.Client#unsubscribe(topic/topic array, [options], [callback]) | ||
@@ -575,10 +619,12 @@ | ||
* `topic` is a `String` topic or an array of topics to unsubscribe from | ||
* `options`: options of unsubscribe. | ||
* `properties`: `object` | ||
* `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object` | ||
* `callback` - `function (err)`, fired on unsuback. An error occurs if client is disconnecting. | ||
- `topic` is a `String` topic or an array of topics to unsubscribe from | ||
- `options`: options of unsubscribe. | ||
- `properties`: `object` | ||
- `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object` | ||
- `callback` - `function (err)`, fired on unsuback. An error occurs if client is disconnecting. | ||
------------------------------------------------------- | ||
--- | ||
<a name="end"></a> | ||
### mqtt.Client#end([force], [options], [callback]) | ||
@@ -588,17 +634,19 @@ | ||
* `force`: passing it to true will close the client right away, without | ||
- `force`: passing it to true will close the client right away, without | ||
waiting for the in-flight messages to be acked. This parameter is | ||
optional. | ||
* `options`: options of disconnect. | ||
* `reasonCode`: Disconnect Reason Code `number` | ||
* `properties`: `object` | ||
* `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`, | ||
* `reasonString`: representing the reason for the disconnect `string`, | ||
* `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`, | ||
* `serverReference`: String which can be used by the Client to identify another Server to use `string` | ||
* `callback`: will be called when the client is closed. This parameter is | ||
- `options`: options of disconnect. | ||
- `reasonCode`: Disconnect Reason Code `number` | ||
- `properties`: `object` | ||
- `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`, | ||
- `reasonString`: representing the reason for the disconnect `string`, | ||
- `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`, | ||
- `serverReference`: String which can be used by the Client to identify another Server to use `string` | ||
- `callback`: will be called when the client is closed. This parameter is | ||
optional. | ||
------------------------------------------------------- | ||
--- | ||
<a name="removeOutgoingMessage"></a> | ||
### mqtt.Client#removeOutgoingMessage(mId) | ||
@@ -611,6 +659,8 @@ | ||
* `mId`: The messageId of the message in the outgoingStore. | ||
- `mId`: The messageId of the message in the outgoingStore. | ||
------------------------------------------------------- | ||
--- | ||
<a name="reconnect"></a> | ||
### mqtt.Client#reconnect() | ||
@@ -620,12 +670,16 @@ | ||
------------------------------------------------------- | ||
--- | ||
<a name="handleMessage"></a> | ||
### mqtt.Client#handleMessage(packet, callback) | ||
Handle messages with backpressure support, one at a time. | ||
Override at will, but __always call `callback`__, or the client | ||
Override at will, but **always call `callback`**, or the client | ||
will hang. | ||
------------------------------------------------------- | ||
--- | ||
<a name="connected"></a> | ||
### mqtt.Client#connected | ||
@@ -635,4 +689,6 @@ | ||
------------------------------------------------------- | ||
--- | ||
<a name="getLastMessageId"></a> | ||
### mqtt.Client#getLastMessageId() | ||
@@ -642,4 +698,6 @@ | ||
------------------------------------------------------- | ||
--- | ||
<a name="reconnecting"></a> | ||
### mqtt.Client#reconnecting | ||
@@ -649,4 +707,6 @@ | ||
------------------------------------------------------- | ||
--- | ||
<a name="store"></a> | ||
### mqtt.Store(options) | ||
@@ -656,21 +716,23 @@ | ||
* `options` is the store options: | ||
* `clean`: `true`, clean inflight messages when close is called (default `true`) | ||
- `options` is the store options: | ||
- `clean`: `true`, clean inflight messages when close is called (default `true`) | ||
Other implementations of `mqtt.Store`: | ||
* [mqtt-jsonl-store](https://github.com/robertsLando/mqtt-jsonl-store) which uses | ||
- [mqtt-jsonl-store](https://github.com/robertsLando/mqtt-jsonl-store) which uses | ||
[jsonl-db](https://github.com/AlCalzone/jsonl-db) to store inflight data, it works only on Node. | ||
* [mqtt-level-store](http://npm.im/mqtt-level-store) which uses | ||
- [mqtt-level-store](http://npm.im/mqtt-level-store) which uses | ||
[Level-browserify](http://npm.im/level-browserify) to store the inflight | ||
data, making it usable both in Node and the Browser. | ||
* [mqtt-nedb-store](https://github.com/behrad/mqtt-nedb-store) which | ||
- [mqtt-nedb-store](https://github.com/behrad/mqtt-nedb-store) which | ||
uses [nedb](https://www.npmjs.com/package/nedb) to store the inflight | ||
data. | ||
* [mqtt-localforage-store](http://npm.im/mqtt-localforage-store) which uses | ||
- [mqtt-localforage-store](http://npm.im/mqtt-localforage-store) which uses | ||
[localForage](http://npm.im/localforage) to store the inflight | ||
data, making it usable in the Browser without browserify. | ||
------------------------------------------------------- | ||
--- | ||
<a name="put"></a> | ||
### mqtt.Store#put(packet, callback) | ||
@@ -682,4 +744,6 @@ | ||
------------------------------------------------------- | ||
--- | ||
<a name="createStream"></a> | ||
### mqtt.Store#createStream() | ||
@@ -689,4 +753,6 @@ | ||
------------------------------------------------------- | ||
--- | ||
<a name="del"></a> | ||
### mqtt.Store#del(packet, cb) | ||
@@ -698,4 +764,6 @@ | ||
------------------------------------------------------- | ||
--- | ||
<a name="close"></a> | ||
### mqtt.Store#close(cb) | ||
@@ -706,5 +774,7 @@ | ||
<a name="browser"></a> | ||
## Browser | ||
<a name="cdn"></a> | ||
### Via CDN | ||
@@ -717,2 +787,3 @@ | ||
<a name="browserify"></a> | ||
### Browserify | ||
@@ -738,2 +809,3 @@ | ||
<a name="webpack"></a> | ||
### Webpack | ||
@@ -755,19 +827,19 @@ | ||
<html> | ||
<head> | ||
<title>test Ws mqtt.js</title> | ||
</head> | ||
<body> | ||
<script src="./browserMqtt.js"></script> | ||
<script> | ||
const client = mqtt.connect() // you add a ws:// url here | ||
client.subscribe("mqtt/demo") | ||
<head> | ||
<title>test Ws mqtt.js</title> | ||
</head> | ||
<body> | ||
<script src="./browserMqtt.js"></script> | ||
<script> | ||
const client = mqtt.connect(); // you add a ws:// url here | ||
client.subscribe("mqtt/demo"); | ||
client.on("message", function (topic, payload) { | ||
alert([topic, payload].join(": ")) | ||
client.end() | ||
}) | ||
client.on("message", function (topic, payload) { | ||
alert([topic, payload].join(": ")); | ||
client.end(); | ||
}); | ||
client.publish("mqtt/demo", "hello world!") | ||
</script> | ||
</body> | ||
client.publish("mqtt/demo", "hello world!"); | ||
</script> | ||
</body> | ||
</html> | ||
@@ -777,2 +849,3 @@ ``` | ||
### React | ||
``` | ||
@@ -788,3 +861,2 @@ npm install -g webpack // Install webpack globally | ||
```javascript | ||
@@ -819,2 +891,3 @@ import React from 'react'; | ||
<a name="qos"></a> | ||
## About QoS | ||
@@ -824,5 +897,5 @@ | ||
* QoS 0 : received **at most once** : The packet is sent, and that's it. There is no validation about whether it has been received. | ||
* QoS 1 : received **at least once** : The packet is sent and stored as long as the client has not received a confirmation from the server. MQTT ensures that it *will* be received, but there can be duplicates. | ||
* QoS 2 : received **exactly once** : Same as QoS 1 but there is no duplicates. | ||
- QoS 0 : received **at most once** : The packet is sent, and that's it. There is no validation about whether it has been received. | ||
- QoS 1 : received **at least once** : The packet is sent and stored as long as the client has not received a confirmation from the server. MQTT ensures that it _will_ be received, but there can be duplicates. | ||
- QoS 2 : received **exactly once** : Same as QoS 1 but there is no duplicates. | ||
@@ -832,16 +905,21 @@ About data consumption, obviously, QoS 2 > QoS 1 > QoS 0, if that's a concern to you. | ||
<a name="typescript"></a> | ||
## Usage with TypeScript | ||
This repo bundles TypeScript definition files for use in TypeScript projects and to support tools that can read `.d.ts` files. | ||
### Pre-requisites | ||
Before you can begin using these TypeScript definitions with your project, you need to make sure your project meets these requirements: | ||
* TypeScript >= 2.1 | ||
* Set tsconfig.json: `{"compilerOptions" : {"moduleResolution" : "node"}, ...}` | ||
* Includes the TypeScript definitions for Node and [ws](https://www.npmjs.com/package/ws). These types are used as | ||
parameters to some of the MQTT client's APIs and if you don't install them they get treated as `any`, which means you lose type | ||
safety. | ||
Use npm to install them by typing the following into a terminal window: | ||
`npm install --save-dev @types/node @types/ws` | ||
- TypeScript >= 2.1 | ||
- Set tsconfig.json: `{"compilerOptions" : {"moduleResolution" : "node"}, ...}` | ||
- Includes the TypeScript definitions for Node and [ws](https://www.npmjs.com/package/ws). These types are used as | ||
parameters to some of the MQTT client's APIs and if you don't install them they get treated as `any`, which means you lose type | ||
safety. | ||
Use npm to install them by typing the following into a terminal window: | ||
`npm install --save-dev @types/node @types/ws` | ||
### TypeScript example | ||
``` | ||
@@ -853,12 +931,16 @@ import * as mqtt from "mqtt" | ||
<a name="weapp-alipay"></a> | ||
## WeChat and Ali Mini Program support | ||
### WeChat Mini Program | ||
Supports [WeChat Mini Program](https://mp.weixin.qq.com/). Use the `wxs` protocol. See [the WeChat docs](https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-socket.html). | ||
```js | ||
const mqtt = require('mqtt') | ||
const client = mqtt.connect('wxs://test.mosquitto.org') | ||
const mqtt = require("mqtt"); | ||
const client = mqtt.connect("wxs://test.mosquitto.org"); | ||
``` | ||
### Ali Mini Program | ||
Supports [Ali Mini Program](https://open.alipay.com/channel/miniIndex.htm). Use the `alis` protocol. See [the Alipay docs](https://docs.alipay.com/mini/developer/getting-started). | ||
@@ -868,7 +950,8 @@ <a name="example"></a> | ||
```js | ||
const mqtt = require('mqtt') | ||
const client = mqtt.connect('alis://test.mosquitto.org') | ||
const mqtt = require("mqtt"); | ||
const client = mqtt.connect("alis://test.mosquitto.org"); | ||
``` | ||
<a name="contributing"></a> | ||
## Contributing | ||
@@ -886,13 +969,23 @@ | ||
<table><tbody> | ||
<tr><th align="left">Adam Rudd</th><td><a href="https://github.com/adamvr">GitHub/adamvr</a></td><td><a href="http://twitter.com/adam_vr">Twitter/@adam_vr</a></td></tr> | ||
<tr><th align="left">Matteo Collina</th><td><a href="https://github.com/mcollina">GitHub/mcollina</a></td><td><a href="http://twitter.com/matteocollina">Twitter/@matteocollina</a></td></tr> | ||
<tr><th align="left">Maxime Agor</th><td><a href="https://github.com/4rzael">GitHub/4rzael</a></td><td><a href="http://twitter.com/4rzael">Twitter/@4rzael</a></td></tr> | ||
<tr><th align="left">Siarhei Buntsevich</th><td><a href="https://github.com/scarry1992">GitHub/scarry1992</a></td></tr> | ||
</tbody></table> | ||
| Name | GitHub | Twitter | | ||
| ------------------ | -------------------------------------------------- | ---------------------------------------------------------- | | ||
| Adam Rudd | [GitHub/adamvr](https://github.com/adamvr) | [Twitter/@adam_vr](http://twitter.com/adam_vr) | | ||
| Matteo Collina | [GitHub/mcollina](https://github.com/mcollina) | [Twitter/@matteocollina](http://twitter.com/matteocollina) | | ||
| Maxime Agor | [GitHub/4rzael](https://github.com/4rzael) | [Twitter/@4rzael](http://twitter.com/4rzael) | | ||
| Siarhei Buntsevich | [GitHub/scarry1992](https://github.com/scarry1992) | | | ||
| Daniel Lando | [GitHub/robertsLando](https://github.com/robertsLando) | | | ||
<a name="sponsor"></a> | ||
## Sponsor | ||
If you would like to support MQTT.js, please consider sponsoring the author and active maintainers: | ||
- [Matteo Collina](https://github.com/sponsors/mcollina): author of MQTT.js | ||
- [Daniel Lando](https://github.com/sponsors/robertsLando): active maintainer | ||
<a name="license"></a> | ||
## License | ||
MIT |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
1168932
26811
942
6
28