beeb8548d77d7ef7a8cc3f8f382c68b9f9fbeffa392f860a9da615840d3c36b742e2770cda93b9aba7356a1567a810bced0749c7ae809a7e3ca2049ef83b3e 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. ![mqtt.js](https://raw.githubusercontent.com/mqttjs/MQTT.js/137ee0e3940c1f01049a30248c70f24dc6e6f829/MQTT.js.png)
  2. =======
  3. ![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)
  4. MQTT.js is a client library for the [MQTT](http://mqtt.org/) protocol, written
  5. in JavaScript for node.js and the browser.
  6. | :boom: MQTT.js vNext |
  7. |:---------------------------|
  8. | Want to contribute to the next generation of **MQTT.js**? Join the discussion [here](https://github.com/mqttjs/MQTT.js/discussions/1324). |
  9. ## Table of Contents
  10. * [__MQTT.js vNext__](#vnext)
  11. * [Upgrade notes](#notes)
  12. * [Installation](#install)
  13. * [Example](#example)
  14. * [Import Styles](#example)
  15. * [Command Line Tools](#cli)
  16. * [API](#api)
  17. * [Browser](#browser)
  18. * [About QoS](#qos)
  19. * [TypeScript](#typescript)
  20. * [Weapp and Ali support](#weapp-alipay)
  21. * [Contributing](#contributing)
  22. * [License](#license)
  23. MQTT.js is an OPEN Open Source Project, see the [Contributing](#contributing) section to find out what this means.
  24. [![JavaScript Style
  25. Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
  26. <a name="vnext"></a>
  27. ## Discussion on the next major version of MQTT.js
  28. There are discussions happening on the future of MQTT.js and the next major version (vNext). We invite the community to provide their thoughts and feedback in [this GitHub discussion](https://github.com/mqttjs/MQTT.js/discussions/1324)
  29. <a name="notes"></a>
  30. ## Important notes for existing users
  31. __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
  32. debug logging, along with some feature additions.
  33. As a __breaking change__, by default a error handler is built into the MQTT.js client, so if any
  34. errors are emitted and the user has not created an event handler on the client for errors, the client will
  35. not break as a result of unhandled errors. Additionally, typical TLS errors like `ECONNREFUSED`, `ECONNRESET` have been
  36. added to a list of TLS errors that will be emitted from the MQTT.js client, and so can be handled as connection errors.
  37. __v3.0.0__ adds support for MQTT 5, support for node v10.x, and many fixes to improve reliability.
  38. __Note:__ MQTT v5 support is experimental as it has not been implemented by brokers yet.
  39. __v2.0.0__ removes support for node v0.8, v0.10 and v0.12, and it is 3x faster in sending
  40. packets. It also removes all the deprecated functionality in v1.0.0,
  41. mainly `mqtt.createConnection` and `mqtt.Server`. From v2.0.0,
  42. subscriptions are restored upon reconnection if `clean: true`.
  43. v1.x.x is now in *LTS*, and it will keep being supported as long as
  44. there are v0.8, v0.10 and v0.12 users.
  45. As a __breaking change__, the `encoding` option in the old client is
  46. removed, and now everything is UTF-8 with the exception of the
  47. `password` in the CONNECT message and `payload` in the PUBLISH message,
  48. which are `Buffer`.
  49. Another __breaking change__ is that MQTT.js now defaults to MQTT v3.1.1,
  50. so to support old brokers, please read the [client options doc](#client).
  51. __v1.0.0__ improves the overall architecture of the project, which is now
  52. split into three components: MQTT.js keeps the Client,
  53. [mqtt-connection](http://npm.im/mqtt-connection) includes the barebone
  54. Connection code for server-side usage, and [mqtt-packet](http://npm.im/mqtt-packet)
  55. includes the protocol parser and generator. The new Client improves
  56. performance by a 30% factor, embeds Websocket support
  57. ([MOWS](http://npm.im/mows) is now deprecated), and it has a better
  58. support for QoS 1 and 2. The previous API is still supported but
  59. deprecated, as such, it is not documented in this README.
  60. <a name="install"></a>
  61. ## Installation
  62. ```sh
  63. npm install mqtt --save
  64. ```
  65. <a name="example"></a>
  66. ## Example
  67. For the sake of simplicity, let's put the subscriber and the publisher in the same file:
  68. ```js
  69. const mqtt = require('mqtt')
  70. const client = mqtt.connect('mqtt://test.mosquitto.org')
  71. client.on('connect', function () {
  72. client.subscribe('presence', function (err) {
  73. if (!err) {
  74. client.publish('presence', 'Hello mqtt')
  75. }
  76. })
  77. })
  78. client.on('message', function (topic, message) {
  79. // message is Buffer
  80. console.log(message.toString())
  81. client.end()
  82. })
  83. ```
  84. output:
  85. ```
  86. Hello mqtt
  87. ```
  88. If you want to run your own MQTT broker, you can use
  89. [Mosquitto](http://mosquitto.org) or
  90. [Aedes-cli](https://github.com/moscajs/aedes-cli), and launch it.
  91. You can also use a test instance: test.mosquitto.org.
  92. If you do not want to install a separate broker, you can try using the
  93. [Aedes](https://github.com/moscajs/aedes).
  94. to use MQTT.js in the browser see the [browserify](#browserify) section
  95. <a name="import_styles"></a>
  96. ## Import styles
  97. ### CommonJS (Require)
  98. ```js
  99. const mqtt = require('mqtt') // require mqtt
  100. const client = mqtt.connect('est.mosquitto.org') // create a client
  101. ```
  102. ### ES6 Modules (Import)
  103. #### Aliased wildcard import
  104. ```js
  105. import * as mqtt from "mqtt" // import everything inside the mqtt module and give it the namespace "mqtt"
  106. let client = mqtt.connect('mqtt://test.mosquitto.org') // create a client
  107. ```
  108. #### Importing individual components
  109. ```js
  110. import { connect } from "mqtt" // import connect from mqtt
  111. let client = connect('mqtt://test.mosquitto.org') // create a client
  112. ```
  113. <a name="promises"></a>
  114. ## Promise support
  115. If you want to use the new [async-await](https://blog.risingstack.com/async-await-node-js-7-nightly/) functionality in JavaScript, or just prefer using Promises instead of callbacks, [async-mqtt](https://github.com/mqttjs/async-mqtt) is a wrapper over MQTT.js which uses promises instead of callbacks when possible.
  116. <a name="cli"></a>
  117. ## Command Line Tools
  118. MQTT.js bundles a command to interact with a broker.
  119. In order to have it available on your path, you should install MQTT.js
  120. globally:
  121. ```sh
  122. npm install mqtt -g
  123. ```
  124. Then, on one terminal
  125. ```
  126. mqtt sub -t 'hello' -h 'test.mosquitto.org' -v
  127. ```
  128. On another
  129. ```
  130. mqtt pub -t 'hello' -h 'test.mosquitto.org' -m 'from MQTT.js'
  131. ```
  132. See `mqtt help <command>` for the command help.
  133. <a name="debug"></a>
  134. ## Debug Logs
  135. 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 :
  136. ```ps
  137. # (example using PowerShell, the VS Code default)
  138. $env:DEBUG='mqttjs*'
  139. ```
  140. <a name="reconnecting"></a>
  141. ## About Reconnection
  142. An important part of any websocket connection is what to do when a connection
  143. drops off and the client needs to reconnect. MQTT has built-in reconnection
  144. support that can be configured to behave in ways that suit the application.
  145. #### Refresh Authentication Options / Signed Urls with `transformWsUrl` (Websocket Only)
  146. When an mqtt connection drops and needs to reconnect, it's common to require
  147. that any authentication associated with the connection is kept current with
  148. the underlying auth mechanism. For instance some applications may pass an auth
  149. token with connection options on the initial connection, while other cloud
  150. services may require a url be signed with each connection.
  151. By the time the reconnect happens in the application lifecycle, the original
  152. auth data may have expired.
  153. To address this we can use a hook called `transformWsUrl` to manipulate
  154. either of the connection url or the client options at the time of a reconnect.
  155. Example (update clientId & username on each reconnect):
  156. ```
  157. const transformWsUrl = (url, options, client) => {
  158. client.options.username = `token=${this.get_current_auth_token()}`;
  159. client.options.clientId = `${this.get_updated_clientId()}`;
  160. return `${this.get_signed_cloud_url(url)`;
  161. }
  162. const connection = await mqtt.connectAsync(<wss url>, {
  163. ...,
  164. transformWsUrl: transformUrl,
  165. });
  166. ```
  167. Now every time a new WebSocket connection is opened (hopefully not too often),
  168. we will get a fresh signed url or fresh auth token data.
  169. Note: Currently this hook does _not_ support promises, meaning that in order to
  170. use the latest auth token, you must have some outside mechanism running that
  171. handles application-level authentication refreshing so that the websocket
  172. connection can simply grab the latest valid token or signed url.
  173. #### Enabling Reconnection with `reconnectPeriod` option
  174. To ensure that the mqtt client automatically tries to reconnect when the
  175. connection is dropped, you must set the client option `reconnectPeriod` to a
  176. value greater than 0. A value of 0 will disable reconnection and then terminate
  177. the final connection when it drops.
  178. The default value is 1000 ms which means it will try to reconnect 1 second
  179. after losing the connection.
  180. <a name="topicalias"></a>
  181. ## About Topic Alias Management
  182. ### Enabling automatic Topic Alias using
  183. If the client sets the option `autoUseTopicAlias:true` then MQTT.js uses existing topic alias automatically.
  184. example scenario:
  185. ```
  186. 1. PUBLISH topic:'t1', ta:1 (register)
  187. 2. PUBLISH topic:'t1' -> topic:'', ta:1 (auto use existing map entry)
  188. 3. PUBLISH topic:'t2', ta:1 (register overwrite)
  189. 4. PUBLISH topic:'t2' -> topic:'', ta:1 (auto use existing map entry based on the receent map)
  190. 5. PUBLISH topic:'t1' (t1 is no longer mapped to ta:1)
  191. ```
  192. User doesn't need to manage which topic is mapped to which topic alias.
  193. If the user want to register topic alias, then publish topic with topic alias.
  194. If the user want to use topic alias, then publish topic without topic alias. If there is a mapped topic alias then added it as a property and update the topic to empty string.
  195. ### Enabling automatic Topic Alias assign
  196. If the client sets the option `autoAssignTopicAlias:true` then MQTT.js uses existing topic alias automatically.
  197. If no topic alias exists, then assign a new vacant topic alias automatically. If topic alias is fully used, then LRU(Least Recently Used) topic-alias entry is overwritten.
  198. example scenario:
  199. ```
  200. The broker returns CONNACK (TopicAliasMaximum:3)
  201. 1. PUBLISH topic:'t1' -> 't1', ta:1 (auto assign t1:1 and register)
  202. 2. PUBLISH topic:'t1' -> '' , ta:1 (auto use existing map entry)
  203. 3. PUBLISH topic:'t2' -> 't2', ta:2 (auto assign t1:2 and register. 2 was vacant)
  204. 4. PUBLISH topic:'t3' -> 't3', ta:3 (auto assign t1:3 and register. 3 was vacant)
  205. 5. PUBLISH topic:'t4' -> 't4', ta:1 (LRU entry is overwritten)
  206. ```
  207. Also user can manually register topic-alias pair using PUBLISH topic:'some', ta:X. It works well with automatic topic alias assign.
  208. <a name="api"></a>
  209. ## API
  210. * <a href="#connect"><code>mqtt.<b>connect()</b></code></a>
  211. * <a href="#client"><code>mqtt.<b>Client()</b></code></a>
  212. * <a href="#publish"><code>mqtt.Client#<b>publish()</b></code></a>
  213. * <a href="#subscribe"><code>mqtt.Client#<b>subscribe()</b></code></a>
  214. * <a href="#unsubscribe"><code>mqtt.Client#<b>unsubscribe()</b></code></a>
  215. * <a href="#end"><code>mqtt.Client#<b>end()</b></code></a>
  216. * <a href="#removeOutgoingMessage"><code>mqtt.Client#<b>removeOutgoingMessage()</b></code></a>
  217. * <a href="#reconnect"><code>mqtt.Client#<b>reconnect()</b></code></a>
  218. * <a href="#handleMessage"><code>mqtt.Client#<b>handleMessage()</b></code></a>
  219. * <a href="#connected"><code>mqtt.Client#<b>connected</b></code></a>
  220. * <a href="#reconnecting"><code>mqtt.Client#<b>reconnecting</b></code></a>
  221. * <a href="#getLastMessageId"><code>mqtt.Client#<b>getLastMessageId()</b></code></a>
  222. * <a href="#store"><code>mqtt.<b>Store()</b></code></a>
  223. * <a href="#put"><code>mqtt.Store#<b>put()</b></code></a>
  224. * <a href="#del"><code>mqtt.Store#<b>del()</b></code></a>
  225. * <a href="#createStream"><code>mqtt.Store#<b>createStream()</b></code></a>
  226. * <a href="#close"><code>mqtt.Store#<b>close()</b></code></a>
  227. -------------------------------------------------------
  228. <a name="connect"></a>
  229. ### mqtt.connect([url], options)
  230. Connects to the broker specified by the given url and options and
  231. returns a [Client](#client).
  232. The URL can be on the following protocols: 'mqtt', 'mqtts', 'tcp',
  233. 'tls', 'ws', 'wss', 'wxs', 'alis'. The URL can also be an object as returned by
  234. [`URL.parse()`](http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost),
  235. in that case the two objects are merged, i.e. you can pass a single
  236. object with both the URL and the connect options.
  237. You can also specify a `servers` options with content: `[{ host:
  238. 'localhost', port: 1883 }, ... ]`, in that case that array is iterated
  239. at every connect.
  240. For all MQTT-related options, see the [Client](#client)
  241. constructor.
  242. -------------------------------------------------------
  243. <a name="client"></a>
  244. ### mqtt.Client(streamBuilder, options)
  245. The `Client` class wraps a client connection to an
  246. MQTT broker over an arbitrary transport method (TCP, TLS,
  247. WebSocket, ecc).
  248. `Client` automatically handles the following:
  249. * Regular server pings
  250. * QoS flow
  251. * Automatic reconnections
  252. * Start publishing before being connected
  253. The arguments are:
  254. * `streamBuilder` is a function that returns a subclass of the `Stream` class that supports
  255. the `connect` event. Typically a `net.Socket`.
  256. * `options` is the client connection options (see: the [connect packet](https://github.com/mcollina/mqtt-packet#connect)). Defaults:
  257. * `wsOptions`: is the WebSocket connection options. Default is `{}`.
  258. It's specific for WebSockets. For possible options have a look at: https://github.com/websockets/ws/blob/master/doc/ws.md.
  259. * `keepalive`: `60` seconds, set to `0` to disable
  260. * `reschedulePings`: reschedule ping messages after sending packets (default `true`)
  261. * `clientId`: `'mqttjs_' + Math.random().toString(16).substr(2, 8)`
  262. * `protocolId`: `'MQTT'`
  263. * `protocolVersion`: `4`
  264. * `clean`: `true`, set to false to receive QoS 1 and 2 messages while
  265. offline
  266. * `reconnectPeriod`: `1000` milliseconds, interval between two
  267. reconnections. Disable auto reconnect by setting to `0`.
  268. * `connectTimeout`: `30 * 1000` milliseconds, time to wait before a
  269. CONNACK is received
  270. * `username`: the username required by your broker, if any
  271. * `password`: the password required by your broker, if any
  272. * `incomingStore`: a [Store](#store) for the incoming packets
  273. * `outgoingStore`: a [Store](#store) for the outgoing packets
  274. * `queueQoSZero`: if connection is broken, queue outgoing QoS zero messages (default `true`)
  275. * `customHandleAcks`: MQTT 5 feature of custom handling puback and pubrec packets. Its callback:
  276. ```js
  277. customHandleAcks: function(topic, message, packet, done) {/*some logic wit colling done(error, reasonCode)*/}
  278. ```
  279. * `autoUseTopicAlias`: enabling automatic Topic Alias using functionality
  280. * `autoAssignTopicAlias`: enabling automatic Topic Alias assign functionality
  281. * `properties`: properties MQTT 5.0.
  282. `object` that supports the following properties:
  283. * `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`,
  284. * `receiveMaximum`: representing the Receive Maximum value `number`,
  285. * `maximumPacketSize`: representing the Maximum Packet Size the Client is willing to accept `number`,
  286. * `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`,
  287. * `requestResponseInformation`: The Client uses this value to request the Server to return Response Information in the CONNACK `boolean`,
  288. * `requestProblemInformation`: The Client uses this value to indicate whether the Reason String or User Properties are sent in the case of failures `boolean`,
  289. * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
  290. * `authenticationMethod`: the name of the authentication method used for extended authentication `string`,
  291. * `authenticationData`: Binary Data containing authentication data `binary`
  292. * `authPacket`: settings for auth packet `object`
  293. * `will`: a message that will sent by the broker automatically when
  294. the client disconnect badly. The format is:
  295. * `topic`: the topic to publish
  296. * `payload`: the message to publish
  297. * `qos`: the QoS
  298. * `retain`: the retain flag
  299. * `properties`: properties of will by MQTT 5.0:
  300. * `willDelayInterval`: representing the Will Delay Interval in seconds `number`,
  301. * `payloadFormatIndicator`: Will Message is UTF-8 Encoded Character Data or not `boolean`,
  302. * `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`,
  303. * `contentType`: describing the content of the Will Message `string`,
  304. * `responseTopic`: String which is used as the Topic Name for a response message `string`,
  305. * `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`,
  306. * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
  307. * `transformWsUrl` : optional `(url, options, client) => url` function
  308. For ws/wss protocols only. Can be used to implement signing
  309. urls which upon reconnect can have become expired.
  310. * `resubscribe` : if connection is broken and reconnects,
  311. subscribed topics are automatically subscribed again (default `true`)
  312. * `messageIdProvider`: custom messageId provider. when `new UniqueMessageIdProvider()` is set, then non conflict messageId is provided.
  313. In case mqtts (mqtt over tls) is required, the `options` object is
  314. passed through to
  315. [`tls.connect()`](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback).
  316. If you are using a **self-signed certificate**, pass the `rejectUnauthorized: false` option.
  317. Beware that you are exposing yourself to man in the middle attacks, so it is a configuration
  318. that is not recommended for production environments.
  319. If you are connecting to a broker that supports only MQTT 3.1 (not
  320. 3.1.1 compliant), you should pass these additional options:
  321. ```js
  322. {
  323. protocolId: 'MQIsdp',
  324. protocolVersion: 3
  325. }
  326. ```
  327. This is confirmed on RabbitMQ 3.2.4, and on Mosquitto < 1.3. Mosquitto
  328. version 1.3 and 1.4 works fine without those.
  329. #### Event `'connect'`
  330. `function (connack) {}`
  331. Emitted on successful (re)connection (i.e. connack rc=0).
  332. * `connack` received connack packet. When `clean` connection option is `false` and server has a previous session
  333. for `clientId` connection option, then `connack.sessionPresent` flag is `true`. When that is the case,
  334. you may rely on stored session and prefer not to send subscribe commands for the client.
  335. #### Event `'reconnect'`
  336. `function () {}`
  337. Emitted when a reconnect starts.
  338. #### Event `'close'`
  339. `function () {}`
  340. Emitted after a disconnection.
  341. #### Event `'disconnect'`
  342. `function (packet) {}`
  343. Emitted after receiving disconnect packet from broker. MQTT 5.0 feature.
  344. #### Event `'offline'`
  345. `function () {}`
  346. Emitted when the client goes offline.
  347. #### Event `'error'`
  348. `function (error) {}`
  349. Emitted when the client cannot connect (i.e. connack rc != 0) or when a
  350. parsing error occurs.
  351. The following TLS errors will be emitted as an `error` event:
  352. * `ECONNREFUSED`
  353. * `ECONNRESET`
  354. * `EADDRINUSE`
  355. * `ENOTFOUND`
  356. #### Event `'end'`
  357. `function () {}`
  358. Emitted when <a href="#end"><code>mqtt.Client#<b>end()</b></code></a> is called.
  359. If a callback was passed to `mqtt.Client#end()`, this event is emitted once the
  360. callback returns.
  361. #### Event `'message'`
  362. `function (topic, message, packet) {}`
  363. Emitted when the client receives a publish packet
  364. * `topic` topic of the received packet
  365. * `message` payload of the received packet
  366. * `packet` received packet, as defined in
  367. [mqtt-packet](https://github.com/mcollina/mqtt-packet#publish)
  368. #### Event `'packetsend'`
  369. `function (packet) {}`
  370. Emitted when the client sends any packet. This includes .published() packets
  371. as well as packets used by MQTT for managing subscriptions and connections
  372. * `packet` received packet, as defined in
  373. [mqtt-packet](https://github.com/mcollina/mqtt-packet)
  374. #### Event `'packetreceive'`
  375. `function (packet) {}`
  376. Emitted when the client receives any packet. This includes packets from
  377. subscribed topics as well as packets used by MQTT for managing subscriptions
  378. and connections
  379. * `packet` received packet, as defined in
  380. [mqtt-packet](https://github.com/mcollina/mqtt-packet)
  381. -------------------------------------------------------
  382. <a name="publish"></a>
  383. ### mqtt.Client#publish(topic, message, [options], [callback])
  384. Publish a message to a topic
  385. * `topic` is the topic to publish to, `String`
  386. * `message` is the message to publish, `Buffer` or `String`
  387. * `options` is the options to publish with, including:
  388. * `qos` QoS level, `Number`, default `0`
  389. * `retain` retain flag, `Boolean`, default `false`
  390. * `dup` mark as duplicate flag, `Boolean`, default `false`
  391. * `properties`: MQTT 5.0 properties `object`
  392. * `payloadFormatIndicator`: Payload is UTF-8 Encoded Character Data or not `boolean`,
  393. * `messageExpiryInterval`: the lifetime of the Application Message in seconds `number`,
  394. * `topicAlias`: value that is used to identify the Topic instead of using the Topic Name `number`,
  395. * `responseTopic`: String which is used as the Topic Name for a response message `string`,
  396. * `correlationData`: used by the sender of the Request Message to identify which request the Response Message is for when it is received `binary`,
  397. * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
  398. * `subscriptionIdentifier`: representing the identifier of the subscription `number`,
  399. * `contentType`: String describing the content of the Application Message `string`
  400. * `cbStorePut` - `function ()`, fired when message is put into `outgoingStore` if QoS is `1` or `2`.
  401. * `callback` - `function (err)`, fired when the QoS handling completes,
  402. or at the next tick if QoS 0. An error occurs if client is disconnecting.
  403. -------------------------------------------------------
  404. <a name="subscribe"></a>
  405. ### mqtt.Client#subscribe(topic/topic array/topic object, [options], [callback])
  406. Subscribe to a topic or topics
  407. * `topic` is a `String` topic to subscribe to or an `Array` of
  408. topics to subscribe to. It can also be an object, it has as object
  409. keys the topic name and as value the QoS, like `{'test1': {qos: 0}, 'test2': {qos: 1}}`.
  410. MQTT `topic` wildcard characters are supported (`+` - for single level and `#` - for multi level)
  411. * `options` is the options to subscribe with, including:
  412. * `qos` QoS subscription level, default 0
  413. * `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)
  414. * `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.)
  415. * `rh` Retain Handling MQTT 5.0 (This option specifies whether retained messages are sent when the subscription is established.)
  416. * `properties`: `object`
  417. * `subscriptionIdentifier`: representing the identifier of the subscription `number`,
  418. * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
  419. * `callback` - `function (err, granted)`
  420. callback fired on suback where:
  421. * `err` a subscription error or an error that occurs when client is disconnecting
  422. * `granted` is an array of `{topic, qos}` where:
  423. * `topic` is a subscribed to topic
  424. * `qos` is the granted QoS level on it
  425. -------------------------------------------------------
  426. <a name="unsubscribe"></a>
  427. ### mqtt.Client#unsubscribe(topic/topic array, [options], [callback])
  428. Unsubscribe from a topic or topics
  429. * `topic` is a `String` topic or an array of topics to unsubscribe from
  430. * `options`: options of unsubscribe.
  431. * `properties`: `object`
  432. * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
  433. * `callback` - `function (err)`, fired on unsuback. An error occurs if client is disconnecting.
  434. -------------------------------------------------------
  435. <a name="end"></a>
  436. ### mqtt.Client#end([force], [options], [callback])
  437. Close the client, accepts the following options:
  438. * `force`: passing it to true will close the client right away, without
  439. waiting for the in-flight messages to be acked. This parameter is
  440. optional.
  441. * `options`: options of disconnect.
  442. * `reasonCode`: Disconnect Reason Code `number`
  443. * `properties`: `object`
  444. * `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`,
  445. * `reasonString`: representing the reason for the disconnect `string`,
  446. * `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
  447. * `serverReference`: String which can be used by the Client to identify another Server to use `string`
  448. * `callback`: will be called when the client is closed. This parameter is
  449. optional.
  450. -------------------------------------------------------
  451. <a name="removeOutgoingMessage"></a>
  452. ### mqtt.Client#removeOutgoingMessage(mId)
  453. Remove a message from the outgoingStore.
  454. The outgoing callback will be called with Error('Message removed') if the message is removed.
  455. After this function is called, the messageId is released and becomes reusable.
  456. * `mId`: The messageId of the message in the outgoingStore.
  457. -------------------------------------------------------
  458. <a name="reconnect"></a>
  459. ### mqtt.Client#reconnect()
  460. Connect again using the same options as connect()
  461. -------------------------------------------------------
  462. <a name="handleMessage"></a>
  463. ### mqtt.Client#handleMessage(packet, callback)
  464. Handle messages with backpressure support, one at a time.
  465. Override at will, but __always call `callback`__, or the client
  466. will hang.
  467. -------------------------------------------------------
  468. <a name="connected"></a>
  469. ### mqtt.Client#connected
  470. Boolean : set to `true` if the client is connected. `false` otherwise.
  471. -------------------------------------------------------
  472. <a name="getLastMessageId"></a>
  473. ### mqtt.Client#getLastMessageId()
  474. Number : get last message id. This is for sent messages only.
  475. -------------------------------------------------------
  476. <a name="reconnecting"></a>
  477. ### mqtt.Client#reconnecting
  478. Boolean : set to `true` if the client is trying to reconnect to the server. `false` otherwise.
  479. -------------------------------------------------------
  480. <a name="store"></a>
  481. ### mqtt.Store(options)
  482. In-memory implementation of the message store.
  483. * `options` is the store options:
  484. * `clean`: `true`, clean inflight messages when close is called (default `true`)
  485. Other implementations of `mqtt.Store`:
  486. * [mqtt-level-store](http://npm.im/mqtt-level-store) which uses
  487. [Level-browserify](http://npm.im/level-browserify) to store the inflight
  488. data, making it usable both in Node and the Browser.
  489. * [mqtt-nedb-store](https://github.com/behrad/mqtt-nedb-store) which
  490. uses [nedb](https://www.npmjs.com/package/nedb) to store the inflight
  491. data.
  492. * [mqtt-localforage-store](http://npm.im/mqtt-localforage-store) which uses
  493. [localForage](http://npm.im/localforage) to store the inflight
  494. data, making it usable in the Browser without browserify.
  495. -------------------------------------------------------
  496. <a name="put"></a>
  497. ### mqtt.Store#put(packet, callback)
  498. Adds a packet to the store, a packet is
  499. anything that has a `messageId` property.
  500. The callback is called when the packet has been stored.
  501. -------------------------------------------------------
  502. <a name="createStream"></a>
  503. ### mqtt.Store#createStream()
  504. Creates a stream with all the packets in the store.
  505. -------------------------------------------------------
  506. <a name="del"></a>
  507. ### mqtt.Store#del(packet, cb)
  508. Removes a packet from the store, a packet is
  509. anything that has a `messageId` property.
  510. The callback is called when the packet has been removed.
  511. -------------------------------------------------------
  512. <a name="close"></a>
  513. ### mqtt.Store#close(cb)
  514. Closes the Store.
  515. <a name="browser"></a>
  516. ## Browser
  517. <a name="cdn"></a>
  518. ### Via CDN
  519. The MQTT.js bundle is available through http://unpkg.com, specifically
  520. at https://unpkg.com/mqtt/dist/mqtt.min.js.
  521. See http://unpkg.com for the full documentation on version ranges.
  522. <a name="browserify"></a>
  523. ### Browserify
  524. In order to use MQTT.js as a browserify module you can either require it in your browserify bundles or build it as a stand alone module. The exported module is AMD/CommonJs compatible and it will add an object in the global space.
  525. ```bash
  526. mkdir tmpdir
  527. cd tmpdir
  528. npm install mqtt
  529. npm install browserify
  530. npm install tinyify
  531. cd node_modules/mqtt/
  532. npm install .
  533. npx browserify mqtt.js -s mqtt >browserMqtt.js // use script tag
  534. # show size for compressed browser transfer
  535. gzip <browserMqtt.js | wc -c
  536. ```
  537. **Be sure to only use this bundle with `ws` or `wss` URLs in the browser. Others URL types will likey fail**
  538. <a name="webpack"></a>
  539. ### Webpack
  540. Just like browserify, export MQTT.js as library. The exported module would be `const mqtt = xxx` and it will add an object in the global space. You could also export module in other [formats (AMD/CommonJS/others)](http://webpack.github.io/docs/configuration.html#output-librarytarget) by setting **output.libraryTarget** in webpack configuration.
  541. ```javascript
  542. npm install -g webpack // install webpack
  543. cd node_modules/mqtt
  544. npm install . // install dev dependencies
  545. webpack mqtt.js ./browserMqtt.js --output-library mqtt
  546. ```
  547. you can then use mqtt.js in the browser with the same api than node's one.
  548. ```html
  549. <html>
  550. <head>
  551. <title>test Ws mqtt.js</title>
  552. </head>
  553. <body>
  554. <script src="./browserMqtt.js"></script>
  555. <script>
  556. const client = mqtt.connect() // you add a ws:// url here
  557. client.subscribe("mqtt/demo")
  558. client.on("message", function (topic, payload) {
  559. alert([topic, payload].join(": "))
  560. client.end()
  561. })
  562. client.publish("mqtt/demo", "hello world!")
  563. </script>
  564. </body>
  565. </html>
  566. ```
  567. ### React
  568. ```
  569. npm install -g webpack // Install webpack globally
  570. npm install mqtt // Install MQTT library
  571. cd node_modules/mqtt
  572. npm install . // Install dev deps at current dir
  573. webpack mqtt.js --output-library mqtt // Build
  574. // now you can import the library with ES6 import, commonJS not tested
  575. ```
  576. ```javascript
  577. import React from 'react';
  578. import mqtt from 'mqtt';
  579. export default () => {
  580. const [connectionStatus, setConnectionStatus] = React.useState(false);
  581. const [messages, setMessages] = React.useState([]);
  582. useEffect(() => {
  583. const client = mqtt.connect(SOME_URL);
  584. client.on('connect', () => setConnectionStatus(true));
  585. client.on('message', (topic, payload, packet) => {
  586. setMessages(messages.concat(payload.toString()));
  587. });
  588. }, []);
  589. return (
  590. <>
  591. {messages.map((message) => (
  592. <h2>{message}</h2>
  593. )
  594. </>
  595. )
  596. }
  597. ```
  598. Your broker should accept websocket connection (see [MQTT over Websockets](https://github.com/moscajs/aedes/blob/master/docs/Examples.md#mqtt-server-over-websocket-using-server-factory) to setup [Aedes](https://github.com/moscajs/aedes)).
  599. <a name="qos"></a>
  600. ## About QoS
  601. Here is how QoS works:
  602. * QoS 0 : received **at most once** : The packet is sent, and that's it. There is no validation about whether it has been received.
  603. * 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.
  604. * QoS 2 : received **exactly once** : Same as QoS 1 but there is no duplicates.
  605. About data consumption, obviously, QoS 2 > QoS 1 > QoS 0, if that's a concern to you.
  606. <a name="typescript"></a>
  607. ## Usage with TypeScript
  608. This repo bundles TypeScript definition files for use in TypeScript projects and to support tools that can read `.d.ts` files.
  609. ### Pre-requisites
  610. Before you can begin using these TypeScript definitions with your project, you need to make sure your project meets a few of these requirements:
  611. * TypeScript >= 2.1
  612. * Set tsconfig.json: `{"compilerOptions" : {"moduleResolution" : "node"}, ...}`
  613. * Includes the TypeScript definitions for node. You can use npm to install this by typing the following into a terminal window:
  614. `npm install --save-dev @types/node`
  615. ### Typescript example
  616. ```
  617. import * as mqtt from "mqtt"
  618. let client : mqtt.MqttClient = mqtt.connect('mqtt://test.mosquitto.org')
  619. ```
  620. <a name="weapp-alipay"></a>
  621. ## WeChat and Ali Mini Program support
  622. ### WeChat Mini Program
  623. 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).
  624. ```js
  625. const mqtt = require('mqtt')
  626. const client = mqtt.connect('wxs://test.mosquitto.org')
  627. ```
  628. ### Ali Mini Program
  629. 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).
  630. <a name="example"></a>
  631. ```js
  632. const mqtt = require('mqtt')
  633. const client = mqtt.connect('alis://test.mosquitto.org')
  634. ```
  635. <a name="contributing"></a>
  636. ## Contributing
  637. MQTT.js is an **OPEN Open Source Project**. This means that:
  638. > Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.
  639. See the [CONTRIBUTING.md](https://github.com/mqttjs/MQTT.js/blob/master/CONTRIBUTING.md) file for more details.
  640. ### Contributors
  641. MQTT.js is only possible due to the excellent work of the following contributors:
  642. <table><tbody>
  643. <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>
  644. <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>
  645. <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>
  646. <tr><th align="left">Siarhei Buntsevich</th><td><a href="https://github.com/scarry1992">GitHub/scarry1992</a></td></tr>
  647. </tbody></table>
  648. <a name="license"></a>
  649. ## License
  650. MIT