Browse Source

设备详情数据绑定更新

lixing 11 months ago
parent
commit
21b40f9916
65 changed files with 20 additions and 8111 deletions
  1. 1 1
      src/utils/hooks.ts
  2. 0 27
      src/utils/mqtt/CONTRIBUTING.md
  3. 0 15
      src/utils/mqtt/LICENSE.md
  4. 0 612
      src/utils/mqtt/README.md
  5. 0 145
      src/utils/mqtt/bin/pub.js
  6. 0 123
      src/utils/mqtt/bin/sub.js
  7. 0 8
      src/utils/mqtt/doc/help.txt
  8. 0 26
      src/utils/mqtt/doc/publish.txt
  9. 0 26
      src/utils/mqtt/doc/subscribe.txt
  10. 0 24
      src/utils/mqtt/examples/client/secure-client.js
  11. 0 13
      src/utils/mqtt/examples/client/simple-both.js
  12. 0 7
      src/utils/mqtt/examples/client/simple-publish.js
  13. 0 9
      src/utils/mqtt/examples/client/simple-subscribe.js
  14. 0 34
      src/utils/mqtt/examples/tls client/crt.ca.cg.pem
  15. 0 48
      src/utils/mqtt/examples/tls client/mqttclient.js
  16. 0 13
      src/utils/mqtt/examples/tls client/tls-cert.pem
  17. 0 15
      src/utils/mqtt/examples/tls client/tls-key.pem
  18. 0 49
      src/utils/mqtt/examples/wss/client.js
  19. 0 58
      src/utils/mqtt/examples/wss/client_with_proxy.js
  20. 0 1129
      src/utils/mqtt/lib/client.js
  21. 0 149
      src/utils/mqtt/lib/connect/index.js
  22. 0 19
      src/utils/mqtt/lib/connect/tcp.js
  23. 0 41
      src/utils/mqtt/lib/connect/tls.js
  24. 0 92
      src/utils/mqtt/lib/connect/ws.js
  25. 0 110
      src/utils/mqtt/lib/connect/wx.js
  26. 0 140
      src/utils/mqtt/lib/store.js
  27. 0 52
      src/utils/mqtt/lib/validations.js
  28. 0 41
      src/utils/mqtt/mqtt.js
  29. 0 107
      src/utils/mqtt/package.json
  30. 0 2667
      src/utils/mqtt/test/abstract_client.js
  31. 0 135
      src/utils/mqtt/test/abstract_store.js
  32. 0 132
      src/utils/mqtt/test/browser/server.js
  33. 0 92
      src/utils/mqtt/test/browser/test.js
  34. 0 93
      src/utils/mqtt/test/browser/wx.js
  35. 0 544
      src/utils/mqtt/test/client.js
  36. 0 16
      src/utils/mqtt/test/helpers/private-csr.pem
  37. 0 27
      src/utils/mqtt/test/helpers/private-key.pem
  38. 0 19
      src/utils/mqtt/test/helpers/public-cert.pem
  39. 0 9
      src/utils/mqtt/test/helpers/public-key.pem
  40. 0 52
      src/utils/mqtt/test/helpers/server.js
  41. 0 9
      src/utils/mqtt/test/helpers/server_process.js
  42. 0 14
      src/utils/mqtt/test/helpers/tls-cert.pem
  43. 0 11
      src/utils/mqtt/test/helpers/tls-csr.pem
  44. 0 15
      src/utils/mqtt/test/helpers/tls-key.pem
  45. 0 13
      src/utils/mqtt/test/helpers/wrong-cert.pem
  46. 0 11
      src/utils/mqtt/test/helpers/wrong-csr.pem
  47. 0 15
      src/utils/mqtt/test/helpers/wrong-key.pem
  48. 0 4
      src/utils/mqtt/test/mocha.opts
  49. 0 230
      src/utils/mqtt/test/mqtt.js
  50. 0 9
      src/utils/mqtt/test/mqtt_store.js
  51. 0 157
      src/utils/mqtt/test/secure_client.js
  52. 0 65
      src/utils/mqtt/test/server.js
  53. 0 10
      src/utils/mqtt/test/store.js
  54. 0 22
      src/utils/mqtt/test/typescript/broker-connect-subscribe-and-publish.ts
  55. 0 14
      src/utils/mqtt/test/typescript/tsconfig.json
  56. 0 13
      src/utils/mqtt/test/util.js
  57. 0 144
      src/utils/mqtt/test/websocket_client.js
  58. 0 27
      src/utils/mqtt/types/index.d.ts
  59. 0 137
      src/utils/mqtt/types/lib/client-options.d.ts
  60. 0 196
      src/utils/mqtt/types/lib/client.d.ts
  61. 0 10
      src/utils/mqtt/types/lib/connect/index.d.ts
  62. 0 6
      src/utils/mqtt/types/lib/store-options.d.ts
  63. 0 46
      src/utils/mqtt/types/lib/store.d.ts
  64. 11 9
      src/views/equipment-center/real-time-data/european-gourd.vue
  65. 8 5
      src/views/equipment-center/real-time-data/index.vue

+ 1 - 1
src/utils/hooks.ts

@@ -2,7 +2,7 @@ import { reactive } from 'vue'
 import router from '@/router'
 import { useSidebarStore } from '@/store/sidebar'
 import { fetchDeviceInfo } from '@/api/deviceAuthorize'
-import '@/utils/mqtt/dist/mqtt.min'
+import '../../public/mqtt/dist/mqtt.min'
 interface IModal {
   // 是否显示,隐藏对话框
   open: boolean

+ 0 - 27
src/utils/mqtt/CONTRIBUTING.md

@@ -1,27 +0,0 @@
-# MQTT.js is an OPEN Open Source Project
-
------------------------------------------
-
-## What?
-
-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.
-
-## Rules
-
-There are a few basic ground-rules for contributors:
-
-1. **No `--force` pushes** or modifying the Git history in any way.
-1. **Non-master branches** ought to be used for ongoing work.
-1. **External API changes and significant modifications** ought to be subject to an **internal pull-request** to solicit feedback from other contributors.
-1. Internal pull-requests to solicit feedback are *encouraged* for any other non-trivial contribution but left to the discretion of the contributor.
-1. Contributors should attempt to adhere to the prevailing code-style.
-
-## Releases
-
-Declaring formal releases remains the prerogative of the project maintainer.
-
-## Changes to this arrangement
-
-This is an experiment and feedback is welcome! This document may also be subject to pull-requests or changes by contributors where you believe you have something valuable to add or change.
-
------------------------------------------

+ 0 - 15
src/utils/mqtt/LICENSE.md

@@ -1,15 +0,0 @@
-The MIT License (MIT)
-=====================
-
-Copyright (c) 2015-2016 MQTT.js contributors
----------------------------------------
-
-*MQTT.js contributors listed at <https://github.com/mqttjs/MQTT.js#contributors>*
-
-Copyright 2011-2014 by Adam Rudd
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 0 - 612
src/utils/mqtt/README.md

@@ -1,612 +0,0 @@
-![mqtt.js](https://raw.githubusercontent.com/mqttjs/MQTT.js/137ee0e3940c1f01049a30248c70f24dc6e6f829/MQTT.js.png)
-=======
-
-[![Build Status](https://travis-ci.org/mqttjs/MQTT.js.svg)](https://travis-ci.org/mqttjs/MQTT.js) [![codecov](https://codecov.io/gh/mqttjs/MQTT.js/branch/master/graph/badge.svg)](https://codecov.io/gh/mqttjs/MQTT.js)
-
-[![NPM](https://nodei.co/npm-dl/mqtt.png)](https://nodei.co/npm/mqtt/) [![NPM](https://nodei.co/npm/mqtt.png)](https://nodei.co/npm/mqtt/)
-
-[![Sauce Test Status](https://saucelabs.com/browser-matrix/mqttjs.svg)](https://saucelabs.com/u/mqttjs)
-
-MQTT.js is a client library for the [MQTT](http://mqtt.org/) protocol, written
-in JavaScript for node.js and the browser.
-
-* [Upgrade notes](#notes)
-* [Installation](#install)
-* [Example](#example)
-* [Command Line Tools](#cli)
-* [API](#api)
-* [Browser](#browser)
-* [Weapp](#weapp)
-* [About QoS](#qos)
-* [TypeScript](#typescript)
-* [Contributing](#contributing)
-* [License](#license)
-
-MQTT.js is an OPEN Open Source Project, see the [Contributing](#contributing) section to find out what this means.
-
-[![JavaScript Style
-Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
-
-
-<a name="notes"></a>
-## Important notes for existing users
-
-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
-there are v0.8, v0.10 and v0.12 users.
-
-v1.0.0 improves the overall architecture of the project, which is now
-split into three components: MQTT.js keeps the Client,
-[mqtt-connection](http://npm.im/mqtt-connection) includes the barebone
-Connection code for server-side usage, and [mqtt-packet](http://npm.im/mqtt-packet)
-includes the protocol parser and generator. The new Client improves
-performance by a 30% factor, embeds Websocket support
-([MOWS](http://npm.im/mows) is now deprecated), and it has a better
-support for QoS 1 and 2. The previous API is still supported but
-deprecated, as such, it is not documented in this README.
-
-As a __breaking change__, the `encoding` option in the old client is
-removed, and now everything is UTF-8 with the exception of the
-`password` in the CONNECT message and `payload` in the PUBLISH message,
-which are `Buffer`.
-
-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).
-
-<a name="install"></a>
-## Installation
-
-```sh
-npm install mqtt --save
-```
-
-<a name="example"></a>
-## Example
-
-For the sake of simplicity, let's put the subscriber and the publisher in the same file:
-
-```js
-var mqtt = require('mqtt')
-var client  = mqtt.connect('mqtt://test.mosquitto.org')
-
-client.on('connect', function () {
-  client.subscribe('presence', function (err) {
-    if (!err) {
-      client.publish('presence', 'Hello mqtt')
-    }
-  })
-})
-
-client.on('message', function (topic, message) {
-  // message is Buffer
-  )
-  client.end()
-})
-```
-
-output:
-```
-Hello mqtt
-```
-
-If you want to run your own MQTT broker, you can use
-[Mosquitto](http://mosquitto.org) or
-[Mosca](http://mcollina.github.io/mosca/), and launch it.
-You can also use a test instance: test.mosquitto.org and test.mosca.io
-are both public.
-
-If you do not want to install a separate broker, you can try using the
-[mqtt-connection](https://www.npmjs.com/package/mqtt-connection).
-
-to use MQTT.js in the browser see the [browserify](#browserify) section
-
-<a name="promises"></a>
-## Promise support
-
-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.
-
-<a name="cli"></a>
-## Command Line Tools
-
-MQTT.js bundles a command to interact with a broker.
-In order to have it available on your path, you should install MQTT.js
-globally:
-
-```sh
-npm install mqtt -g
-```
-
-Then, on one terminal
-
-```
-mqtt sub -t 'hello' -h 'test.mosquitto.org' -v
-```
-
-On another
-
-```
-mqtt pub -t 'hello' -h 'test.mosquitto.org' -m 'from MQTT.js'
-```
-
-See `mqtt help <command>` for the command help.
-
-<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 name="connect"></a>
-### mqtt.connect([url], options)
-
-Connects to the broker specified by the given url and options and
-returns a [Client](#client).
-
-The URL can be on the following protocols: 'mqtt', 'mqtts', 'tcp',
-'tls', 'ws', 'wss'. The URL can also be an object as returned by
-[`URL.parse()`](http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost),
-in that case the two objects are merged, i.e. you can pass a single
-object with both the URL and the connect options.
-
-You can also specify a `servers` options with content: `[{ host:
-'localhost', port: 1883 }, ... ]`, in that case that array is iterated
-at every connect.
-
-For all MQTT-related options, see the [Client](#client)
-constructor.
-
--------------------------------------------------------
-<a name="client"></a>
-### mqtt.Client(streamBuilder, options)
-
-The `Client` class wraps a client connection to an
-MQTT broker over an arbitrary transport method (TCP, TLS,
-WebSocket, ecc).
-
-`Client` automatically handles the following:
-
-* 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
-    offline
-  * `reconnectPeriod`: `1000` milliseconds, interval between two
-    reconnections
-  * `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`)
-  * `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
-  * `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`)
-
-In case mqtts (mqtt over tls) is required, the `options` object is
-passed through to
-[`tls.connect()`](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback).
-If you are using a **self-signed certificate**, pass the `rejectUnauthorized: false` option.
-Beware that you are exposing yourself to man in the middle attacks, so it is a configuration
-that is not recommended for production environments.
-
-If you are connecting to a broker that supports only MQTT 3.1 (not
-3.1.1 compliant), you should pass these additional options:
-
-```js
-{
-  protocolId: 'MQIsdp',
-  protocolVersion: 3
-}
-```
-
-This is confirmed on RabbitMQ 3.2.4, and on Mosquitto < 1.3. Mosquitto
-version 1.3 and 1.4 works fine without those.
-
-#### Event `'connect'`
-
-`function (connack) {}`
-
-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.
-
-#### Event `'reconnect'`
-
-`function () {}`
-
-Emitted when a reconnect starts.
-
-#### Event `'close'`
-
-`function () {}`
-
-Emitted after a disconnection.
-
-#### Event `'offline'`
-
-`function () {}`
-
-Emitted when the client goes offline.
-
-#### Event `'error'`
-
-`function (error) {}`
-
-Emitted when the client cannot connect (i.e. connack rc != 0) or when a
-parsing error occurs.
-
-#### Event `'end'`
-
-`function () {}`
-
-Emitted when <a href="#end"><code>mqtt.Client#<b>end()</b></code></a> is called.
-If a callback was passed to `mqtt.Client#end()`, this event is emitted once the
-callback returns.
-
-#### Event `'message'`
-
-`function (topic, message, packet) {}`
-
-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
-  [mqtt-packet](https://github.com/mcollina/mqtt-packet#publish)
-
-#### Event `'packetsend'`
-
-`function (packet) {}`
-
-Emitted when the client sends any packet. This includes .published() packets
-as well as packets used by MQTT for managing subscriptions and connections
-* `packet` received packet, as defined in
-  [mqtt-packet](https://github.com/mcollina/mqtt-packet)
-
-#### Event `'packetreceive'`
-
-`function (packet) {}`
-
-Emitted when the client receives any packet. This includes packets from
-subscribed topics as well as packets used by MQTT for managing subscriptions
-and connections
-* `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])
-
-Publish a message to a topic
-
-* `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`
-* `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])
-
-Subscribe to a topic or topics
-
-* `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': 0, 'test2': 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
-* `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
-
--------------------------------------------------------
-<a name="unsubscribe"></a>
-### mqtt.Client#unsubscribe(topic/topic array, [callback])
-
-Unsubscribe from a topic or topics
-
-* `topic` is a `String` topic or an array of topics to unsubscribe from
-* `callback` - `function (err)`, fired on unsuback. An error occurs if client is disconnecting.
-
--------------------------------------------------------
-<a name="end"></a>
-### mqtt.Client#end([force], [cb])
-
-Close the client, accepts the following options:
-
-* `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.
-* `cb`: will be called when the client is closed. This parameter is
-  optional.
-
--------------------------------------------------------
-<a name="removeOutgoingMessage"></a>
-### mqtt.Client#removeOutgoingMessage(mid)
-
-Remove a message from the outgoingStore.
-The outgoing callback will be called with Error('Message removed') if the message is removed.
-
-After this function is called, the messageId is released and becomes reusable.
-
-* `mid`: The messageId of the message in the outgoingStore.
-
--------------------------------------------------------
-<a name="reconnect"></a>
-### mqtt.Client#reconnect()
-
-Connect again using the same options as connect()
-
--------------------------------------------------------
-<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
-will hang.
-
--------------------------------------------------------
-<a name="connected"></a>
-### mqtt.Client#connected
-
-Boolean : set to `true` if the client is connected. `false` otherwise.
-
--------------------------------------------------------
-<a name="getLastMessageId"></a>
-### mqtt.Client#getLastMessageId()
-
-Number : get last message id. This is for sent messages only.
-
--------------------------------------------------------
-<a name="reconnecting"></a>
-### mqtt.Client#reconnecting
-
-Boolean : set to `true` if the client is trying to reconnect to the server. `false` otherwise.
-
--------------------------------------------------------
-<a name="store"></a>
-### mqtt.Store(options)
-
-In-memory implementation of the message store.
-
-* `options` is the store options:
-  * `clean`: `true`, clean inflight messages when close is called (default `true`)
-
-Other implementations of `mqtt.Store`:
-
-* [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-nedbb-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
-  [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)
-
-Adds a packet to the store, a packet is
-anything that has a `messageId` property.
-The callback is called when the packet has been stored.
-
--------------------------------------------------------
-<a name="createStream"></a>
-### mqtt.Store#createStream()
-
-Creates a stream with all the packets in the store.
-
--------------------------------------------------------
-<a name="del"></a>
-### mqtt.Store#del(packet, cb)
-
-Removes a packet from the store, a packet is
-anything that has a `messageId` property.
-The callback is called when the packet has been removed.
-
--------------------------------------------------------
-<a name="close"></a>
-### mqtt.Store#close(cb)
-
-Closes the Store.
-
-<a name="browser"></a>
-## Browser
-
-<a name="cdn"></a>
-### Via CDN
-
-The MQTT.js bundle is available through http://unpkg.com, specifically
-at https://unpkg.com/mqtt/dist/mqtt.min.js.
-See http://unpkg.com for the full documentation on version ranges.
-
-<a name="weapp"></a>
-## Weixin App
-Surport [Weixin App](https://mp.weixin.qq.com/). See [Doc](https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-socket.html).
-<a name="example"></a>
-
-## Example(js)
-
-```js
-var mqtt = require('mqtt')
-var client  = mqtt.connect('wxs://test.mosquitto.org')
-```
-
-## Example(ts)
-
-```ts
-import { connect } from 'mqtt';
-const client  = connect('wxs://test.mosquitto.org');
-```
-
-<a name="browserify"></a>
-### Browserify
-
-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.
-
-```javascript
-npm install -g browserify // install browserify
-cd node_modules/mqtt
-npm install . // install dev dependencies
-browserify mqtt.js -s mqtt > browserMqtt.js // require mqtt in your client-side app
-```
-
-<a name="webpack"></a>
-### Webpack
-
-Just like browserify, export MQTT.js as library. The exported module would be `var 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.
-
-```javascript
-npm install -g webpack // install webpack
-
-cd node_modules/mqtt
-npm install . // install dev dependencies
-webpack mqtt.js ./browserMqtt.js --output-library mqtt
-```
-
-you can then use mqtt.js in the browser with the same api than node's one.
-
-```html
-<html>
-<head>
-  <title>test Ws mqtt.js</title>
-</head>
-<body>
-<script src="./browserMqtt.js"></script>
-<script>
-  var 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.publish("mqtt/demo", "hello world!")
-</script>
-</body>
-</html>
-```
-
-Your broker should accept websocket connection (see [MQTT over Websockets](https://github.com/mcollina/mosca/wiki/MQTT-over-Websockets) to setup [Mosca](http://mcollina.github.io/mosca/)).
-
-<a name="signedurls"></a>
-### Signed WebSocket Urls
-
-If you need to sign an url, for example for [AWS IoT](http://docs.aws.amazon.com/iot/latest/developerguide/protocols.html#mqtt-ws),
-then you can pass in a `transformWsUrl` function to the <a href="#connect"><code>mqtt.<b>connect()</b></code></a> options
-This is needed because signed urls have an expiry and eventually upon reconnects, a new signed url needs to be created:
-
-```js
-// This module doesn't actually exist, just an example
-var awsIotUrlSigner = require('awsIotUrlSigner')
-mqtt.connect('wss://a2ukbzaqo9vbpb.iot.ap-southeast-1.amazonaws.com/mqtt', {
-  transformWsUrl: function (url, options, client) {
-    // It's possible to inspect some state on options(pre parsed url components)
-    // and the client (reconnect state etc)
-    return awsIotUrlSigner(url)
-  }
-})
-
-// Now every time a new WebSocket connection is opened (hopefully not that
-// often) we get a freshly signed url
-
-```
-
-<a name="qos"></a>
-## About QoS
-
-Here is how QoS works:
-
-* 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.
-
-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 a few of these requirements:
- * TypeScript >= 2.1
- * Set tsconfig.json: `{"compilerOptions" : {"moduleResolution" : "node"}, ...}`
- * Includes the TypeScript definitions for node. You can use npm to install this by typing the following into a terminal window:
-   `npm install --save-dev @types/node`
-
-<a name="contributing"></a>
-## Contributing
-
-MQTT.js is an **OPEN Open Source Project**. This means that:
-
-> 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.
-
-See the [CONTRIBUTING.md](https://github.com/mqttjs/MQTT.js/blob/master/CONTRIBUTING.md) file for more details.
-
-### Contributors
-
-MQTT.js is only possible due to the excellent work of the following contributors:
-
-<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>
-</tbody></table>
-
-<a name="license"></a>
-## License
-
-MIT

+ 0 - 145
src/utils/mqtt/bin/pub.js

@@ -1,145 +0,0 @@
-#!/usr/bin/env node
-var mqtt = require('../')
-var pump = require('pump')
-var path = require('path')
-var fs = require('fs')
-var concat = require('concat-stream')
-var Writable = require('readable-stream').Writable
-var helpMe = require('help-me')({
-  dir: path.join(__dirname, '..', 'doc')
-})
-var minimist = require('minimist')
-var split2 = require('split2')
-
-function send(args) {
-  var client = mqtt.connect(args)
-  client.on('connect', function () {
-    client.publish(args.topic, args.message, args, function (err) {
-      if (err) {
-        console.warn(err)
-      }
-      client.end()
-    })
-  })
-  client.on('error', function (err) {
-    console.warn(err)
-    client.end()
-  })
-}
-
-function multisend(args) {
-  var client = mqtt.connect(args)
-  var sender = new Writable({
-    objectMode: true
-  })
-  sender._write = function (line, enc, cb) {
-    client.publish(args.topic, line.trim(), args, cb)
-  }
-
-  client.on('connect', function () {
-    pump(process.stdin, split2(), sender, function (err) {
-      client.end()
-      if (err) {
-        throw err
-      }
-    })
-  })
-}
-
-function start(args) {
-  args = minimist(args, {
-    string: ['hostname', 'username', 'password', 'key', 'cert', 'ca', 'message', 'clientId', 'i', 'id'],
-    boolean: ['stdin', 'retain', 'help', 'insecure', 'multiline'],
-    alias: {
-      port: 'p',
-      hostname: ['h', 'host'],
-      topic: 't',
-      message: 'm',
-      qos: 'q',
-      clientId: ['i', 'id'],
-      retain: 'r',
-      username: 'u',
-      password: 'P',
-      stdin: 's',
-      multiline: 'M',
-      protocol: ['C', 'l'],
-      help: 'H',
-      ca: 'cafile'
-    },
-    default: {
-      host: 'localhost',
-      qos: 0,
-      retain: false,
-      topic: '',
-      message: ''
-    }
-  })
-
-  if (args.help) {
-    return helpMe.toStdout('publish')
-  }
-
-  if (args.key) {
-    args.key = fs.readFileSync(args.key)
-  }
-
-  if (args.cert) {
-    args.cert = fs.readFileSync(args.cert)
-  }
-
-  if (args.ca) {
-    args.ca = fs.readFileSync(args.ca)
-  }
-
-  if (args.key && args.cert && !args.protocol) {
-    args.protocol = 'mqtts'
-  }
-
-  if (args.port) {
-    if (typeof args.port !== 'number') {
-      console.warn("# Port: number expected, '%s' was given.", typeof args.port)
-      return
-    }
-  }
-
-  if (args['will-topic']) {
-    args.will = {}
-    args.will.topic = args['will-topic']
-    args.will.payload = args['will-message']
-    args.will.qos = args['will-qos']
-    args.will.retain = args['will-retain']
-  }
-
-  if (args.insecure) {
-    args.rejectUnauthorized = false
-  }
-
-  args.topic = (args.topic || args._.shift()).toString()
-  args.message = (args.message || args._.shift()).toString()
-
-  if (!args.topic) {
-    console.error('missing topic\n')
-    return helpMe.toStdout('publish')
-  }
-
-  if (args.stdin) {
-    if (args.multiline) {
-      multisend(args)
-    } else {
-      process.stdin.pipe(
-        concat(function (data) {
-          args.message = data
-          send(args)
-        })
-      )
-    }
-  } else {
-    send(args)
-  }
-}
-
-module.exports = start
-
-if (require.main === module) {
-  start(process.argv.slice(2))
-}

+ 0 - 123
src/utils/mqtt/bin/sub.js

@@ -1,123 +0,0 @@
-#!/usr/bin/env node
-
-var mqtt = require('../')
-var path = require('path')
-var fs = require('fs')
-var helpMe = require('help-me')({
-  dir: path.join(__dirname, '..', 'doc')
-})
-var minimist = require('minimist')
-
-function start (args) {
-  args = minimist(args, {
-    string: ['hostname', 'username', 'password', 'key', 'cert', 'ca', 'clientId', 'i', 'id'],
-    boolean: ['stdin', 'help', 'clean', 'insecure'],
-    alias: {
-      port: 'p',
-      hostname: ['h', 'host'],
-      topic: 't',
-      qos: 'q',
-      clean: 'c',
-      keepalive: 'k',
-      clientId: ['i', 'id'],
-      username: 'u',
-      password: 'P',
-      protocol: ['C', 'l'],
-      verbose: 'v',
-      help: '-H',
-      ca: 'cafile'
-    },
-    default: {
-      host: 'localhost',
-      qos: 0,
-      retain: false,
-      clean: true,
-      keepAlive: 30 // 30 sec
-    }
-  })
-
-  if (args.help) {
-    return helpMe.toStdout('subscribe')
-  }
-
-  args.topic = args.topic || args._.shift()
-
-  if (!args.topic) {
-    console.error('missing topic\n')
-    return helpMe.toStdout('subscribe')
-  }
-
-  if (args.key) {
-    args.key = fs.readFileSync(args.key)
-  }
-
-  if (args.cert) {
-    args.cert = fs.readFileSync(args.cert)
-  }
-
-  if (args.ca) {
-    args.ca = fs.readFileSync(args.ca)
-  }
-
-  if (args.key && args.cert && !args.protocol) {
-    args.protocol = 'mqtts'
-  }
-
-  if (args.insecure) {
-    args.rejectUnauthorized = false
-  }
-
-  if (args.port) {
-    if (typeof args.port !== 'number') {
-      console.warn('# Port: number expected, \'%s\' was given.', typeof args.port)
-      return
-    }
-  }
-
-  if (args['will-topic']) {
-    args.will = {}
-    args.will.topic = args['will-topic']
-    args.will.payload = args['will-message']
-    args.will.qos = args['will-qos']
-    args.will.retain = args['will-retain']
-  }
-
-  args.keepAlive = args['keep-alive']
-
-  var client = mqtt.connect(args)
-
-  client.on('connect', function () {
-    client.subscribe(args.topic, { qos: args.qos }, function (err, result) {
-      if (err) {
-        console.error(err)
-        process.exit(1)
-      }
-
-      result.forEach(function (sub) {
-        if (sub.qos > 2) {
-          console.error('subscription negated to', sub.topic, 'with code', sub.qos)
-          process.exit(1)
-        }
-      })
-    })
-  })
-
-  client.on('message', function (topic, payload) {
-    if (args.verbose) {
-      console.log(topic, payload.toString())
-    } else {
-      console.log(payload.toString())
-    }
-  })
-
-  client.on('error', function (err) {
-    console.warn(err)
-    client.end()
-  })
-}
-
-module.exports = start
-
-if (require.main === module) {
-  start(process.argv.slice(2))
-}

+ 0 - 8
src/utils/mqtt/doc/help.txt

@@ -1,8 +0,0 @@
-MQTT.js command line interface, available commands are:
-
-  * publish     publish a message to the broker
-  * subscribe   subscribe for updates from the broker
-  * version     the current MQTT.js version
-  * help        help about commands
-
-Launch 'mqtt help [command]' to know more about the commands.

+ 0 - 26
src/utils/mqtt/doc/publish.txt

@@ -1,26 +0,0 @@
-Usage: mqtt publish [opts] topic [message]
-
-Available options:
-
-  -h/--hostname HOST    the broker host
-  -p/--port PORT        the broker port
-  -i/--client-id ID     the client id
-  -q/--qos 0/1/2        the QoS of the message
-  -t/--topic TOPIC      the message topic
-  -m/--message MSG      the message body
-  -r/--retain           send a retained message
-  -s/--stdin            read the message body from stdin
-  -M/--multiline        read lines from stdin as multiple messages 
-  -u/--username USER    the username
-  -P/--password PASS    the password
-  -C/--protocol PROTO   the protocol to use, 'mqtt',
-                        'mqtts', 'ws' or 'wss'
-  --key PATH            path to the key file
-  --cert PATH           path to the cert file
-  --ca PATH             path to the ca certificate
-  --insecure            do not verify the server certificate
-  --will-topic TOPIC    the will topic
-  --will-payload BODY   the will message
-  --will-qos 0/1/2      the will qos
-  --will-retain         send a will retained message 
-  -H/--help             show this

+ 0 - 26
src/utils/mqtt/doc/subscribe.txt

@@ -1,26 +0,0 @@
-Usage: mqtt subscribe [opts] [topic]
-
-Available options:
-
-  -h/--hostname HOST    the broker host
-  -p/--port PORT        the broker port
-  -i/--client-id ID     the client id
-  -q/--qos 0/1/2        the QoS of the message
-  --no-clean            do not discard any pending message for
-                        the given id
-  -t/--topic TOPIC      the message topic
-  -k/--keepalive SEC    send a ping every SEC seconds
-  -u/--username USER    the username
-  -P/--password PASS    the password
-  -l/--protocol PROTO   the protocol to use, 'mqtt',
-                        'mqtts', 'ws' or 'wss'
-  --key PATH            path to the key file
-  --cert PATH           path to the cert file
-  --ca PATH             path to the ca certificate
-  --insecure            do not verify the server certificate
-  --will-topic TOPIC    the will topic
-  --will-message BODY   the will message
-  --will-qos 0/1/2      the will qos
-  --will-retain         send a will retained message
-  -v/--verbose          print the topic before the message
-  -H/--help             show this

+ 0 - 24
src/utils/mqtt/examples/client/secure-client.js

@@ -1,24 +0,0 @@
-'use strict'
-
-var mqtt = require('../..')
-var path = require('path')
-var fs = require('fs')
-var KEY = fs.readFileSync(path.join(__dirname, '..', '..', 'test', 'helpers', 'tls-key.pem'))
-var CERT = fs.readFileSync(path.join(__dirname, '..', '..', 'test', 'helpers', 'tls-cert.pem'))
-
-var PORT = 8443
-
-var options = {
-  port: PORT,
-  key: KEY,
-  cert: CERT,
-  rejectUnauthorized: false
-}
-
-var client = mqtt.connect(options)
-
-client.subscribe('messages')
-client.publish('messages', 'Current time is: ' + new Date())
-client.on('message', function (topic, message) {
-  console.log(message)
-})

+ 0 - 13
src/utils/mqtt/examples/client/simple-both.js

@@ -1,13 +0,0 @@
-'use strict'
-
-var mqtt = require('../..')
-var client = mqtt.connect()
-
-// or var client = mqtt.connect({ port: 1883, host: '192.168.1.100', keepalive: 10000});
-
-client.subscribe('presence')
-client.publish('presence', 'bin hier')
-client.on('message', function (topic, message) {
-  console.log(message)
-})
-client.end()

+ 0 - 7
src/utils/mqtt/examples/client/simple-publish.js

@@ -1,7 +0,0 @@
-'use strict'
-
-var mqtt = require('../..')
-var client = mqtt.connect()
-
-client.publish('presence', 'hello!')
-client.end()

+ 0 - 9
src/utils/mqtt/examples/client/simple-subscribe.js

@@ -1,9 +0,0 @@
-'use strict'
-
-var mqtt = require('../..')
-var client = mqtt.connect()
-
-client.subscribe('presence')
-client.on('message', function (topic, message) {
-  console.log(message)
-})

+ 0 - 34
src/utils/mqtt/examples/tls client/crt.ca.cg.pem

@@ -1,34 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIF7zCCA9egAwIBAgIJAOeJR1p1PU3qMA0GCSqGSIb3DQEBBQUAMIGNMQswCQYD
-VQQGEwJFUzERMA8GA1UECAwIWmFyYWdvemExETAPBgNVBAcMCFphcmFnb3phMRkw
-FwYDVQQKDBBNUVRUIGZvciBub2RlLmpzMRAwDgYDVQQLDAdNUVRULmpzMQ0wCwYD
-VQQDDARtcXR0MRwwGgYJKoZIhvcNAQkBFg1mYWtlQG1haWwuY29tMB4XDTEzMDgz
-MDEzMDIwNVoXDTIzMDgyODEzMDIwNVowgY0xCzAJBgNVBAYTAkVTMREwDwYDVQQI
-DAhaYXJhZ296YTERMA8GA1UEBwwIWmFyYWdvemExGTAXBgNVBAoMEE1RVFQgZm9y
-IG5vZGUuanMxEDAOBgNVBAsMB01RVFQuanMxDTALBgNVBAMMBG1xdHQxHDAaBgkq
-hkiG9w0BCQEWDWZha2VAbWFpbC5jb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw
-ggIKAoICAQC7Of6OppOE+xwPdPcsT0w3keCa5k4ufZCqUAHex7+mLlrpjfCjQ2z6
-Rm0XBiCu9vy+xvLtbGDh5e/gocjAkkEywjbtrRMiFq5i41BNT3dzEWb9cCXvMWYa
-RxQgIqouJUz5r+TbaP1bm4gAWTHmp09ccoIs9Tykxhyc1nZxXVrEsHF4aBmuw5NJ
-ZwxK1tJTgP4m5H38Ms7ahGpByPsnMg6GBRs/Yen0mGhOsG+MU4TFiQb4bwIxg8Eu
-ntGP1gARvtmyTkkTDhfksRs+muEV17uPtdhGNS/0CGRWaZ2mjEYyD70Ijl2grLd4
-6Vz27uPaqUvbgntPNadKqFN+jEHTtptou3k6V9C8CeLHIq+5N6abfPVHBzaqyNqg
-QelzpSgQQBJ1H0CYREjzAs9uLfeep5ejW99Ik4YwtL6UrTVUyGzGgAl9mevZN5a4
-7mEY7MNUFdwigq0ZpbZmzYiuOURGYnoiy5o64balG5XH6Zh6B1WWhK7CArPVosz8
-eoQacj1WEM5d2Ivg1OLlEdD8FZDABv5CMTmRvnoFQuuIDzWVfrhdcZQ2tQuNLWrz
-YDKheCunPkAIFOlGi70Xv3DVrTCr6kixwL2p9MHTzF4xiWWtiOv41ZXHTMG0t2I3
-YmA45FEO5JawebPgUoGhoc2vgIw5Jo9dcGtwLCqBHSnCojPoTipVhQIDAQABo1Aw
-TjAdBgNVHQ4EFgQU1yVv/ezoDLs+qjbx0O4KiHpC41swHwYDVR0jBBgwFoAU1yVv
-/ezoDLs+qjbx0O4KiHpC41swDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOC
-AgEAScnfOewEk59DgfICJJ2vhcI33wqqn54zhJ1pi8SX3e7PLv26UEUXZaddIqeZ
-JzA/IWF+GCBQFAL7Z+sI4djXx/UpZp5ptCQBFc0tinHk1CGlC0E+LI3JS/cnFf+2
-L8VKZHbSf4ua2f/VMJo7uoyrw/gQHgUToAlYYWpGcIKKm7d0JYQE60wlHk9TXgCc
-s9XAwI+bP9VKNQkZCeooODG/5VcxdJafZSU3rW1WniFcD/R+ZNq7FZYbM+2u2mRt
-Qm7Hh/FjrN4Hnmf3xdNUE0NLHznwk4CD6EeQukN12yP2ccubnG6Z7HFFdV0g9fEP
-AVMsgY/9E9Te/BBoQKjhIg8c274ozIOsCHODx15Mn52848sq0LIQjyeOH4rtuWLL
-1dFE1ysY2gzSMUtrP+on+r6F1GkndFszxfDrBcZMXs85VAy3eKfY/jzUMrdfn0YJ
-36Wz7F40vnOUd2ni24kaOfnRodbu3lOEYD6l5fDGP79kfITyy+dtL6ExTLZQmEn+
-xKsWM9bBkV4STpFiTF61tJwzlcAL1ZDLqDaSwsM8UDZopnDgvklNoJK9XzdLwD1X
-PofOtUe08G4tq5cBDVURLKif+7EfCyAqvUptQ3MJarhoXzhDy9CjtN8TmWexKC1q
-kB5DBML0Y4NnqTEnfYCs/XFPosaS+0GximGySJcg08ay6ZA=
------END CERTIFICATE-----

+ 0 - 48
src/utils/mqtt/examples/tls client/mqttclient.js

@@ -1,48 +0,0 @@
-'use strict'
-
-/** ************************** IMPORTANT NOTE ***********************************
-
-  The certificate used on this example has been generated for a host named stark.
-  So as host we SHOULD use stark if we want the server to be authorized.
-  For testing this we should add on the computer running this example a line on
-  the hosts file:
-  /etc/hosts [UNIX]
-  OR
-  \System32\drivers\etc\hosts [Windows]
-
-  The line to add on the file should be as follows:
-  <the ip address of the server> stark
- *******************************************************************************/
-
-var mqtt = require('mqtt')
-var fs = require('fs')
-var path = require('path')
-var KEY = fs.readFileSync(path.join(__dirname, '/tls-key.pem'))
-var CERT = fs.readFileSync(path.join(__dirname, '/tls-cert.pem'))
-var TRUSTED_CA_LIST = fs.readFileSync(path.join(__dirname, '/crt.ca.cg.pem'))
-
-var PORT = 1883
-var HOST = 'stark'
-
-var options = {
-  port: PORT,
-  host: HOST,
-  key: KEY,
-  cert: CERT,
-  rejectUnauthorized: true,
-  // The CA list will be used to determine if server is authorized
-  ca: TRUSTED_CA_LIST,
-  protocol: 'mqtts'
-}
-
-var client = mqtt.connect(options)
-
-client.subscribe('messages')
-client.publish('messages', 'Current time is: ' + new Date())
-client.on('message', function (topic, message) {
-  console.log(message)
-})
-
-client.on('connect', function () {
-  console.log('Connected')
-})

+ 0 - 13
src/utils/mqtt/examples/tls client/tls-cert.pem

@@ -1,13 +0,0 @@
------BEGIN CERTIFICATE-----
-MIICATCCAWoCCQC2pNY4sfld/jANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB
-VTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0
-cyBQdHkgTHRkMB4XDTEzMDgyNzEyNTU0NVoXDTEzMDkyNjEyNTU0NVowRTELMAkG
-A1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0
-IFdpZGdpdHMgUHR5IEx0ZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAzXGU
-1mZUBqLwoP1fWkiZeypiKgWICUdNm+d2JHXnpQMEVBxSvsaRGOnzWVvgbMVxmD7n
-5/p9qQGTj8FY/+t2NHpbt1I9lGV0+BlZxGJvyvHikEAXPD85EEFhqSbDwgkVuMqa
-w08njqhJJ37fbd2ux6w4woRrDTN4r9CNMhFb9QECAwEAATANBgkqhkiG9w0BAQUF
-AAOBgQBIlZYo1rf8GlISuV1haSBm8U/uiyjIX/pTE5Cs7Kb84SPzKB0tHnGGCa2t
-Lu+TEwetF3NatuI1biqYuevQSfmEM75zsRSwt1P40sJ2y9B1XRTdamHOHCYCJG/b
-rti7WJYjvO8JsCUeB6M+5jFodbmvjsGgAHLLUINXrxOqYe+PWg==
------END CERTIFICATE-----

+ 0 - 15
src/utils/mqtt/examples/tls client/tls-key.pem

@@ -1,15 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIICXQIBAAKBgQDNcZTWZlQGovCg/V9aSJl7KmIqBYgJR02b53YkdeelAwRUHFK+
-xpEY6fNZW+BsxXGYPufn+n2pAZOPwVj/63Y0elu3Uj2UZXT4GVnEYm/K8eKQQBc8
-PzkQQWGpJsPCCRW4yprDTyeOqEknft9t3a7HrDjChGsNM3iv0I0yEVv1AQIDAQAB
-AoGBALv9P+WEE0VTWf7mepdBsXfbi6HKF/Xtkh2kCh5I6WO8Q/y3Qhwh1OnIQg41
-nUHK1iwq+8fxFYVN1PoJQWhEzI6JdBCrn88oADo/aVm1mGN5CWr3pwn92SAVMhbw
-442AWWG81RStrr2uPhLBNE6U/4P835qM8uG4rCP+5Z5SzX7VAkEA+TptuSc0TEkL
-5B/Nml2fYNfbQvRGVzyCbdCXdgkeZt5xuSuwDgC4GvWgjL+SAN1fjTek/Iez5NnL
-xHa5w93j2wJBANMGmRTaTxvpGdkUi/utTPtCp6GXL7hS9v41LClmQTYBOYscPn2b
-Dny2fyZPp29sZ7+AvXHWZxw7QtH+jO2Xz1MCQCI7vlqSYgKgffulyq4LchrxS3LU
-7tyIuTmwTz2tXvmuUFyo/ZPO0XsShi0PG1T3E2roW8c8NJ+Ysv6XeEjJL8UCQG0Z
-/S0tzTa15no4SEM/jwxcosRFoRNgOXimTwW8azybl3+Xg6t27h+GTuikyAEwf9cf
-nVJssfSDowFk5MG1+icCQQCqBOTXEukcJRXZixkpfEuuvS3RNzOYwG4ReKjpvWPy
-EvsfHoCsO1Sz9qz8DXpwl3GEWUGGTfWwBfereX6HLXj+
------END RSA PRIVATE KEY-----

+ 0 - 49
src/utils/mqtt/examples/wss/client.js

@@ -1,49 +0,0 @@
-'use strict'
-
-var mqtt = require('mqtt')
-
-var clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8)
-
-var host = 'wss://localhost:3001/Mosca'
-
-var options = {
-  keepalive: 10,
-  clientId: clientId,
-  protocolId: 'MQTT',
-  protocolVersion: 4,
-  clean: true,
-  reconnectPeriod: 1000,
-  connectTimeout: 30 * 1000,
-  will: {
-    topic: 'WillMsg',
-    payload: 'Connection Closed abnormally..!',
-    qos: 0,
-    retain: false
-  },
-  username: 'demo',
-  password: 'demo',
-  rejectUnauthorized: false
-}
-
-var client = mqtt.connect(host, options)
-
-client.on('error', function (err) {
-  console.log(err)
-  client.end()
-})
-
-client.on('connect', function () {
-  console.log('client connected:' + clientId)
-})
-
-client.subscribe('topic', { qos: 0 })
-
-client.publish('topic', 'wss secure connection demo...!', { qos: 0, retain: false })
-
-client.on('message', function (topic, message, packet) {
-  console.log('Received Message:= ' + message.toString() + '\nOn topic:= ' + topic)
-})
-
-client.on('close', function () {
-  console.log(clientId + ' disconnected')
-})

+ 0 - 58
src/utils/mqtt/examples/wss/client_with_proxy.js

@@ -1,58 +0,0 @@
-'use strict'
-
-var mqtt = require('mqtt')
-var HttpsProxyAgent = require('https-proxy-agent')
-var url = require('url')
-/*
-host: host of the endpoint you want to connect e.g. my.mqqt.host.com
-path: path to you endpoint e.g. '/foo/bar/mqtt'
-*/
-var endpoint = 'wss://<host><path>'
-/* create proxy agent
-proxy: your proxy e.g. proxy.foo.bar.com
-port: http proxy port e.g. 8080
-*/
-var proxy = process.env.http_proxy || 'http://<proxy>:<port>'
-var parsed = url.parse(endpoint)
-var proxyOpts = url.parse(proxy)
-// true for wss
-proxyOpts.secureEndpoint = parsed.protocol ? parsed.protocol === 'wss:' : true
-var agent = new HttpsProxyAgent(proxyOpts)
-var wsOptions = {
-  agent: agent
-  // other wsOptions
-  // foo:'bar'
-}
-var mqttOptions = {
-  keepalive: 60,
-  reschedulePings: true,
-  protocolId: 'MQTT',
-  protocolVersion: 4,
-  reconnectPeriod: 1000,
-  connectTimeout: 30 * 1000,
-  clean: true,
-  clientId: 'testClient',
-  wsOptions: wsOptions
-}
-
-var client = mqtt.connect(parsed, mqttOptions)
-
-client.on('connect', function () {
-  console.log('connected')
-})
-
-client.on('error', function (a) {
-  console.log('error!' + a)
-})
-
-client.on('offline', function (a) {
-  console.log('lost connection!' + a)
-})
-
-client.on('close', function (a) {
-  console.log('connection closed!' + a)
-})
-
-client.on('message', function (topic, message) {
-  console.log(message.toString())
-})

+ 0 - 1129
src/utils/mqtt/lib/client.js

@@ -1,1129 +0,0 @@
-'use strict'
-
-/**
- * Module dependencies
- */
-var events = require('events')
-var Store = require('./store')
-var eos = require('end-of-stream')
-var mqttPacket = require('mqtt-packet')
-var Writable = require('readable-stream').Writable
-var inherits = require('inherits')
-var reInterval = require('reinterval')
-var validations = require('./validations')
-var xtend = require('xtend')
-var setImmediate = global.setImmediate || function (callback) {
-  // works in node v0.8
-  process.nextTick(callback)
-}
-var defaultConnectOptions = {
-  keepalive: 60,
-  reschedulePings: true,
-  protocolId: 'MQTT',
-  protocolVersion: 4,
-  reconnectPeriod: 1000,
-  connectTimeout: 30 * 1000,
-  clean: true,
-  resubscribe: true
-}
-
-function defaultId () {
-  return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
-}
-
-function sendPacket (client, packet, cb) {
-  client.emit('packetsend', packet)
-
-  var result = mqttPacket.writeToStream(packet, client.stream)
-
-  if (!result && cb) {
-    client.stream.once('drain', cb)
-  } else if (cb) {
-    cb()
-  }
-}
-
-function flush (queue) {
-  if (queue) {
-    Object.keys(queue).forEach(function (messageId) {
-      if (typeof queue[messageId] === 'function') {
-        queue[messageId](new Error('Connection closed'))
-        delete queue[messageId]
-      }
-    })
-  }
-}
-
-function storeAndSend (client, packet, cb) {
-  client.outgoingStore.put(packet, function storedPacket (err) {
-    if (err) {
-      return cb && cb(err)
-    }
-    sendPacket(client, packet, cb)
-  })
-}
-
-function nop () {}
-
-/**
- * MqttClient constructor
- *
- * @param {Stream} stream - stream
- * @param {Object} [options] - connection options
- * (see Connection#connect)
- */
-function MqttClient (streamBuilder, options) {
-  var k
-  var that = this
-
-  if (!(this instanceof MqttClient)) {
-    return new MqttClient(streamBuilder, options)
-  }
-
-  this.options = options || {}
-
-  // Defaults
-  for (k in defaultConnectOptions) {
-    if (typeof this.options[k] === 'undefined') {
-      this.options[k] = defaultConnectOptions[k]
-    } else {
-      this.options[k] = options[k]
-    }
-  }
-
-  this.options.clientId = (typeof this.options.clientId === 'string') ? this.options.clientId : defaultId()
-
-  this.streamBuilder = streamBuilder
-
-  // Inflight message storages
-  this.outgoingStore = this.options.outgoingStore || new Store()
-  this.incomingStore = this.options.incomingStore || new Store()
-
-  // Should QoS zero messages be queued when the connection is broken?
-  this.queueQoSZero = this.options.queueQoSZero === undefined ? true : this.options.queueQoSZero
-
-  // map of subscribed topics to support reconnection
-  this._resubscribeTopics = {}
-
-  // map of a subscribe messageId and a topic
-  this.messageIdToTopic = {}
-
-  // Ping timer, setup in _setupPingTimer
-  this.pingTimer = null
-  // Is the client connected?
-  this.connected = false
-  // Are we disconnecting?
-  this.disconnecting = false
-  // Packet queue
-  this.queue = []
-  // connack timer
-  this.connackTimer = null
-  // Reconnect timer
-  this.reconnectTimer = null
-  /**
-   * MessageIDs starting with 1
-   * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
-   */
-  this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
-
-  // Inflight callbacks
-  this.outgoing = {}
-
-  // Mark connected on connect
-  this.on('connect', function () {
-    if (this.disconnected) {
-      return
-    }
-
-    this.connected = true
-    var outStore = this.outgoingStore.createStream()
-
-    this.once('close', remove)
-    outStore.on('end', function () {
-      that.removeListener('close', remove)
-    })
-    outStore.on('error', function (err) {
-      that.removeListener('close', remove)
-      that.emit('error', err)
-    })
-
-    function remove () {
-      outStore.destroy()
-      outStore = null
-    }
-
-    function storeDeliver () {
-      // edge case, we wrapped this twice
-      if (!outStore) {
-        return
-      }
-
-      var packet = outStore.read(1)
-      var cb
-
-      if (!packet) {
-        // read when data is available in the future
-        outStore.once('readable', storeDeliver)
-        return
-      }
-
-      // Avoid unnecessary stream read operations when disconnected
-      if (!that.disconnecting && !that.reconnectTimer) {
-        cb = that.outgoing[packet.messageId]
-        that.outgoing[packet.messageId] = function (err, status) {
-          // Ensure that the original callback passed in to publish gets invoked
-          if (cb) {
-            cb(err, status)
-          }
-
-          storeDeliver()
-        }
-        that._sendPacket(packet)
-      } else if (outStore.destroy) {
-        outStore.destroy()
-      }
-    }
-
-    // start flowing
-    storeDeliver()
-  })
-
-  // Mark disconnected on stream close
-  this.on('close', function () {
-    this.connected = false
-    clearTimeout(this.connackTimer)
-  })
-
-  // Setup ping timer
-  this.on('connect', this._setupPingTimer)
-
-  // Send queued packets
-  this.on('connect', function () {
-    var queue = this.queue
-
-    function deliver () {
-      var entry = queue.shift()
-      var packet = null
-
-      if (!entry) {
-        return
-      }
-
-      packet = entry.packet
-
-      that._sendPacket(
-        packet,
-        function (err) {
-          if (entry.cb) {
-            entry.cb(err)
-          }
-          deliver()
-        }
-      )
-    }
-
-    deliver()
-  })
-
-  var firstConnection = true
-  // resubscribe
-  this.on('connect', function () {
-    if (!firstConnection &&
-        this.options.clean &&
-        Object.keys(this._resubscribeTopics).length > 0) {
-      if (this.options.resubscribe) {
-        this._resubscribeTopics.resubscribe = true
-        this.subscribe(this._resubscribeTopics)
-      } else {
-        this._resubscribeTopics = {}
-      }
-    }
-
-    firstConnection = false
-  })
-
-  // Clear ping timer
-  this.on('close', function () {
-    if (that.pingTimer !== null) {
-      that.pingTimer.clear()
-      that.pingTimer = null
-    }
-  })
-
-  // Setup reconnect timer on disconnect
-  this.on('close', this._setupReconnect)
-
-  events.EventEmitter.call(this)
-
-  this._setupStream()
-}
-inherits(MqttClient, events.EventEmitter)
-
-/**
- * setup the event handlers in the inner stream.
- *
- * @api private
- */
-MqttClient.prototype._setupStream = function () {
-  var connectPacket
-  var that = this
-  var writable = new Writable()
-  var parser = mqttPacket.parser(this.options)
-  var completeParse = null
-  var packets = []
-
-  this._clearReconnect()
-
-  this.stream = this.streamBuilder(this)
-
-  parser.on('packet', function (packet) {
-    packets.push(packet)
-  })
-
-  function nextTickWork () {
-    process.nextTick(work)
-  }
-
-  function work () {
-    var packet = packets.shift()
-    var done = completeParse
-
-    if (packet) {
-      that._handlePacket(packet, nextTickWork)
-    } else {
-      completeParse = null
-      done()
-    }
-  }
-
-  writable._write = function (buf, enc, done) {
-    completeParse = done
-    parser.parse(buf)
-    work()
-  }
-
-  this.stream.pipe(writable)
-
-  // Suppress connection errors
-  this.stream.on('error', nop)
-
-  // Echo stream close
-  eos(this.stream, this.emit.bind(this, 'close'))
-
-  // Send a connect packet
-  connectPacket = Object.create(this.options)
-  connectPacket.cmd = 'connect'
-  // avoid message queue
-  sendPacket(this, connectPacket)
-
-  // Echo connection errors
-  parser.on('error', this.emit.bind(this, 'error'))
-
-  // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
-  this.stream.setMaxListeners(1000)
-
-  clearTimeout(this.connackTimer)
-  this.connackTimer = setTimeout(function () {
-    that._cleanUp(true)
-  }, this.options.connectTimeout)
-}
-
-MqttClient.prototype._handlePacket = function (packet, done) {
-  this.emit('packetreceive', packet)
-
-  switch (packet.cmd) {
-    case 'publish':
-      this._handlePublish(packet, done)
-      break
-    case 'puback':
-    case 'pubrec':
-    case 'pubcomp':
-    case 'suback':
-    case 'unsuback':
-      this._handleAck(packet)
-      done()
-      break
-    case 'pubrel':
-      this._handlePubrel(packet, done)
-      break
-    case 'connack':
-      this._handleConnack(packet)
-      done()
-      break
-    case 'pingresp':
-      this._handlePingresp(packet)
-      done()
-      break
-    default:
-      // do nothing
-      // maybe we should do an error handling
-      // or just log it
-      break
-  }
-}
-
-MqttClient.prototype._checkDisconnecting = function (callback) {
-  if (this.disconnecting) {
-    if (callback) {
-      callback(new Error('client disconnecting'))
-    } else {
-      this.emit('error', new Error('client disconnecting'))
-    }
-  }
-  return this.disconnecting
-}
-
-/**
- * publish - publish <message> to <topic>
- *
- * @param {String} topic - topic to publish to
- * @param {String, Buffer} message - message to publish
- * @param {Object} [opts] - publish options, includes:
- *    {Number} qos - qos level to publish on
- *    {Boolean} retain - whether or not to retain the message
- *    {Boolean} dup - whether or not mark a message as duplicate
- * @param {Function} [callback] - function(err){}
- *    called when publish succeeds or fails
- * @returns {MqttClient} this - for chaining
- * @api public
- *
- * @example client.publish('topic', 'message');
- * @example
- *     client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
- * @example client.publish('topic', 'message', console.log);
- */
-MqttClient.prototype.publish = function (topic, message, opts, callback) {
-  var packet
-
-  // .publish(topic, payload, cb);
-  if (typeof opts === 'function') {
-    callback = opts
-    opts = null
-  }
-
-  // default opts
-  var defaultOpts = {qos: 0, retain: false, dup: false}
-  opts = xtend(defaultOpts, opts)
-
-  if (this._checkDisconnecting(callback)) {
-    return this
-  }
-
-  packet = {
-    cmd: 'publish',
-    topic: topic,
-    payload: message,
-    qos: opts.qos,
-    retain: opts.retain,
-    messageId: this._nextId(),
-    dup: opts.dup
-  }
-
-  switch (opts.qos) {
-    case 1:
-    case 2:
-
-      // Add to callbacks
-      this.outgoing[packet.messageId] = callback || nop
-      this._sendPacket(packet)
-      break
-    default:
-      this._sendPacket(packet, callback)
-      break
-  }
-
-  return this
-}
-
-/**
- * subscribe - subscribe to <topic>
- *
- * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
- * @param {Object} [opts] - optional subscription options, includes:
- *    {Number} qos - subscribe qos level
- * @param {Function} [callback] - function(err, granted){} where:
- *    {Error} err - subscription error (none at the moment!)
- *    {Array} granted - array of {topic: 't', qos: 0}
- * @returns {MqttClient} this - for chaining
- * @api public
- * @example client.subscribe('topic');
- * @example client.subscribe('topic', {qos: 1});
- * @example client.subscribe({'topic': 0, 'topic2': 1}, console.log);
- * @example client.subscribe('topic', console.log);
- */
-MqttClient.prototype.subscribe = function () {
-  var packet
-  var args = Array.prototype.slice.call(arguments)
-  var subs = []
-  var obj = args.shift()
-  var resubscribe = obj.resubscribe
-  var callback = args.pop() || nop
-  var opts = args.pop()
-  var invalidTopic
-  var that = this
-
-  delete obj.resubscribe
-
-  if (typeof obj === 'string') {
-    obj = [obj]
-  }
-
-  if (typeof callback !== 'function') {
-    opts = callback
-    callback = nop
-  }
-
-  invalidTopic = validations.validateTopics(obj)
-  if (invalidTopic !== null) {
-    setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
-    return this
-  }
-
-  if (this._checkDisconnecting(callback)) {
-    return this
-  }
-
-  var defaultOpts = { qos: 0 }
-  opts = xtend(defaultOpts, opts)
-
-  if (Array.isArray(obj)) {
-    obj.forEach(function (topic) {
-      if (that._resubscribeTopics[topic] < opts.qos ||
-          !that._resubscribeTopics.hasOwnProperty(topic) ||
-          resubscribe) {
-        subs.push({
-          topic: topic,
-          qos: opts.qos
-        })
-      }
-    })
-  } else {
-    Object
-      .keys(obj)
-      .forEach(function (k) {
-        if (that._resubscribeTopics[k] < obj[k] ||
-            !that._resubscribeTopics.hasOwnProperty(k) ||
-            resubscribe) {
-          subs.push({
-            topic: k,
-            qos: obj[k]
-          })
-        }
-      })
-  }
-
-  packet = {
-    cmd: 'subscribe',
-    subscriptions: subs,
-    qos: 1,
-    retain: false,
-    dup: false,
-    messageId: this._nextId()
-  }
-
-  if (!subs.length) {
-    callback(null, [])
-    return
-  }
-
-  // subscriptions to resubscribe to in case of disconnect
-  if (this.options.resubscribe) {
-    var topics = []
-    subs.forEach(function (sub) {
-      if (that.options.reconnectPeriod > 0) {
-        that._resubscribeTopics[sub.topic] = sub.qos
-        topics.push(sub.topic)
-      }
-    })
-    that.messageIdToTopic[packet.messageId] = topics
-  }
-
-  this.outgoing[packet.messageId] = function (err, packet) {
-    if (!err) {
-      var granted = packet.granted
-      for (var i = 0; i < granted.length; i += 1) {
-        subs[i].qos = granted[i]
-      }
-    }
-
-    callback(err, subs)
-  }
-
-  this._sendPacket(packet)
-
-  return this
-}
-
-/**
- * unsubscribe - unsubscribe from topic(s)
- *
- * @param {String, Array} topic - topics to unsubscribe from
- * @param {Function} [callback] - callback fired on unsuback
- * @returns {MqttClient} this - for chaining
- * @api public
- * @example client.unsubscribe('topic');
- * @example client.unsubscribe('topic', console.log);
- */
-MqttClient.prototype.unsubscribe = function (topic, callback) {
-  var packet = {
-    cmd: 'unsubscribe',
-    qos: 1,
-    messageId: this._nextId()
-  }
-  var that = this
-
-  callback = callback || nop
-
-  if (this._checkDisconnecting(callback)) {
-    return this
-  }
-
-  if (typeof topic === 'string') {
-    packet.unsubscriptions = [topic]
-  } else if (typeof topic === 'object' && topic.length) {
-    packet.unsubscriptions = topic
-  }
-
-  if (this.options.resubscribe) {
-    packet.unsubscriptions.forEach(function (topic) {
-      delete that._resubscribeTopics[topic]
-    })
-  }
-
-  this.outgoing[packet.messageId] = callback
-
-  this._sendPacket(packet)
-
-  return this
-}
-
-/**
- * end - close connection
- *
- * @returns {MqttClient} this - for chaining
- * @param {Boolean} force - do not wait for all in-flight messages to be acked
- * @param {Function} cb - called when the client has been closed
- *
- * @api public
- */
-MqttClient.prototype.end = function (force, cb) {
-  var that = this
-
-  if (typeof force === 'function') {
-    cb = force
-    force = false
-  }
-
-  function closeStores () {
-    that.disconnected = true
-    that.incomingStore.close(function () {
-      that.outgoingStore.close(function () {
-        if (cb) {
-          cb.apply(null, arguments)
-        }
-        that.emit('end')
-      })
-    })
-    if (that._deferredReconnect) {
-      that._deferredReconnect()
-    }
-  }
-
-  function finish () {
-    // defer closesStores of an I/O cycle,
-    // just to make sure things are
-    // ok for websockets
-    that._cleanUp(force, setImmediate.bind(null, closeStores))
-  }
-
-  if (this.disconnecting) {
-    return this
-  }
-
-  this._clearReconnect()
-
-  this.disconnecting = true
-
-  if (!force && Object.keys(this.outgoing).length > 0) {
-    // wait 10ms, just to be sure we received all of it
-    this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
-  } else {
-    finish()
-  }
-
-  return this
-}
-
-/**
- * removeOutgoingMessage - remove a message in outgoing store
- * the outgoing callback will be called withe Error('Message removed') if the message is removed
- *
- * @param {Number} mid - messageId to remove message
- * @returns {MqttClient} this - for chaining
- * @api public
- *
- * @example client.removeOutgoingMessage(client.getLastMessageId());
- */
-MqttClient.prototype.removeOutgoingMessage = function (mid) {
-  var cb = this.outgoing[mid]
-  delete this.outgoing[mid]
-  this.outgoingStore.del({messageId: mid}, function () {
-    cb(new Error('Message removed'))
-  })
-  return this
-}
-
-/**
- * reconnect - connect again using the same options as connect()
- *
- * @param {Object} [opts] - optional reconnect options, includes:
- *    {Store} incomingStore - a store for the incoming packets
- *    {Store} outgoingStore - a store for the outgoing packets
- *    if opts is not given, current stores are used
- * @returns {MqttClient} this - for chaining
- *
- * @api public
- */
-MqttClient.prototype.reconnect = function (opts) {
-  var that = this
-  var f = function () {
-    if (opts) {
-      that.options.incomingStore = opts.incomingStore
-      that.options.outgoingStore = opts.outgoingStore
-    } else {
-      that.options.incomingStore = null
-      that.options.outgoingStore = null
-    }
-    that.incomingStore = that.options.incomingStore || new Store()
-    that.outgoingStore = that.options.outgoingStore || new Store()
-    that.disconnecting = false
-    that.disconnected = false
-    that._deferredReconnect = null
-    that._reconnect()
-  }
-
-  if (this.disconnecting && !this.disconnected) {
-    this._deferredReconnect = f
-  } else {
-    f()
-  }
-  return this
-}
-
-/**
- * _reconnect - implement reconnection
- * @api privateish
- */
-MqttClient.prototype._reconnect = function () {
-  this.emit('reconnect')
-  this._setupStream()
-}
-
-/**
- * _setupReconnect - setup reconnect timer
- */
-MqttClient.prototype._setupReconnect = function () {
-  var that = this
-
-  if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
-    if (!this.reconnecting) {
-      this.emit('offline')
-      this.reconnecting = true
-    }
-    that.reconnectTimer = setInterval(function () {
-      that._reconnect()
-    }, that.options.reconnectPeriod)
-  }
-}
-
-/**
- * _clearReconnect - clear the reconnect timer
- */
-MqttClient.prototype._clearReconnect = function () {
-  if (this.reconnectTimer) {
-    clearInterval(this.reconnectTimer)
-    this.reconnectTimer = null
-  }
-}
-
-/**
- * _cleanUp - clean up on connection end
- * @api private
- */
-MqttClient.prototype._cleanUp = function (forced, done) {
-  if (done) {
-    this.stream.on('close', done)
-  }
-
-  if (forced) {
-    if ((this.options.reconnectPeriod === 0) && this.options.clean) {
-      flush(this.outgoing)
-    }
-    this.stream.destroy()
-  } else {
-    this._sendPacket(
-      { cmd: 'disconnect' },
-      setImmediate.bind(
-        null,
-        this.stream.end.bind(this.stream)
-      )
-    )
-  }
-
-  if (!this.disconnecting) {
-    this._clearReconnect()
-    this._setupReconnect()
-  }
-
-  if (this.pingTimer !== null) {
-    this.pingTimer.clear()
-    this.pingTimer = null
-  }
-
-  if (done && !this.connected) {
-    this.stream.removeListener('close', done)
-    done()
-  }
-}
-
-/**
- * _sendPacket - send or queue a packet
- * @param {String} type - packet type (see `protocol`)
- * @param {Object} packet - packet options
- * @param {Function} cb - callback when the packet is sent
- * @api private
- */
-MqttClient.prototype._sendPacket = function (packet, cb) {
-  if (!this.connected) {
-    if (((packet.qos || 0) === 0 && this.queueQoSZero) || packet.cmd !== 'publish') {
-      this.queue.push({ packet: packet, cb: cb })
-    } else if (packet.qos > 0) {
-      cb = this.outgoing[packet.messageId]
-      this.outgoingStore.put(packet, function (err) {
-        if (err) {
-          return cb && cb(err)
-        }
-      })
-    } else if (cb) {
-      cb(new Error('No connection to broker'))
-    }
-
-    return
-  }
-
-  // When sending a packet, reschedule the ping timer
-  this._shiftPingInterval()
-
-  switch (packet.cmd) {
-    case 'publish':
-      break
-    case 'pubrel':
-      storeAndSend(this, packet, cb)
-      return
-    default:
-      sendPacket(this, packet, cb)
-      return
-  }
-
-  switch (packet.qos) {
-    case 2:
-    case 1:
-      storeAndSend(this, packet, cb)
-      break
-    /**
-     * no need of case here since it will be caught by default
-     * and jshint comply that before default it must be a break
-     * anyway it will result in -1 evaluation
-     */
-    case 0:
-      /* falls through */
-    default:
-      sendPacket(this, packet, cb)
-      break
-  }
-}
-
-/**
- * _setupPingTimer - setup the ping timer
- *
- * @api private
- */
-MqttClient.prototype._setupPingTimer = function () {
-  var that = this
-
-  if (!this.pingTimer && this.options.keepalive) {
-    this.pingResp = true
-    this.pingTimer = reInterval(function () {
-      that._checkPing()
-    }, this.options.keepalive * 1000)
-  }
-}
-
-/**
- * _shiftPingInterval - reschedule the ping interval
- *
- * @api private
- */
-MqttClient.prototype._shiftPingInterval = function () {
-  if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
-    this.pingTimer.reschedule(this.options.keepalive * 1000)
-  }
-}
-/**
- * _checkPing - check if a pingresp has come back, and ping the server again
- *
- * @api private
- */
-MqttClient.prototype._checkPing = function () {
-  if (this.pingResp) {
-    this.pingResp = false
-    this._sendPacket({ cmd: 'pingreq' })
-  } else {
-    // do a forced cleanup since socket will be in bad shape
-    this._cleanUp(true)
-  }
-}
-
-/**
- * _handlePingresp - handle a pingresp
- *
- * @api private
- */
-MqttClient.prototype._handlePingresp = function () {
-  this.pingResp = true
-}
-
-/**
- * _handleConnack
- *
- * @param {Object} packet
- * @api private
- */
-
-MqttClient.prototype._handleConnack = function (packet) {
-  var rc = packet.returnCode
-  var errors = [
-    '',
-    'Unacceptable protocol version',
-    'Identifier rejected',
-    'Server unavailable',
-    'Bad username or password',
-    'Not authorized'
-  ]
-
-  clearTimeout(this.connackTimer)
-
-  if (rc === 0) {
-    this.reconnecting = false
-    this.emit('connect', packet)
-  } else if (rc > 0) {
-    var err = new Error('Connection refused: ' + errors[rc])
-    err.code = rc
-    this.emit('error', err)
-  }
-}
-
-/**
- * _handlePublish
- *
- * @param {Object} packet
- * @api private
- */
-/*
-those late 2 case should be rewrite to comply with coding style:
-
-case 1:
-case 0:
-  // do not wait sending a puback
-  // no callback passed
-  if (1 === qos) {
-    this._sendPacket({
-      cmd: 'puback',
-      messageId: mid
-    });
-  }
-  // emit the message event for both qos 1 and 0
-  this.emit('message', topic, message, packet);
-  this.handleMessage(packet, done);
-  break;
-default:
-  // do nothing but every switch mus have a default
-  // log or throw an error about unknown qos
-  break;
-
-for now i just suppressed the warnings
-*/
-MqttClient.prototype._handlePublish = function (packet, done) {
-  done = typeof done !== 'undefined' ? done : nop
-  var topic = packet.topic.toString()
-  var message = packet.payload
-  var qos = packet.qos
-  var mid = packet.messageId
-  var that = this
-
-  switch (qos) {
-    case 2:
-      this.incomingStore.put(packet, function (err) {
-        if (err) {
-          return done(err)
-        }
-        that._sendPacket({cmd: 'pubrec', messageId: mid}, done)
-      })
-      break
-    case 1:
-      // emit the message event
-      this.emit('message', topic, message, packet)
-      this.handleMessage(packet, function (err) {
-        if (err) {
-          return done(err)
-        }
-        // send 'puback' if the above 'handleMessage' method executed
-        // successfully.
-        that._sendPacket({cmd: 'puback', messageId: mid}, done)
-      })
-      break
-    case 0:
-      // emit the message event
-      this.emit('message', topic, message, packet)
-      this.handleMessage(packet, done)
-      break
-    default:
-      // do nothing
-      // log or throw an error about unknown qos
-      break
-  }
-}
-
-/**
- * Handle messages with backpressure support, one at a time.
- * Override at will.
- *
- * @param Packet packet the packet
- * @param Function callback call when finished
- * @api public
- */
-MqttClient.prototype.handleMessage = function (packet, callback) {
-  callback()
-}
-
-/**
- * _handleAck
- *
- * @param {Object} packet
- * @api private
- */
-
-MqttClient.prototype._handleAck = function (packet) {
-  /* eslint no-fallthrough: "off" */
-  var mid = packet.messageId
-  var type = packet.cmd
-  var response = null
-  var cb = this.outgoing[mid]
-  var that = this
-
-  if (!cb) {
-    // Server sent an ack in error, ignore it.
-    return
-  }
-
-  // Process
-  switch (type) {
-    case 'pubcomp':
-      // same thing as puback for QoS 2
-    case 'puback':
-      // Callback - we're done
-      delete this.outgoing[mid]
-      this.outgoingStore.del(packet, cb)
-      break
-    case 'pubrec':
-      response = {
-        cmd: 'pubrel',
-        qos: 2,
-        messageId: mid
-      }
-
-      this._sendPacket(response)
-      break
-    case 'suback':
-      delete this.outgoing[mid]
-      if (packet.granted.length === 1 && (packet.granted[0] & 0x80) !== 0) {
-        // suback with Failure status
-        var topics = this.messageIdToTopic[mid]
-        if (topics) {
-          topics.forEach(function (topic) {
-            delete that._resubscribeTopics[topic]
-          })
-        }
-      }
-      cb(null, packet)
-      break
-    case 'unsuback':
-      delete this.outgoing[mid]
-      cb(null)
-      break
-    default:
-      that.emit('error', new Error('unrecognized packet type'))
-  }
-
-  if (this.disconnecting &&
-      Object.keys(this.outgoing).length === 0) {
-    this.emit('outgoingEmpty')
-  }
-}
-
-/**
- * _handlePubrel
- *
- * @param {Object} packet
- * @api private
- */
-MqttClient.prototype._handlePubrel = function (packet, callback) {
-  callback = typeof callback !== 'undefined' ? callback : nop
-  var mid = packet.messageId
-  var that = this
-
-  var comp = {cmd: 'pubcomp', messageId: mid}
-
-  that.incomingStore.get(packet, function (err, pub) {
-    if (!err && pub.cmd !== 'pubrel') {
-      that.emit('message', pub.topic, pub.payload, pub)
-      that.incomingStore.put(packet, function (err) {
-        if (err) {
-          return callback(err)
-        }
-        that.handleMessage(pub, function (err) {
-          if (err) {
-            return callback(err)
-          }
-          that._sendPacket(comp, callback)
-        })
-      })
-    } else {
-      that._sendPacket(comp, callback)
-    }
-  })
-}
-
-/**
- * _nextId
- * @return unsigned int
- */
-MqttClient.prototype._nextId = function () {
-  // id becomes current state of this.nextId and increments afterwards
-  var id = this.nextId++
-  // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
-  if (this.nextId === 65536) {
-    this.nextId = 1
-  }
-  return id
-}
-
-/**
- * getLastMessageId
- * @return unsigned int
- */
-MqttClient.prototype.getLastMessageId = function () {
-  return (this.nextId === 1) ? 65535 : (this.nextId - 1)
-}
-
-module.exports = MqttClient

+ 0 - 149
src/utils/mqtt/lib/connect/index.js

@@ -1,149 +0,0 @@
-'use strict'
-
-var MqttClient = require('../client')
-var Store = require('../store')
-var url = require('url')
-var xtend = require('xtend')
-var protocols = {}
-
-if (process.title !== 'browser') {
-  protocols.mqtt = require('./tcp')
-  protocols.tcp = require('./tcp')
-  protocols.ssl = require('./tls')
-  protocols.tls = require('./tls')
-  protocols.mqtts = require('./tls')
-} else {
-  protocols.wx = require('./wx')
-  protocols.wxs = require('./wx')
-}
-
-protocols.ws = require('./ws')
-protocols.wss = require('./ws')
-
-/**
- * Parse the auth attribute and merge username and password in the options object.
- *
- * @param {Object} [opts] option object
- */
-function parseAuthOptions (opts) {
-  var matches
-  if (opts.auth) {
-    matches = opts.auth.match(/^(.+):(.+)$/)
-    if (matches) {
-      opts.username = matches[1]
-      opts.password = matches[2]
-    } else {
-      opts.username = opts.auth
-    }
-  }
-}
-
-/**
- * connect - connect to an MQTT broker.
- *
- * @param {String} [brokerUrl] - url of the broker, optional
- * @param {Object} opts - see MqttClient#constructor
- */
-function connect (brokerUrl, opts) {
-  if ((typeof brokerUrl === 'object') && !opts) {
-    opts = brokerUrl
-    brokerUrl = null
-  }
-
-  opts = opts || {}
-
-  if (brokerUrl) {
-    var parsed = url.parse(brokerUrl, true)
-    if (parsed.port != null) {
-      parsed.port = Number(parsed.port)
-    }
-
-    opts = xtend(parsed, opts)
-
-    if (opts.protocol === null) {
-      throw new Error('Missing protocol')
-    }
-    opts.protocol = opts.protocol.replace(/:$/, '')
-  }
-
-  // merge in the auth options if supplied
-  parseAuthOptions(opts)
-
-  // support clientId passed in the query string of the url
-  if (opts.query && typeof opts.query.clientId === 'string') {
-    opts.clientId = opts.query.clientId
-  }
-
-  if (opts.cert && opts.key) {
-    if (opts.protocol) {
-      if (['mqtts', 'wss', 'wxs'].indexOf(opts.protocol) === -1) {
-        switch (opts.protocol) {
-          case 'mqtt':
-            opts.protocol = 'mqtts'
-            break
-          case 'ws':
-            opts.protocol = 'wss'
-            break
-          case 'wx':
-            opts.protocol = 'wxs'
-            break
-          default:
-            throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!')
-        }
-      }
-    } else {
-      // don't know what protocol he want to use, mqtts or wss
-      throw new Error('Missing secure protocol key')
-    }
-  }
-
-  if (!protocols[opts.protocol]) {
-    var isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
-    opts.protocol = [
-      'mqtt',
-      'mqtts',
-      'ws',
-      'wss',
-      'wx',
-      'wxs'
-    ].filter(function (key, index) {
-      if (isSecure && index % 2 === 0) {
-        // Skip insecure protocols when requesting a secure one.
-        return false
-      }
-      return (typeof protocols[key] === 'function')
-    })[0]
-  }
-
-  if (opts.clean === false && !opts.clientId) {
-    throw new Error('Missing clientId for unclean clients')
-  }
-
-  if (opts.protocol) {
-    opts.defaultProtocol = opts.protocol
-  }
-
-  function wrapper (client) {
-    if (opts.servers) {
-      if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
-        client._reconnectCount = 0
-      }
-
-      opts.host = opts.servers[client._reconnectCount].host
-      opts.port = opts.servers[client._reconnectCount].port
-      opts.protocol = (!opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol)
-      opts.hostname = opts.host
-
-      client._reconnectCount++
-    }
-
-    return protocols[opts.protocol](client, opts)
-  }
-
-  return new MqttClient(wrapper, opts)
-}
-
-module.exports = connect
-module.exports.connect = connect
-module.exports.MqttClient = MqttClient
-module.exports.Store = Store

+ 0 - 19
src/utils/mqtt/lib/connect/tcp.js

@@ -1,19 +0,0 @@
-'use strict'
-var net = require('net')
-
-/*
-  variables port and host can be removed since
-  you have all required information in opts object
-*/
-function buildBuilder (client, opts) {
-  var port, host
-  opts.port = opts.port || 1883
-  opts.hostname = opts.hostname || opts.host || 'localhost'
-
-  port = opts.port
-  host = opts.hostname
-
-  return net.createConnection(port, host)
-}
-
-module.exports = buildBuilder

+ 0 - 41
src/utils/mqtt/lib/connect/tls.js

@@ -1,41 +0,0 @@
-'use strict'
-var tls = require('tls')
-
-function buildBuilder (mqttClient, opts) {
-  var connection
-  opts.port = opts.port || 8883
-  opts.host = opts.hostname || opts.host || 'localhost'
-
-  opts.rejectUnauthorized = opts.rejectUnauthorized !== false
-
-  delete opts.path
-
-  connection = tls.connect(opts)
-  /* eslint no-use-before-define: [2, "nofunc"] */
-  connection.on('secureConnect', function () {
-    if (opts.rejectUnauthorized && !connection.authorized) {
-      connection.emit('error', new Error('TLS not authorized'))
-    } else {
-      connection.removeListener('error', handleTLSerrors)
-    }
-  })
-
-  function handleTLSerrors (err) {
-    // How can I get verify this error is a tls error?
-    if (opts.rejectUnauthorized) {
-      mqttClient.emit('error', err)
-    }
-
-    // close this connection to match the behaviour of net
-    // otherwise all we get is an error from the connection
-    // and close event doesn't fire. This is a work around
-    // to enable the reconnect code to work the same as with
-    // net.createConnection
-    connection.end()
-  }
-
-  connection.on('error', handleTLSerrors)
-  return connection
-}
-
-module.exports = buildBuilder

+ 0 - 92
src/utils/mqtt/lib/connect/ws.js

@@ -1,92 +0,0 @@
-'use strict'
-
-var websocket = require('websocket-stream')
-var urlModule = require('url')
-var WSS_OPTIONS = [
-  'rejectUnauthorized',
-  'ca',
-  'cert',
-  'key',
-  'pfx',
-  'passphrase'
-]
-var IS_BROWSER = process.title === 'browser'
-
-function buildUrl (opts, client) {
-  var url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
-  if (typeof (opts.transformWsUrl) === 'function') {
-    url = opts.transformWsUrl(url, opts, client)
-  }
-  return url
-}
-
-function setDefaultOpts (opts) {
-  if (!opts.hostname) {
-    opts.hostname = 'localhost'
-  }
-  if (!opts.port) {
-    if (opts.protocol === 'wss') {
-      opts.port = 443
-    } else {
-      opts.port = 80
-    }
-  }
-  if (!opts.path) {
-    opts.path = '/'
-  }
-
-  if (!opts.wsOptions) {
-    opts.wsOptions = {}
-  }
-  if (!IS_BROWSER && opts.protocol === 'wss') {
-    // Add cert/key/ca etc options
-    WSS_OPTIONS.forEach(function (prop) {
-      if (opts.hasOwnProperty(prop) && !opts.wsOptions.hasOwnProperty(prop)) {
-        opts.wsOptions[prop] = opts[prop]
-      }
-    })
-  }
-}
-
-function createWebSocket (client, opts) {
-  var websocketSubProtocol =
-    (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
-      ? 'mqttv3.1'
-      : 'mqtt'
-
-  setDefaultOpts(opts)
-  var url = buildUrl(opts, client)
-  return websocket(url, [websocketSubProtocol], opts.wsOptions)
-}
-
-function buildBuilder (client, opts) {
-  return createWebSocket(client, opts)
-}
-
-function buildBuilderBrowser (client, opts) {
-  if (!opts.hostname) {
-    opts.hostname = opts.host
-  }
-
-  if (!opts.hostname) {
-    // Throwing an error in a Web Worker if no `hostname` is given, because we
-    // can not determine the `hostname` automatically.  If connecting to
-    // localhost, please supply the `hostname` as an argument.
-    if (typeof (document) === 'undefined') {
-      throw new Error('Could not determine host. Specify host manually.')
-    }
-    var parsed = urlModule.parse(document.URL)
-    opts.hostname = parsed.hostname
-
-    if (!opts.port) {
-      opts.port = parsed.port
-    }
-  }
-  return createWebSocket(client, opts)
-}
-
-if (IS_BROWSER) {
-  module.exports = buildBuilderBrowser
-} else {
-  module.exports = buildBuilder
-}

+ 0 - 110
src/utils/mqtt/lib/connect/wx.js

@@ -1,110 +0,0 @@
-'use strict'
-
-/* global wx */
-var socketOpen = false
-var socketMsgQueue = []
-
-function sendSocketMessage (msg) {
-  if (socketOpen) {
-    wx.sendSocketMessage({
-      data: msg.buffer || msg
-    })
-  } else {
-    socketMsgQueue.push(msg)
-  }
-}
-
-function WebSocket (url, protocols) {
-  var ws = {
-    OPEN: 1,
-    CLOSING: 2,
-    CLOSED: 3,
-    readyState: socketOpen ? 1 : 0,
-    send: sendSocketMessage,
-    close: wx.closeSocket,
-    onopen: null,
-    onmessage: null,
-    onclose: null,
-    onerror: null
-  }
-
-  wx.connectSocket({
-    url: url,
-    protocols: protocols
-  })
-  wx.onSocketOpen(function (res) {
-    ws.readyState = ws.OPEN
-    socketOpen = true
-    for (var i = 0; i < socketMsgQueue.length; i++) {
-      sendSocketMessage(socketMsgQueue[i])
-    }
-    socketMsgQueue = []
-
-    ws.onopen && ws.onopen.apply(ws, arguments)
-  })
-  wx.onSocketMessage(function (res) {
-    ws.onmessage && ws.onmessage.apply(ws, arguments)
-  })
-  wx.onSocketClose(function () {
-    ws.onclose && ws.onclose.apply(ws, arguments)
-    ws.readyState = ws.CLOSED
-    socketOpen = false
-  })
-  wx.onSocketError(function () {
-    ws.onerror && ws.onerror.apply(ws, arguments)
-    ws.readyState = ws.CLOSED
-    socketOpen = false
-  })
-
-  return ws
-}
-
-var websocket = require('websocket-stream')
-
-function buildUrl (opts, client) {
-  var protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
-  var url = protocol + '://' + opts.hostname + opts.path
-  if (opts.port && opts.port !== 80 && opts.port !== 443) {
-    url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
-  }
-  if (typeof (opts.transformWsUrl) === 'function') {
-    url = opts.transformWsUrl(url, opts, client)
-  }
-  return url
-}
-
-function setDefaultOpts (opts) {
-  if (!opts.hostname) {
-    opts.hostname = 'localhost'
-  }
-  if (!opts.path) {
-    opts.path = '/'
-  }
-
-  if (!opts.wsOptions) {
-    opts.wsOptions = {}
-  }
-}
-
-function createWebSocket (client, opts) {
-  var websocketSubProtocol =
-    (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
-      ? 'mqttv3.1'
-      : 'mqtt'
-
-  setDefaultOpts(opts)
-  var url = buildUrl(opts, client)
-  return websocket(WebSocket(url, [websocketSubProtocol]))
-}
-
-function buildBuilder (client, opts) {
-  opts.hostname = opts.hostname || opts.host
-
-  if (!opts.hostname) {
-    throw new Error('Could not determine host. Specify host manually.')
-  }
-
-  return createWebSocket(client, opts)
-}
-
-module.exports = buildBuilder

+ 0 - 140
src/utils/mqtt/lib/store.js

@@ -1,140 +0,0 @@
-'use strict'
-
-/**
- * Module dependencies
- */
-var xtend = require('xtend')
-
-var Readable = require('readable-stream').Readable
-var streamsOpts = { objectMode: true }
-var defaultStoreOptions = {
-  clean: true
-}
-
-/**
- * es6-map can preserve insertion order even if ES version is older.
- *
- * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Description
- * It should be noted that a Map which is a map of an object, especially
- * a dictionary of dictionaries, will only map to the object's insertion
- * order. In ES2015 this is ordered for objects but for older versions of
- * ES, this may be random and not ordered.
- *
- */
-var Map = require('es6-map')
-
-/**
- * In-memory implementation of the message store
- * This can actually be saved into files.
- *
- * @param {Object} [options] - store options
- */
-function Store (options) {
-  if (!(this instanceof Store)) {
-    return new Store(options)
-  }
-
-  this.options = options || {}
-
-  // Defaults
-  this.options = xtend(defaultStoreOptions, options)
-
-  this._inflights = new Map()
-}
-
-/**
- * Adds a packet to the store, a packet is
- * anything that has a messageId property.
- *
- */
-Store.prototype.put = function (packet, cb) {
-  this._inflights.set(packet.messageId, packet)
-
-  if (cb) {
-    cb()
-  }
-
-  return this
-}
-
-/**
- * Creates a stream with all the packets in the store
- *
- */
-Store.prototype.createStream = function () {
-  var stream = new Readable(streamsOpts)
-  var destroyed = false
-  var values = []
-  var i = 0
-
-  this._inflights.forEach(function (value, key) {
-    values.push(value)
-  })
-
-  stream._read = function () {
-    if (!destroyed && i < values.length) {
-      this.push(values[i++])
-    } else {
-      this.push(null)
-    }
-  }
-
-  stream.destroy = function () {
-    if (destroyed) {
-      return
-    }
-
-    var self = this
-
-    destroyed = true
-
-    process.nextTick(function () {
-      self.emit('close')
-    })
-  }
-
-  return stream
-}
-
-/**
- * deletes a packet from the store.
- */
-Store.prototype.del = function (packet, cb) {
-  packet = this._inflights.get(packet.messageId)
-  if (packet) {
-    this._inflights.delete(packet.messageId)
-    cb(null, packet)
-  } else if (cb) {
-    cb(new Error('missing packet'))
-  }
-
-  return this
-}
-
-/**
- * get a packet from the store.
- */
-Store.prototype.get = function (packet, cb) {
-  packet = this._inflights.get(packet.messageId)
-  if (packet) {
-    cb(null, packet)
-  } else if (cb) {
-    cb(new Error('missing packet'))
-  }
-
-  return this
-}
-
-/**
- * Close the store
- */
-Store.prototype.close = function (cb) {
-  if (this.options.clean) {
-    this._inflights = null
-  }
-  if (cb) {
-    cb()
-  }
-}
-
-module.exports = Store

+ 0 - 52
src/utils/mqtt/lib/validations.js

@@ -1,52 +0,0 @@
-'use strict'
-
-/**
- * Validate a topic to see if it's valid or not.
- * A topic is valid if it follow below rules:
- * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
- * - Rule #2: Part `#` must be located at the end of the mailbox
- *
- * @param {String} topic - A topic
- * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
- */
-function validateTopic (topic) {
-  var parts = topic.split('/')
-
-  for (var i = 0; i < parts.length; i++) {
-    if (parts[i] === '+') {
-      continue
-    }
-
-    if (parts[i] === '#') {
-      // for Rule #2
-      return i === parts.length - 1
-    }
-
-    if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
-      return false
-    }
-  }
-
-  return true
-}
-
-/**
- * Validate an array of topics to see if any of them is valid or not
-  * @param {Array} topics - Array of topics
- * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
- */
-function validateTopics (topics) {
-  if (topics.length === 0) {
-    return 'empty_topic_list'
-  }
-  for (var i = 0; i < topics.length; i++) {
-    if (!validateTopic(topics[i])) {
-      return topics[i]
-    }
-  }
-  return null
-}
-
-module.exports = {
-  validateTopics: validateTopics
-}

+ 0 - 41
src/utils/mqtt/mqtt.js

@@ -1,41 +0,0 @@
-#!/usr/bin/env node
-'use strict'
-
-/*
- * Copyright (c) 2015-2015 MQTT.js contributors.
- * Copyright (c) 2011-2014 Adam Rudd.
- *
- * See LICENSE for more information
- */
-
-var MqttClient = require('./lib/client')
-var connect = require('./lib/connect')
-var Store = require('./lib/store')
-
-module.exports.connect = connect
-
-// Expose MqttClient
-module.exports.MqttClient = MqttClient
-module.exports.Client = MqttClient
-module.exports.Store = Store
-
-function cli() {
-  var commist = require('commist')()
-  var helpMe = require('help-me')()
-
-  commist.register('publish', require('./bin/pub'))
-  commist.register('subscribe', require('./bin/sub'))
-  commist.register('version', function () {
-    console.log('MQTT.js version:', require('./package.json').version)
-  })
-  commist.register('help', helpMe.toStdout)
-
-  if (commist.parse(process.argv.slice(2)) !== null) {
-    console.log('No such command:', process.argv[2], '\n')
-    helpMe.toStdout()
-  }
-}
-
-if (require.main === module) {
-  cli()
-}

+ 0 - 107
src/utils/mqtt/package.json

@@ -1,107 +0,0 @@
-{
-  "name": "mqtt",
-  "description": "A library for the MQTT protocol",
-  "version": "2.18.9",
-  "contributors": [
-    "Adam Rudd <adamvrr@gmail.com>",
-    "Matteo Collina <matteo.collina@gmail.com> (https://github.com/mcollina)"
-  ],
-  "keywords": [
-    "mqtt",
-    "publish/subscribe",
-    "publish",
-    "subscribe"
-  ],
-  "license": "MIT",
-  "repository": {
-    "type": "git",
-    "url": "git://github.com/mqttjs/MQTT.js.git"
-  },
-  "main": "mqtt.js",
-  "types": "types/index.d.ts",
-  "scripts": {
-    "test": "node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly --",
-    "pretest": "standard | snazzy",
-    "tslint": "if [[ \"`node -v`\" != \"v4.3.2\" ]]; then tslint types/**/*.d.ts; fi",
-    "typescript-compile-test": "tsc -p test/typescript/tsconfig.json",
-    "typescript-compile-execute": "node test/typescript/*.js",
-    "typescript-test": "npm run typescript-compile-test && npm run typescript-compile-execute",
-    "prepare": "npm run browser-build",
-    "browser-build": "rimraf dist/ && mkdirp dist/ && browserify mqtt.js -s mqtt > dist/mqtt.js && uglifyjs < dist/mqtt.js > dist/mqtt.min.js",
-    "browser-test": "zuul --server test/browser/server.js --local --open test/browser/test.js",
-    "weapp-test": "zuul --server test/browser/server.js --local --open test/browser/wx.js",
-    "sauce-test": "zuul --server test/browser/server.js --tunnel ngrok -- test/browser/test.js",
-    "ci": "npm run tslint && npm run typescript-test && npm run test && codecov"
-  },
-  "bin": {
-    "mqtt_pub": "./bin/pub.js",
-    "mqtt_sub": "./bin/sub.js",
-    "mqtt": "./mqtt.js"
-  },
-  "files": [
-    "dist/",
-    "CONTRIBUTING.md",
-    "doc",
-    "lib",
-    "bin",
-    "examples",
-    "test",
-    "types",
-    "mqtt.js"
-  ],
-  "engines": {
-    "node": ">=4.0.0"
-  },
-  "browser": {
-    "./mqtt.js": "./lib/connect/index.js",
-    "fs": false,
-    "tls": false,
-    "net": false
-  },
-  "dependencies": {
-    "commist": "^1.0.0",
-    "concat-stream": "^1.6.2",
-    "end-of-stream": "^1.4.1",
-    "es6-map": "^0.1.5",
-    "help-me": "^1.0.1",
-    "inherits": "^2.0.3",
-    "minimist": "^1.2.0",
-    "mqtt-packet": "^5.6.0",
-    "pump": "^3.0.0",
-    "readable-stream": "^2.3.6",
-    "reinterval": "^1.1.0",
-    "split2": "^2.1.1",
-    "websocket-stream": "~5.2.0",
-    "xtend": "^4.0.1"
-  },
-  "devDependencies": {
-    "@types/node": "^8.10.21",
-    "browserify": "^16.2.2",
-    "codecov": "^3.0.4",
-    "global": "^4.3.2",
-    "istanbul": "^0.4.5",
-    "mkdirp": "^0.5.1",
-    "mocha": "^4.1.0",
-    "mqtt-connection": "^3.0.0",
-    "pre-commit": "^1.2.2",
-    "rimraf": "^2.6.2",
-    "safe-buffer": "^5.1.2",
-    "should": "^13.2.1",
-    "sinon": "~1.17.7",
-    "snazzy": "^7.1.1",
-    "standard": "^11.0.1",
-    "through2": "^2.0.3",
-    "tslint": "^5.11.0",
-    "tslint-config-standard": "^7.1.0",
-    "typescript": "^2.9.2",
-    "uglify-js": "^3.4.5",
-    "ws": "^3.3.3",
-    "zuul": "^3.12.0",
-    "zuul-ngrok": "^4.0.0"
-  },
-  "standard": {
-    "env": [
-      "mocha"
-    ]
-  }
-}

+ 0 - 2667
src/utils/mqtt/test/abstract_client.js

@@ -1,2667 +0,0 @@
-'use strict'
-
-/**
- * Testing dependencies
- */
-var should = require('should')
-var sinon = require('sinon')
-var mqtt = require('../')
-var xtend = require('xtend')
-var Server = require('./server')
-var Store = require('./../lib/store')
-var port = 9876
-
-module.exports = function (server, config) {
-  function connect (opts) {
-    opts = xtend(config, opts)
-    return mqtt.connect(opts)
-  }
-
-  describe('closing', function () {
-    it('should emit close if stream closes', function (done) {
-      var client = connect()
-
-      client.once('connect', function () {
-        client.stream.end()
-      })
-      client.once('close', function () {
-        client.end()
-        done()
-      })
-    })
-
-    it('should mark the client as disconnected', function (done) {
-      var client = connect()
-
-      client.once('close', function () {
-        client.end()
-        if (!client.connected) {
-          done()
-        } else {
-          done(new Error('Not marked as disconnected'))
-        }
-      })
-      client.once('connect', function () {
-        client.stream.end()
-      })
-    })
-
-    it('should stop ping timer if stream closes', function (done) {
-      var client = connect()
-
-      client.once('close', function () {
-        should.not.exist(client.pingTimer)
-        client.end()
-        done()
-      })
-
-      client.once('connect', function () {
-        should.exist(client.pingTimer)
-        client.stream.end()
-      })
-    })
-
-    it('should emit close after end called', function (done) {
-      var client = connect()
-
-      client.once('close', function () {
-        done()
-      })
-
-      client.once('connect', function () {
-        client.end()
-      })
-    })
-
-    it('should emit end after end called and client must be disconnected', function (done) {
-      var client = connect()
-
-      client.once('end', function () {
-        if (client.disconnected) {
-          return done()
-        }
-        done(new Error('client must be disconnected'))
-      })
-
-      client.once('connect', function () {
-        client.end()
-      })
-    })
-
-    it('should pass store close error to end callback but not to end listeners', function (done) {
-      var store = new Store()
-      var client = connect({outgoingStore: store})
-
-      store.close = function (cb) {
-        cb(new Error('test'))
-      }
-      client.once('end', function () {
-        if (arguments.length === 0) {
-          return done()
-        }
-        throw new Error('no argument shoould be passed to event')
-      })
-
-      client.once('connect', function () {
-        client.end(function (test) {
-          if (test && test.message === 'test') {
-            return
-          }
-          throw new Error('bad argument passed to callback')
-        })
-      })
-    })
-
-    it('should return `this` if end called twice', function (done) {
-      var client = connect()
-
-      client.once('connect', function () {
-        client.end()
-        var value = client.end()
-        if (value === client) {
-          done()
-        } else {
-          done(new Error('Not returning client.'))
-        }
-      })
-    })
-
-    it('should emit end only on first client end', function (done) {
-      var client = connect()
-
-      client.once('end', function () {
-        var timeout = setTimeout(done.bind(null), 200)
-        client.once('end', function () {
-          clearTimeout(timeout)
-          done(new Error('end was emitted twice'))
-        })
-        client.end()
-      })
-
-      client.once('connect', client.end.bind(client))
-    })
-
-    it('should stop ping timer after end called', function (done) {
-      var client = connect()
-
-      client.once('connect', function () {
-        should.exist(client.pingTimer)
-        client.end()
-        should.not.exist(client.pingTimer)
-        done()
-      })
-    })
-
-    it('should be able to end even on a failed connection', function (done) {
-      var client = connect({host: 'this_hostname_should_not_exist'})
-
-      var timeout = setTimeout(function () {
-        done(new Error('Failed to end a disconnected client'))
-      }, 500)
-
-      setTimeout(function () {
-        client.end(function () {
-          clearTimeout(timeout)
-          done()
-        })
-      }, 200)
-    })
-
-    it('should emit end even on a failed connection', function (done) {
-      var client = connect({host: 'this_hostname_should_not_exist'})
-
-      var timeout = setTimeout(function () {
-        done(new Error('Disconnected client has failed to emit end'))
-      }, 500)
-
-      client.once('end', function () {
-        clearTimeout(timeout)
-        done()
-      })
-
-      setTimeout(client.end.bind(client), 200)
-    })
-
-    it('should emit end only once for a reconnecting client', function (done) {
-      var client = connect({host: 'this_hostname_should_not_exist', connectTimeout: 10, reconnectPeriod: 10})
-
-      client.once('end', function () {
-        var timeout = setTimeout(done.bind(null))
-        client.once('end', function () {
-          clearTimeout(timeout)
-          done(new Error('end emitted twice'))
-        })
-      })
-
-      setTimeout(client.end.bind(client), 300)
-    })
-  })
-
-  describe('connecting', function () {
-    it('should connect to the broker', function (done) {
-      var client = connect()
-      client.on('error', done)
-
-      server.once('client', function () {
-        client.end()
-        done()
-      })
-    })
-
-    it('should send a default client id', function (done) {
-      var client = connect()
-      client.on('error', done)
-
-      server.once('client', function (serverClient) {
-        serverClient.once('connect', function (packet) {
-          packet.clientId.should.match(/mqttjs.*/)
-          serverClient.disconnect()
-          done()
-        })
-      })
-    })
-
-    it('should send be clean by default', function (done) {
-      var client = connect()
-      client.on('error', done)
-
-      server.once('client', function (serverClient) {
-        serverClient.once('connect', function (packet) {
-          packet.clean.should.be.true()
-          serverClient.disconnect()
-          done()
-        })
-      })
-    })
-
-    it('should connect with the given client id', function (done) {
-      var client = connect({clientId: 'testclient'})
-      client.on('error', function (err) {
-        throw err
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('connect', function (packet) {
-          packet.clientId.should.match(/testclient/)
-          serverClient.disconnect()
-          done()
-        })
-      })
-    })
-
-    it('should connect with the client id and unclean state', function (done) {
-      var client = connect({clientId: 'testclient', clean: false})
-      client.on('error', function (err) {
-        throw err
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('connect', function (packet) {
-          packet.clientId.should.match(/testclient/)
-          packet.clean.should.be.false()
-          serverClient.disconnect()
-          done()
-        })
-      })
-    })
-
-    it('should require a clientId with clean=false', function (done) {
-      try {
-        var client = connect({ clean: false })
-        client.on('error', function (err) {
-          done(err)
-          // done(new Error('should have thrown'));
-        })
-      } catch (err) {
-        done()
-      }
-    })
-
-    it('should default to localhost', function (done) {
-      var client = connect({clientId: 'testclient'})
-      client.on('error', function (err) {
-        throw err
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('connect', function (packet) {
-          packet.clientId.should.match(/testclient/)
-          serverClient.disconnect()
-          done()
-        })
-      })
-    })
-
-    it('should emit connect', function (done) {
-      var client = connect()
-      client.once('connect', function () {
-        client.end()
-        done()
-      })
-      client.once('error', done)
-    })
-
-    it('should provide connack packet with connect event', function (done) {
-      server.once('client', function (serverClient) {
-        serverClient.connack({returnCode: 0, sessionPresent: true})
-
-        server.once('client', function (serverClient) {
-          serverClient.connack({returnCode: 0, sessionPresent: false})
-        })
-      })
-
-      var client = connect()
-      client.once('connect', function (packet) {
-        should(packet.sessionPresent).be.equal(true)
-        client.once('connect', function (packet) {
-          should(packet.sessionPresent).be.equal(false)
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should mark the client as connected', function (done) {
-      var client = connect()
-      client.once('connect', function () {
-        client.end()
-        if (client.connected) {
-          done()
-        } else {
-          done(new Error('Not marked as connected'))
-        }
-      })
-    })
-
-    it('should emit error', function (done) {
-      var client = connect({clientId: 'invalid'})
-      client.once('connect', function () {
-        done(new Error('Should not emit connect'))
-      })
-      client.once('error', function (error) {
-        should(error.code).be.equal(2) // code for clientID identifer rejected
-        client.end()
-        done()
-      })
-    })
-
-    it('should have different client ids', function (done) {
-      var client1 = connect()
-      var client2 = connect()
-
-      client1.options.clientId.should.not.equal(client2.options.clientId)
-      client1.end(true)
-      client2.end(true)
-      setImmediate(done)
-    })
-  })
-
-  describe('handling offline states', function () {
-    it('should emit offline events once when the client transitions from connected states to disconnected ones', function (done) {
-      var client = connect({reconnectPeriod: 20})
-
-      client.on('connect', function () {
-        this.stream.end()
-      })
-
-      client.on('offline', function () {
-        client.end(true, done)
-      })
-    })
-
-    it('should emit offline events once when the client (at first) can NOT connect to servers', function (done) {
-      // fake a port
-      var client = connect({ reconnectPeriod: 20, port: 4557 })
-
-      client.on('offline', function () {
-        client.end(true, done)
-      })
-    })
-  })
-
-  describe('topic validations when subscribing', function () {
-    it('should be ok for well-formated topics', function (done) {
-      var client = connect()
-      client.subscribe(
-        [
-          '+', '+/event', 'event/+', '#', 'event/#', 'system/event/+',
-          'system/+/event', 'system/registry/event/#', 'system/+/event/#',
-          'system/registry/event/new_device', 'system/+/+/new_device'
-        ],
-        function (err) {
-          client.end(function () {
-            if (err) {
-              return done(new Error(err))
-            }
-            done()
-          })
-        }
-      )
-    })
-
-    it('should return an error (via callbacks) for topic #/event', function (done) {
-      var client = connect()
-      client.subscribe(['#/event', 'event#', 'event+'], function (err) {
-        client.end(false, function () {
-          if (err) {
-            return done()
-          }
-          done(new Error('Validations do NOT work'))
-        })
-      })
-    })
-
-    it('should return an empty array for duplicate subs', function (done) {
-      var client = connect()
-      client.subscribe('event', function (err, granted1) {
-        if (err) {
-          return done(err)
-        }
-        client.subscribe('event', function (err, granted2) {
-          if (err) {
-            return done(err)
-          }
-          granted2.should.Array()
-          granted2.should.be.empty()
-          done()
-        })
-      })
-    })
-
-    it('should return an error (via callbacks) for topic #/event', function (done) {
-      var client = connect()
-      client.subscribe('#/event', function (err) {
-        client.end(function () {
-          if (err) {
-            return done()
-          }
-          done(new Error('Validations do NOT work'))
-        })
-      })
-    })
-
-    it('should return an error (via callbacks) for topic event#', function (done) {
-      var client = connect()
-      client.subscribe('event#', function (err) {
-        client.end(function () {
-          if (err) {
-            return done()
-          }
-          done(new Error('Validations do NOT work'))
-        })
-      })
-    })
-
-    it('should return an error (via callbacks) for topic system/#/event', function (done) {
-      var client = connect()
-      client.subscribe('system/#/event', function (err) {
-        client.end(function () {
-          if (err) {
-            return done()
-          }
-          done(new Error('Validations do NOT work'))
-        })
-      })
-    })
-
-    it('should return an error (via callbacks) for empty topic list', function (done) {
-      var client = connect()
-      client.subscribe([], function (err) {
-        client.end()
-        if (err) {
-          return done()
-        }
-        done(new Error('Validations do NOT work'))
-      })
-    })
-
-    it('should return an error (via callbacks) for topic system/+/#/event', function (done) {
-      var client = connect()
-      client.subscribe('system/+/#/event', function (err) {
-        client.end(true, function () {
-          if (err) {
-            return done()
-          }
-          done(new Error('Validations do NOT work'))
-        })
-      })
-    })
-  })
-
-  describe('offline messages', function () {
-    it('should queue message until connected', function (done) {
-      var client = connect()
-
-      client.publish('test', 'test')
-      client.subscribe('test')
-      client.unsubscribe('test')
-      client.queue.length.should.equal(3)
-
-      client.once('connect', function () {
-        client.queue.length.should.equal(0)
-        setTimeout(function () {
-          client.end(true, done)
-        }, 10)
-      })
-    })
-
-    it('should not queue qos 0 messages if queueQoSZero is false', function (done) {
-      var client = connect({queueQoSZero: false})
-
-      client.publish('test', 'test', {qos: 0})
-      client.queue.length.should.equal(0)
-      client.on('connect', function () {
-        setTimeout(function () {
-          client.end(true, done)
-        }, 10)
-      })
-    })
-
-    it('should queue qos != 0 messages', function (done) {
-      var client = connect({queueQoSZero: false})
-
-      client.publish('test', 'test', {qos: 1})
-      client.publish('test', 'test', {qos: 2})
-      client.subscribe('test')
-      client.unsubscribe('test')
-      client.queue.length.should.equal(2)
-      client.on('connect', function () {
-        setTimeout(function () {
-          client.end(true, done)
-        }, 10)
-      })
-    })
-
-    it('should call cb if an outgoing QoS 0 message is not sent', function (done) {
-      var client = connect({queueQoSZero: false})
-      var called = false
-
-      client.publish('test', 'test', {qos: 0}, function () {
-        called = true
-      })
-
-      client.on('connect', function () {
-        called.should.equal(true)
-        setTimeout(function () {
-          client.end(true, done)
-        }, 10)
-      })
-    })
-
-    it('should delay ending up until all inflight messages are delivered', function (done) {
-      var client = connect()
-      var subscribeCalled = false
-
-      client.on('connect', function () {
-        client.subscribe('test', function () {
-          subscribeCalled = true
-        })
-        client.publish('test', 'test', function () {
-          client.end(false, function () {
-            subscribeCalled.should.be.equal(true)
-            done()
-          })
-        })
-      })
-    })
-
-    it('wait QoS 1 publish messages', function (done) {
-      var client = connect()
-      var messageReceived = false
-
-      client.on('connect', function () {
-        client.subscribe('test')
-        client.publish('test', 'test', { qos: 1 }, function () {
-          client.end(false, function () {
-            messageReceived.should.equal(true)
-            done()
-          })
-        })
-        client.on('message', function () {
-          messageReceived = true
-        })
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.on('subscribe', function () {
-          serverClient.on('publish', function (packet) {
-            serverClient.publish(packet)
-          })
-        })
-      })
-    })
-
-    it('does not wait acks when force-closing', function (done) {
-      // non-running broker
-      var client = connect('mqtt://localhost:8993')
-      client.publish('test', 'test', { qos: 1 })
-      client.end(true, done)
-    })
-
-    it('should call cb if store.put fails', function (done) {
-      const store = new Store()
-      store.put = function (packet, cb) {
-        process.nextTick(cb, new Error('oops there is an error'))
-      }
-      var client = connect({ incomingStore: store, outgoingStore: store })
-      client.publish('test', 'test', { qos: 2 }, function (err) {
-        if (err) {
-          client.end(true, done)
-        }
-      })
-    })
-  })
-
-  describe('publishing', function () {
-    it('should publish a message (offline)', function (done) {
-      var client = connect()
-      var payload = 'test'
-      var topic = 'test'
-
-      client.publish(topic, payload)
-
-      server.on('client', onClient)
-
-      function onClient (serverClient) {
-        serverClient.once('connect', function () {
-          server.removeListener('client', onClient)
-        })
-
-        serverClient.once('publish', function (packet) {
-          packet.topic.should.equal(topic)
-          packet.payload.toString().should.equal(payload)
-          packet.qos.should.equal(0)
-          packet.retain.should.equal(false)
-          client.end(true, done)
-        })
-      }
-    })
-
-    it('should publish a message (online)', function (done) {
-      var client = connect()
-      var payload = 'test'
-      var topic = 'test'
-
-      client.on('connect', function () {
-        client.publish(topic, payload)
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('publish', function (packet) {
-          packet.topic.should.equal(topic)
-          packet.payload.toString().should.equal(payload)
-          packet.qos.should.equal(0)
-          packet.retain.should.equal(false)
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should publish a message (retain, offline)', function (done) {
-      var client = connect({ queueQoSZero: true })
-      var payload = 'test'
-      var topic = 'test'
-      var called = false
-
-      client.publish(topic, payload, { retain: true }, function () {
-        called = true
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('publish', function (packet) {
-          packet.topic.should.equal(topic)
-          packet.payload.toString().should.equal(payload)
-          packet.qos.should.equal(0)
-          packet.retain.should.equal(true)
-          called.should.equal(true)
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should emit a packetsend event', function (done) {
-      var client = connect()
-      var payload = 'test_payload'
-      var testTopic = 'testTopic'
-
-      client.on('packetsend', function (packet) {
-        if (packet.cmd === 'publish') {
-          packet.qos.should.equal(0)
-          packet.topic.should.equal(testTopic)
-          packet.payload.should.equal(payload)
-          packet.retain.should.equal(false)
-          client.end()
-          done()
-        }
-      })
-
-      client.publish(testTopic, payload)
-    })
-
-    it('should accept options', function (done) {
-      var client = connect()
-      var payload = 'test'
-      var topic = 'test'
-      var opts = {
-        retain: true,
-        qos: 1
-      }
-
-      client.once('connect', function () {
-        client.publish(topic, payload, opts)
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('publish', function (packet) {
-          packet.topic.should.equal(topic)
-          packet.payload.toString().should.equal(payload)
-          packet.qos.should.equal(opts.qos, 'incorrect qos')
-          packet.retain.should.equal(opts.retain, 'incorrect ret')
-          packet.dup.should.equal(false, 'incorrect dup')
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should publish with the default options for an empty parameter', function (done) {
-      var client = connect()
-      var payload = 'test'
-      var topic = 'test'
-      var defaultOpts = {qos: 0, retain: false, dup: false}
-
-      client.once('connect', function () {
-        client.publish(topic, payload, {})
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('publish', function (packet) {
-          packet.topic.should.equal(topic)
-          packet.payload.toString().should.equal(payload)
-          packet.qos.should.equal(defaultOpts.qos, 'incorrect qos')
-          packet.retain.should.equal(defaultOpts.retain, 'incorrect ret')
-          packet.dup.should.equal(defaultOpts.dup, 'incorrect dup')
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should mark a message as  duplicate when "dup" option is set', function (done) {
-      var client = connect()
-      var payload = 'duplicated-test'
-      var topic = 'test'
-      var opts = {
-        retain: true,
-        qos: 1,
-        dup: true
-      }
-
-      client.once('connect', function () {
-        client.publish(topic, payload, opts)
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('publish', function (packet) {
-          packet.topic.should.equal(topic)
-          packet.payload.toString().should.equal(payload)
-          packet.dup.should.equal(opts.dup, 'incorrect dup')
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should fire a callback (qos 0)', function (done) {
-      var client = connect()
-
-      client.once('connect', function () {
-        client.publish('a', 'b', function () {
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should fire a callback (qos 1)', function (done) {
-      var client = connect()
-      var opts = { qos: 1 }
-
-      client.once('connect', function () {
-        client.publish('a', 'b', opts, function () {
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should fire a callback (qos 2)', function (done) {
-      var client = connect()
-      var opts = { qos: 2 }
-
-      client.once('connect', function () {
-        client.publish('a', 'b', opts, function () {
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should support UTF-8 characters in topic', function (done) {
-      var client = connect()
-
-      client.once('connect', function () {
-        client.publish('中国', 'hello', function () {
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should support UTF-8 characters in payload', function (done) {
-      var client = connect()
-
-      client.once('connect', function () {
-        client.publish('hello', '中国', function () {
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should publish 10 QoS 2 and receive them', function (done) {
-      var client = connect()
-      var count = 0
-
-      client.on('connect', function () {
-        client.subscribe('test')
-        client.publish('test', 'test', { qos: 2 })
-      })
-
-      client.on('message', function () {
-        if (count >= 10) {
-          client.end()
-          done()
-        } else {
-          client.publish('test', 'test', { qos: 2 })
-        }
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.on('offline', function () {
-          client.end()
-          done('error went offline... didnt see this happen')
-        })
-
-        serverClient.on('subscribe', function () {
-          serverClient.on('publish', function (packet) {
-            serverClient.publish(packet)
-          })
-        })
-
-        serverClient.on('pubrel', function () {
-          count++
-        })
-      })
-    })
-
-    function testQosHandleMessage (qos, done) {
-      var client = connect()
-
-      var messageEventCount = 0
-      var handleMessageCount = 0
-
-      client.handleMessage = function (packet, callback) {
-        setTimeout(function () {
-          handleMessageCount++
-          // next message event should not emit until handleMessage completes
-          handleMessageCount.should.equal(messageEventCount)
-          if (handleMessageCount === 10) {
-            setTimeout(function () {
-              client.end()
-              done()
-            })
-          }
-          callback()
-        }, 100)
-      }
-
-      client.on('message', function (topic, message, packet) {
-        messageEventCount++
-      })
-
-      client.on('connect', function () {
-        client.subscribe('test')
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.on('offline', function () {
-          client.end()
-          done('error went offline... didnt see this happen')
-        })
-
-        serverClient.on('subscribe', function () {
-          for (var i = 0; i < 10; i++) {
-            serverClient.publish({
-              messageId: i,
-              topic: 'test',
-              payload: 'test' + i,
-              qos: qos
-            })
-          }
-        })
-      })
-    }
-
-    it('should publish 10 QoS 0 and receive them only when `handleMessage` finishes', function (done) {
-      testQosHandleMessage(0, done)
-    })
-
-    it('should publish 10 QoS 1 and receive them only when `handleMessage` finishes', function (done) {
-      testQosHandleMessage(1, done)
-    })
-
-    it('should publish 10 QoS 2 and receive them only when `handleMessage` finishes', function (done) {
-      testQosHandleMessage(2, done)
-    })
-
-    it('should not send a `puback` if the execution of `handleMessage` fails for messages with QoS `1`', function (done) {
-      var client = connect()
-
-      client.handleMessage = function (packet, callback) {
-        callback(new Error('Error thrown by the application'))
-      }
-
-      client._sendPacket = sinon.spy()
-
-      client._handlePublish({
-        messageId: Math.floor(65535 * Math.random()),
-        topic: 'test',
-        payload: 'test',
-        qos: 1
-      }, function (err) {
-        should.exist(err)
-      })
-
-      client._sendPacket.callCount.should.equal(0)
-      client.end()
-      client.on('connect', function () { done() })
-    })
-
-    it('should silently ignore errors thrown by `handleMessage` and return when no callback is passed ' +
-      'into `handlePublish` method', function (done) {
-      var client = connect()
-
-      client.handleMessage = function (packet, callback) {
-        callback(new Error('Error thrown by the application'))
-      }
-
-      try {
-        client._handlePublish({
-          messageId: Math.floor(65535 * Math.random()),
-          topic: 'test',
-          payload: 'test',
-          qos: 1
-        })
-        done()
-      } catch (err) {
-        done(err)
-      } finally {
-        client.end()
-      }
-    })
-
-    it('should handle error with async incoming store in QoS 2 `handlePublish` method', function (done) {
-      function AsyncStore () {
-        if (!(this instanceof AsyncStore)) {
-          return new AsyncStore()
-        }
-      }
-      AsyncStore.prototype.put = function (packet, cb) {
-        process.nextTick(function () {
-          cb(new Error('Error'))
-        })
-      }
-      var store = new AsyncStore()
-      var client = connect({incomingStore: store})
-
-      client._handlePublish({
-        messageId: 1,
-        topic: 'test',
-        payload: 'test',
-        qos: 2
-      }, function () {
-        done()
-        client.end()
-      })
-    })
-
-    it('should handle error with async incoming store in QoS 2 `handlePubrel` method', function (done) {
-      function AsyncStore () {
-        if (!(this instanceof AsyncStore)) {
-          return new AsyncStore()
-        }
-      }
-      AsyncStore.prototype.put = function (packet, cb) {
-        process.nextTick(function () {
-          cb(new Error('Error'))
-        })
-      }
-      AsyncStore.prototype.get = function (packet, cb) {
-        process.nextTick(function () {
-          cb(null, {cmd: 'publish'})
-        })
-      }
-      var store = new AsyncStore()
-      var client = connect({incomingStore: store})
-
-      client._handlePubrel({
-        messageId: 1,
-        qos: 2
-      }, function () {
-        done()
-        client.end()
-      })
-    })
-
-    it('should handle success with async incoming store in QoS 2 `handlePubrel` method', function (done) {
-      var putComplete = false
-      function AsyncStore () {
-        if (!(this instanceof AsyncStore)) {
-          return new AsyncStore()
-        }
-      }
-      AsyncStore.prototype.put = function (packet, cb) {
-        process.nextTick(function () {
-          putComplete = true
-          cb(null)
-        })
-      }
-      AsyncStore.prototype.get = function (packet, cb) {
-        process.nextTick(function () {
-          cb(null, {cmd: 'publish'})
-        })
-      }
-      var store = new AsyncStore()
-      var client = connect({incomingStore: store})
-
-      client._handlePubrel({
-        messageId: 1,
-        qos: 2
-      }, function () {
-        putComplete.should.equal(true)
-        done()
-        client.end()
-      })
-    })
-
-    it('should handle error with async incoming store in QoS 1 `handlePublish` method', function (done) {
-      function AsyncStore () {
-        if (!(this instanceof AsyncStore)) {
-          return new AsyncStore()
-        }
-      }
-      AsyncStore.prototype.put = function (packet, cb) {
-        process.nextTick(function () {
-          cb(null, 'Error')
-        })
-      }
-      var store = new AsyncStore()
-      var client = connect({incomingStore: store})
-
-      client._handlePublish({
-        messageId: 1,
-        topic: 'test',
-        payload: 'test',
-        qos: 1
-      }, function () {
-        done()
-        client.end()
-      })
-    })
-
-    it('should not send a `pubcomp` if the execution of `handleMessage` fails for messages with QoS `2`', function (done) {
-      var store = new Store()
-      var client = connect({incomingStore: store})
-
-      var messageId = Math.floor(65535 * Math.random())
-      var topic = 'test'
-      var payload = 'test'
-      var qos = 2
-
-      client.handleMessage = function (packet, callback) {
-        callback(new Error('Error thrown by the application'))
-      }
-
-      client.once('connect', function () {
-        client.subscribe(topic, {qos: 2})
-
-        store.put({
-          messageId: messageId,
-          topic: topic,
-          payload: payload,
-          qos: qos,
-          cmd: 'publish'
-        }, function () {
-          // cleans up the client
-          client.end()
-
-          client._sendPacket = sinon.spy()
-          client._handlePubrel({cmd: 'pubrel', messageId: messageId}, function (err) {
-            should.exist(err)
-          })
-          client._sendPacket.callCount.should.equal(0)
-          done()
-        })
-      })
-    })
-
-    it('should silently ignore errors thrown by `handleMessage` and return when no callback is passed ' +
-      'into `handlePubrel` method', function (done) {
-      var store = new Store()
-      var client = connect({incomingStore: store})
-
-      var messageId = Math.floor(65535 * Math.random())
-      var topic = 'test'
-      var payload = 'test'
-      var qos = 2
-
-      client.handleMessage = function (packet, callback) {
-        callback(new Error('Error thrown by the application'))
-      }
-
-      client.once('connect', function () {
-        client.subscribe(topic, {qos: 2})
-
-        store.put({
-          messageId: messageId,
-          topic: topic,
-          payload: payload,
-          qos: qos,
-          cmd: 'publish'
-        }, function () {
-          try {
-            client._handlePubrel({cmd: 'pubrel', messageId: messageId})
-            done()
-          } catch (err) {
-            done(err)
-          } finally {
-            client.end()
-          }
-        })
-      })
-    })
-  })
-
-  describe('unsubscribing', function () {
-    it('should send an unsubscribe packet (offline)', function (done) {
-      var client = connect()
-
-      client.unsubscribe('test')
-
-      server.once('client', function (serverClient) {
-        serverClient.once('unsubscribe', function (packet) {
-          packet.unsubscriptions.should.containEql('test')
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should send an unsubscribe packet', function (done) {
-      var client = connect()
-      var topic = 'topic'
-
-      client.once('connect', function () {
-        client.unsubscribe(topic)
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('unsubscribe', function (packet) {
-          packet.unsubscriptions.should.containEql(topic)
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should emit a packetsend event', function (done) {
-      var client = connect()
-      var testTopic = 'testTopic'
-
-      client.once('connect', function () {
-        client.subscribe(testTopic)
-      })
-
-      client.on('packetsend', function (packet) {
-        if (packet.cmd === 'subscribe') {
-          client.end()
-          done()
-        }
-      })
-    })
-
-    it('should emit a packetreceive event', function (done) {
-      var client = connect()
-      var testTopic = 'testTopic'
-
-      client.once('connect', function () {
-        client.subscribe(testTopic)
-      })
-
-      client.on('packetreceive', function (packet) {
-        if (packet.cmd === 'suback') {
-          client.end()
-          done()
-        }
-      })
-    })
-
-    it('should accept an array of unsubs', function (done) {
-      var client = connect()
-      var topics = ['topic1', 'topic2']
-
-      client.once('connect', function () {
-        client.unsubscribe(topics)
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('unsubscribe', function (packet) {
-          packet.unsubscriptions.should.eql(topics)
-          done()
-        })
-      })
-    })
-
-    it('should fire a callback on unsuback', function (done) {
-      var client = connect()
-      var topic = 'topic'
-
-      client.once('connect', function () {
-        client.unsubscribe(topic, done)
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('unsubscribe', function (packet) {
-          serverClient.unsuback(packet)
-          client.end()
-        })
-      })
-    })
-
-    it('should unsubscribe from a chinese topic', function (done) {
-      var client = connect()
-      var topic = '中国'
-
-      client.once('connect', function () {
-        client.unsubscribe(topic)
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('unsubscribe', function (packet) {
-          packet.unsubscriptions.should.containEql(topic)
-          client.end()
-          done()
-        })
-      })
-    })
-  })
-
-  describe('keepalive', function () {
-    var clock
-
-    beforeEach(function () {
-      clock = sinon.useFakeTimers()
-    })
-
-    afterEach(function () {
-      clock.restore()
-    })
-
-    it('should checkPing at keepalive interval', function (done) {
-      var interval = 3
-      var client = connect({ keepalive: interval })
-
-      client._checkPing = sinon.spy()
-
-      client.once('connect', function () {
-        clock.tick(interval * 1000)
-        client._checkPing.callCount.should.equal(1)
-
-        clock.tick(interval * 1000)
-        client._checkPing.callCount.should.equal(2)
-
-        clock.tick(interval * 1000)
-        client._checkPing.callCount.should.equal(3)
-
-        client.end()
-        done()
-      })
-    })
-
-    it('should not checkPing if publishing at a higher rate than keepalive', function (done) {
-      var intervalMs = 3000
-      var client = connect({keepalive: intervalMs / 1000})
-
-      client._checkPing = sinon.spy()
-
-      client.once('connect', function () {
-        client.publish('foo', 'bar')
-        clock.tick(intervalMs - 1)
-        client.publish('foo', 'bar')
-        clock.tick(2)
-        client._checkPing.callCount.should.equal(0)
-        client.end()
-        done()
-      })
-    })
-
-    it('should checkPing if publishing at a higher rate than keepalive and reschedulePings===false', function (done) {
-      var intervalMs = 3000
-      var client = connect({
-        keepalive: intervalMs / 1000,
-        reschedulePings: false
-      })
-
-      client._checkPing = sinon.spy()
-
-      client.once('connect', function () {
-        client.publish('foo', 'bar')
-        clock.tick(intervalMs - 1)
-        client.publish('foo', 'bar')
-        clock.tick(2)
-        client._checkPing.callCount.should.equal(1)
-        client.end()
-        done()
-      })
-    })
-  })
-
-  describe('pinging', function () {
-    it('should set a ping timer', function (done) {
-      var client = connect({keepalive: 3})
-      client.once('connect', function () {
-        should.exist(client.pingTimer)
-        client.end()
-        done()
-      })
-    })
-
-    it('should not set a ping timer keepalive=0', function (done) {
-      var client = connect({keepalive: 0})
-      client.on('connect', function () {
-        should.not.exist(client.pingTimer)
-        client.end()
-        done()
-      })
-    })
-
-    it('should reconnect if pingresp is not sent', function (done) {
-      var client = connect({keepalive: 1, reconnectPeriod: 100})
-
-      // Fake no pingresp being send by stubbing the _handlePingresp function
-      client._handlePingresp = function () {}
-
-      client.once('connect', function () {
-        client.once('connect', function () {
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should not reconnect if pingresp is successful', function (done) {
-      var client = connect({keepalive: 100})
-      client.once('close', function () {
-        done(new Error('Client closed connection'))
-      })
-      setTimeout(done, 1000)
-    })
-
-    it('should defer the next ping when sending a control packet', function (done) {
-      var client = connect({keepalive: 1})
-
-      client.once('connect', function () {
-        client._checkPing = sinon.spy()
-
-        client.publish('foo', 'bar')
-        setTimeout(function () {
-          client._checkPing.callCount.should.equal(0)
-          client.publish('foo', 'bar')
-
-          setTimeout(function () {
-            client._checkPing.callCount.should.equal(0)
-            client.publish('foo', 'bar')
-
-            setTimeout(function () {
-              client._checkPing.callCount.should.equal(0)
-              done()
-            }, 75)
-          }, 75)
-        }, 75)
-      })
-    })
-  })
-
-  describe('subscribing', function () {
-    it('should send a subscribe message (offline)', function (done) {
-      var client = connect()
-
-      client.subscribe('test')
-
-      server.once('client', function (serverClient) {
-        serverClient.once('subscribe', function () {
-          done()
-        })
-      })
-    })
-
-    it('should send a subscribe message', function (done) {
-      var client = connect()
-      var topic = 'test'
-
-      client.once('connect', function () {
-        client.subscribe(topic)
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('subscribe', function (packet) {
-          packet.subscriptions.should.containEql({
-            topic: topic,
-            qos: 0
-          })
-          done()
-        })
-      })
-    })
-
-    it('should emit a packetsend event', function (done) {
-      var client = connect()
-      var testTopic = 'testTopic'
-
-      client.once('connect', function () {
-        client.subscribe(testTopic)
-      })
-
-      client.on('packetsend', function (packet) {
-        if (packet.cmd === 'subscribe') {
-          done()
-        }
-      })
-    })
-
-    it('should emit a packetreceive event', function (done) {
-      var client = connect()
-      var testTopic = 'testTopic'
-
-      client.once('connect', function () {
-        client.subscribe(testTopic)
-      })
-
-      client.on('packetreceive', function (packet) {
-        if (packet.cmd === 'suback') {
-          done()
-        }
-      })
-    })
-
-    it('should accept an array of subscriptions', function (done) {
-      var client = connect()
-      var subs = ['test1', 'test2']
-
-      client.once('connect', function () {
-        client.subscribe(subs)
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('subscribe', function (packet) {
-          // i.e. [{topic: 'a', qos: 0}, {topic: 'b', qos: 0}]
-          var expected = subs.map(function (i) {
-            return {topic: i, qos: 0}
-          })
-
-          packet.subscriptions.should.eql(expected)
-          done()
-        })
-      })
-    })
-
-    it('should accept an hash of subscriptions', function (done) {
-      var client = connect()
-      var topics = {
-        test1: 0,
-        test2: 1
-      }
-
-      client.once('connect', function () {
-        client.subscribe(topics)
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('subscribe', function (packet) {
-          var k
-          var expected = []
-
-          for (k in topics) {
-            if (topics.hasOwnProperty(k)) {
-              expected.push({
-                topic: k,
-                qos: topics[k]
-              })
-            }
-          }
-
-          packet.subscriptions.should.eql(expected)
-          done()
-        })
-      })
-    })
-
-    it('should accept an options parameter', function (done) {
-      var client = connect()
-      var topic = 'test'
-      var opts = {qos: 1}
-
-      client.once('connect', function () {
-        client.subscribe(topic, opts)
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('subscribe', function (packet) {
-          var expected = [{
-            topic: topic,
-            qos: 1
-          }]
-
-          packet.subscriptions.should.eql(expected)
-          done()
-        })
-      })
-    })
-
-    it('should subscribe with the default options for an empty options parameter', function (done) {
-      var client = connect()
-      var topic = 'test'
-      var defaultOpts = {qos: 0}
-
-      client.once('connect', function () {
-        client.subscribe(topic, {})
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('subscribe', function (packet) {
-          packet.subscriptions.should.containEql({
-            topic: topic,
-            qos: defaultOpts.qos
-          })
-          done()
-        })
-      })
-    })
-
-    it('should fire a callback on suback', function (done) {
-      var client = connect()
-      var topic = 'test'
-
-      client.once('connect', function () {
-        client.subscribe(topic, { qos: 2 }, function (err, granted) {
-          if (err) {
-            done(err)
-          } else {
-            should.exist(granted, 'granted not given')
-            granted.should.containEql({topic: 'test', qos: 2})
-            done()
-          }
-        })
-      })
-    })
-
-    it('should fire a callback with error if disconnected (options provided)', function (done) {
-      var client = connect()
-      var topic = 'test'
-      client.once('connect', function () {
-        client.end(true, function () {
-          client.subscribe(topic, {qos: 2}, function (err, granted) {
-            should.not.exist(granted, 'granted given')
-            should.exist(err, 'no error given')
-            done()
-          })
-        })
-      })
-    })
-
-    it('should fire a callback with error if disconnected (options not provided)', function (done) {
-      var client = connect()
-      var topic = 'test'
-
-      client.once('connect', function () {
-        client.end(true, function () {
-          client.subscribe(topic, function (err, granted) {
-            should.not.exist(granted, 'granted given')
-            should.exist(err, 'no error given')
-            done()
-          })
-        })
-      })
-    })
-
-    it('should subscribe with a chinese topic', function (done) {
-      var client = connect()
-      var topic = '中国'
-
-      client.once('connect', function () {
-        client.subscribe(topic)
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('subscribe', function (packet) {
-          packet.subscriptions.should.containEql({
-            topic: topic,
-            qos: 0
-          })
-          done()
-        })
-      })
-    })
-  })
-
-  describe('receiving messages', function () {
-    it('should fire the message event', function (done) {
-      var client = connect()
-      var testPacket = {
-        topic: 'test',
-        payload: 'message',
-        retain: true,
-        qos: 1,
-        messageId: 5
-      }
-
-      client.subscribe(testPacket.topic)
-      client.once('message', function (topic, message, packet) {
-        topic.should.equal(testPacket.topic)
-        message.toString().should.equal(testPacket.payload)
-        packet.should.equal(packet)
-        client.end()
-        done()
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.on('subscribe', function () {
-          serverClient.publish(testPacket)
-        })
-      })
-    })
-
-    it('should emit a packetreceive event', function (done) {
-      var client = connect()
-      var testPacket = {
-        topic: 'test',
-        payload: 'message',
-        retain: true,
-        qos: 1,
-        messageId: 5
-      }
-
-      client.subscribe(testPacket.topic)
-      client.on('packetreceive', function (packet) {
-        if (packet.cmd === 'publish') {
-          packet.qos.should.equal(1)
-          packet.topic.should.equal(testPacket.topic)
-          packet.payload.toString().should.equal(testPacket.payload)
-          packet.retain.should.equal(true)
-          client.end()
-          done()
-        }
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.on('subscribe', function () {
-          serverClient.publish(testPacket)
-        })
-      })
-    })
-
-    it('should support binary data', function (done) {
-      var client = connect({ encoding: 'binary' })
-      var testPacket = {
-        topic: 'test',
-        payload: 'message',
-        retain: true,
-        qos: 1,
-        messageId: 5
-      }
-
-      client.subscribe(testPacket.topic)
-      client.once('message', function (topic, message, packet) {
-        topic.should.equal(testPacket.topic)
-        message.should.be.an.instanceOf(Buffer)
-        message.toString().should.equal(testPacket.payload)
-        packet.should.equal(packet)
-        done()
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.on('subscribe', function () {
-          serverClient.publish(testPacket)
-        })
-      })
-    })
-
-    it('should emit a message event (qos=2)', function (done) {
-      var client = connect()
-      var testPacket = {
-        topic: 'test',
-        payload: 'message',
-        retain: true,
-        qos: 2,
-        messageId: 5
-      }
-
-      server.testPublish = testPacket
-
-      client.subscribe(testPacket.topic)
-      client.once('message', function (topic, message, packet) {
-        topic.should.equal(testPacket.topic)
-        message.toString().should.equal(testPacket.payload)
-        packet.should.equal(packet)
-        done()
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.on('subscribe', function () {
-          serverClient.publish(testPacket)
-        })
-      })
-    })
-
-    it('should emit a message event (qos=2) - repeated publish', function (done) {
-      var client = connect()
-      var testPacket = {
-        topic: 'test',
-        payload: 'message',
-        retain: true,
-        qos: 2,
-        messageId: 5
-      }
-
-      server.testPublish = testPacket
-
-      client.subscribe(testPacket.topic)
-      client.on('message', function (topic, message, packet) {
-        topic.should.equal(testPacket.topic)
-        message.toString().should.equal(testPacket.payload)
-        packet.should.equal(packet)
-        done()
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.on('subscribe', function () {
-          serverClient.publish(testPacket)
-          // twice, should be ignored
-          serverClient.publish(testPacket)
-        })
-      })
-    })
-
-    it('should support chinese topic', function (done) {
-      var client = connect({ encoding: 'binary' })
-      var testPacket = {
-        topic: '国',
-        payload: 'message',
-        retain: true,
-        qos: 1,
-        messageId: 5
-      }
-
-      client.subscribe(testPacket.topic)
-      client.once('message', function (topic, message, packet) {
-        topic.should.equal(testPacket.topic)
-        message.should.be.an.instanceOf(Buffer)
-        message.toString().should.equal(testPacket.payload)
-        packet.should.equal(packet)
-        done()
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.on('subscribe', function () {
-          serverClient.publish(testPacket)
-        })
-      })
-    })
-  })
-
-  describe('qos handling', function () {
-    it('should follow qos 0 semantics (trivial)', function (done) {
-      var client = connect()
-      var testTopic = 'test'
-      var testMessage = 'message'
-
-      client.once('connect', function () {
-        client.subscribe(testTopic, {qos: 0})
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('subscribe', function () {
-          serverClient.publish({
-            topic: testTopic,
-            payload: testMessage,
-            qos: 0,
-            retain: false
-          })
-          done()
-        })
-      })
-    })
-
-    it('should follow qos 1 semantics', function (done) {
-      var client = connect()
-      var testTopic = 'test'
-      var testMessage = 'message'
-      var mid = 50
-
-      client.once('connect', function () {
-        client.subscribe(testTopic, {qos: 1})
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('subscribe', function () {
-          serverClient.publish({
-            topic: testTopic,
-            payload: testMessage,
-            messageId: mid,
-            qos: 1
-          })
-        })
-
-        serverClient.once('puback', function (packet) {
-          packet.messageId.should.equal(mid)
-          done()
-        })
-      })
-    })
-
-    it('should follow qos 2 semantics', function (done) {
-      var client = connect()
-      var testTopic = 'test'
-      var testMessage = 'message'
-      var mid = 253
-
-      client.once('connect', function () {
-        client.subscribe(testTopic, {qos: 2})
-      })
-
-      server.once('client', function (serverClient) {
-        serverClient.once('subscribe', function () {
-          serverClient.publish({
-            topic: testTopic,
-            payload: testMessage,
-            qos: 2,
-            messageId: mid
-          })
-        })
-
-        serverClient.once('pubcomp', function () {
-          done()
-        })
-      })
-    })
-  })
-
-  describe('auto reconnect', function () {
-    it('should mark the client disconnecting if #end called', function () {
-      var client = connect()
-
-      client.end()
-      client.disconnecting.should.eql(true)
-    })
-
-    it('should reconnect after stream disconnect', function (done) {
-      var client = connect()
-      var tryReconnect = true
-
-      client.on('connect', function () {
-        if (tryReconnect) {
-          client.stream.end()
-          tryReconnect = false
-        } else {
-          client.end()
-          done()
-        }
-      })
-    })
-
-    it('should emit \'reconnect\' when reconnecting', function (done) {
-      var client = connect()
-      var tryReconnect = true
-      var reconnectEvent = false
-
-      client.on('reconnect', function () {
-        reconnectEvent = true
-      })
-
-      client.on('connect', function () {
-        if (tryReconnect) {
-          client.stream.end()
-          tryReconnect = false
-        } else {
-          reconnectEvent.should.equal(true)
-          client.end()
-          done()
-        }
-      })
-    })
-
-    it('should emit \'offline\' after going offline', function (done) {
-      var client = connect()
-      var tryReconnect = true
-      var offlineEvent = false
-
-      client.on('offline', function () {
-        offlineEvent = true
-      })
-
-      client.on('connect', function () {
-        if (tryReconnect) {
-          client.stream.end()
-          tryReconnect = false
-        } else {
-          offlineEvent.should.equal(true)
-          client.end()
-          done()
-        }
-      })
-    })
-
-    it('should not reconnect if it was ended by the user', function (done) {
-      var client = connect()
-
-      client.on('connect', function () {
-        client.end()
-        done() // it will raise an exception if called two times
-      })
-    })
-
-    it('should setup a reconnect timer on disconnect', function (done) {
-      var client = connect()
-
-      client.once('connect', function () {
-        should.not.exist(client.reconnectTimer)
-        client.stream.end()
-      })
-
-      client.once('close', function () {
-        should.exist(client.reconnectTimer)
-        client.end()
-        done()
-      })
-    })
-
-    it('should allow specification of a reconnect period', function (done) {
-      var end
-      var period = 200
-      var client = connect({reconnectPeriod: period})
-      var reconnect = false
-      var start = Date.now()
-
-      client.on('connect', function () {
-        if (!reconnect) {
-          client.stream.end()
-          reconnect = true
-        } else {
-          client.end()
-          end = Date.now()
-          if (end - start >= period) {
-            // Connected in about 2 seconds, that's good enough
-            done()
-          } else {
-            done(new Error('Strange reconnect period'))
-          }
-        }
-      })
-    })
-
-    it('should always cleanup successfully on reconnection', function (done) {
-      var client = connect({host: 'this_hostname_should_not_exist', connectTimeout: 0, reconnectPeriod: 1})
-      setTimeout(client.end.bind(client, done), 50)
-    })
-
-    it('should resend in-flight QoS 1 publish messages from the client', function (done) {
-      var client = connect({reconnectPeriod: 200})
-      var serverPublished = false
-      var clientCalledBack = false
-
-      server.once('client', function (serverClient) {
-        serverClient.on('connect', function () {
-          setImmediate(function () {
-            serverClient.stream.destroy()
-          })
-        })
-
-        server.once('client', function (serverClientNew) {
-          serverClientNew.on('publish', function () {
-            serverPublished = true
-            check()
-          })
-        })
-      })
-
-      client.publish('hello', 'world', { qos: 1 }, function () {
-        clientCalledBack = true
-        check()
-      })
-
-      function check () {
-        if (serverPublished && clientCalledBack) {
-          client.end()
-          done()
-        }
-      }
-    })
-
-    it('should not resend in-flight publish messages if disconnecting', function (done) {
-      var client = connect({reconnectPeriod: 200})
-      var serverPublished = false
-      var clientCalledBack = false
-      server.once('client', function (serverClient) {
-        serverClient.on('connect', function () {
-          setImmediate(function () {
-            serverClient.stream.destroy()
-            client.end()
-            serverPublished.should.be.false()
-            clientCalledBack.should.be.false()
-            done()
-          })
-        })
-        server.once('client', function (serverClientNew) {
-          serverClientNew.on('publish', function () {
-            serverPublished = true
-          })
-        })
-      })
-      client.publish('hello', 'world', { qos: 1 }, function () {
-        clientCalledBack = true
-      })
-    })
-
-    it('should resend in-flight QoS 2 publish messages from the client', function (done) {
-      var client = connect({reconnectPeriod: 200})
-      var serverPublished = false
-      var clientCalledBack = false
-
-      server.once('client', function (serverClient) {
-        // ignore errors
-        serverClient.on('error', function () {})
-        serverClient.on('publish', function () {
-          setImmediate(function () {
-            serverClient.stream.destroy()
-          })
-        })
-
-        server.once('client', function (serverClientNew) {
-          serverClientNew.on('pubrel', function () {
-            serverPublished = true
-            check()
-          })
-        })
-      })
-
-      client.publish('hello', 'world', { qos: 2 }, function () {
-        clientCalledBack = true
-        check()
-      })
-
-      function check () {
-        if (serverPublished && clientCalledBack) {
-          client.end()
-          done()
-        }
-      }
-    })
-
-    it('should not resend in-flight QoS 1 removed publish messages from the client', function (done) {
-      var client = connect({reconnectPeriod: 200})
-      var clientCalledBack = false
-
-      server.once('client', function (serverClient) {
-        serverClient.on('connect', function () {
-          setImmediate(function () {
-            serverClient.stream.destroy()
-          })
-        })
-
-        server.once('client', function (serverClientNew) {
-          serverClientNew.on('publish', function () {
-            should.fail()
-            done()
-          })
-        })
-      })
-
-      client.publish('hello', 'world', { qos: 1 }, function (err) {
-        clientCalledBack = true
-        should(err.message).be.equal('Message removed')
-      })
-      should(Object.keys(client.outgoing).length).be.equal(1)
-      should(client.outgoingStore._inflights.size).be.equal(1)
-      client.removeOutgoingMessage(client.getLastMessageId())
-      should(Object.keys(client.outgoing).length).be.equal(0)
-      should(client.outgoingStore._inflights.size).be.equal(0)
-      clientCalledBack.should.be.true()
-      client.end()
-      done()
-    })
-
-    it('should not resend in-flight QoS 2 removed publish messages from the client', function (done) {
-      var client = connect({reconnectPeriod: 200})
-      var clientCalledBack = false
-
-      server.once('client', function (serverClient) {
-        serverClient.on('connect', function () {
-          setImmediate(function () {
-            serverClient.stream.destroy()
-          })
-        })
-
-        server.once('client', function (serverClientNew) {
-          serverClientNew.on('publish', function () {
-            should.fail()
-            done()
-          })
-        })
-      })
-
-      client.publish('hello', 'world', { qos: 2 }, function (err) {
-        clientCalledBack = true
-        should(err.message).be.equal('Message removed')
-      })
-      should(Object.keys(client.outgoing).length).be.equal(1)
-      should(client.outgoingStore._inflights.size).be.equal(1)
-      client.removeOutgoingMessage(client.getLastMessageId())
-      should(Object.keys(client.outgoing).length).be.equal(0)
-      should(client.outgoingStore._inflights.size).be.equal(0)
-      clientCalledBack.should.be.true()
-      client.end()
-      done()
-    })
-
-    it('should resubscribe when reconnecting', function (done) {
-      var client = connect({ reconnectPeriod: 100 })
-      var tryReconnect = true
-      var reconnectEvent = false
-
-      client.on('reconnect', function () {
-        reconnectEvent = true
-      })
-
-      client.on('connect', function () {
-        if (tryReconnect) {
-          client.subscribe('hello', function () {
-            client.stream.end()
-
-            server.once('client', function (serverClient) {
-              serverClient.on('subscribe', function () {
-                client.end()
-                done()
-              })
-            })
-          })
-
-          tryReconnect = false
-        } else {
-          reconnectEvent.should.equal(true)
-        }
-      })
-    })
-
-    it('should not resubscribe when reconnecting if resubscribe is disabled', function (done) {
-      var client = connect({ reconnectPeriod: 100, resubscribe: false })
-      var tryReconnect = true
-      var reconnectEvent = false
-
-      client.on('reconnect', function () {
-        reconnectEvent = true
-      })
-
-      client.on('connect', function () {
-        if (tryReconnect) {
-          client.subscribe('hello', function () {
-            client.stream.end()
-
-            server.once('client', function (serverClient) {
-              serverClient.on('subscribe', function () {
-                should.fail()
-              })
-            })
-          })
-
-          tryReconnect = false
-        } else {
-          reconnectEvent.should.equal(true)
-          should(Object.keys(client._resubscribeTopics).length).be.equal(0)
-          done()
-        }
-      })
-    })
-
-    it('should not resubscribe when reconnecting if suback is error', function (done) {
-      var tryReconnect = true
-      var reconnectEvent = false
-      var server2 = new Server(function (c) {
-        c.on('connect', function (packet) {
-          c.connack({returnCode: 0})
-        })
-        c.on('subscribe', function (packet) {
-          c.suback({
-            messageId: packet.messageId,
-            granted: packet.subscriptions.map(function (e) {
-              return e.qos | 0x80
-            })
-          })
-          c.pubrel({ messageId: Math.floor(Math.random() * 9000) + 1000 })
-        })
-      })
-
-      server2.listen(port + 49, function () {
-        var client = mqtt.connect({
-          port: port + 49,
-          host: 'localhost',
-          reconnectPeriod: 100
-        })
-
-        client.on('reconnect', function () {
-          reconnectEvent = true
-        })
-
-        client.on('connect', function () {
-          if (tryReconnect) {
-            client.subscribe('hello', function () {
-              client.stream.end()
-
-              server.once('client', function (serverClient) {
-                serverClient.on('subscribe', function () {
-                  should.fail()
-                })
-              })
-            })
-            tryReconnect = false
-          } else {
-            reconnectEvent.should.equal(true)
-            should(Object.keys(client._resubscribeTopics).length).be.equal(0)
-            server2.close()
-            done()
-          }
-        })
-      })
-    })
-
-    it('should preserved incomingStore after disconnecting if clean is false', function (done) {
-      var reconnect = false
-      var client = {}
-      var incomingStore = new mqtt.Store({ clean: false })
-      var outgoingStore = new mqtt.Store({ clean: false })
-      var server2 = new Server(function (c) {
-        c.on('connect', function (packet) {
-          c.connack({returnCode: 0})
-          if (reconnect) {
-            c.pubrel({ messageId: 1 })
-          }
-        })
-        c.on('subscribe', function (packet) {
-          c.suback({
-            messageId: packet.messageId,
-            granted: packet.subscriptions.map(function (e) {
-              return e.qos
-            })
-          })
-          c.publish({ topic: 'topic', payload: 'payload', qos: 2, messageId: 1, retain: false })
-        })
-        c.on('pubrec', function (packet) {
-          client.end(false, function () {
-            client.reconnect({
-              incomingStore: incomingStore,
-              outgoingStore: outgoingStore
-            })
-          })
-        })
-        c.on('pubcomp', function (packet) {
-          client.end()
-          server2.close()
-          done()
-        })
-      })
-
-      server2.listen(port + 50, function () {
-        client = mqtt.connect({
-          port: port + 50,
-          host: 'localhost',
-          clean: false,
-          clientId: 'cid1',
-          reconnectPeriod: 0,
-          incomingStore: incomingStore,
-          outgoingStore: outgoingStore
-        })
-
-        client.on('connect', function () {
-          if (!reconnect) {
-            client.subscribe('test', {qos: 2}, function () {
-            })
-            reconnect = true
-          }
-        })
-        client.on('message', function (topic, message) {
-          topic.should.equal('topic')
-          message.toString().should.equal('payload')
-        })
-      })
-    })
-
-    it('should resend in-flight QoS 1 publish messages from the client if clean is false', function (done) {
-      var reconnect = false
-      var client = {}
-      var incomingStore = new mqtt.Store({ clean: false })
-      var outgoingStore = new mqtt.Store({ clean: false })
-      var server2 = new Server(function (c) {
-        c.on('connect', function (packet) {
-          c.connack({returnCode: 0})
-        })
-        c.on('publish', function (packet) {
-          if (reconnect) {
-            server2.close()
-            done()
-          } else {
-            client.end(true, function () {
-              client.reconnect({
-                incomingStore: incomingStore,
-                outgoingStore: outgoingStore
-              })
-              reconnect = true
-            })
-          }
-        })
-      })
-
-      server2.listen(port + 50, function () {
-        client = mqtt.connect({
-          port: port + 50,
-          host: 'localhost',
-          clean: false,
-          clientId: 'cid1',
-          reconnectPeriod: 0,
-          incomingStore: incomingStore,
-          outgoingStore: outgoingStore
-        })
-
-        client.on('connect', function () {
-          if (!reconnect) {
-            client.publish('topic', 'payload', {qos: 1})
-          }
-        })
-        client.on('error', function () {})
-      })
-    })
-
-    it('should resend in-flight QoS 2 publish messages from the client if clean is false', function (done) {
-      var reconnect = false
-      var client = {}
-      var incomingStore = new mqtt.Store({ clean: false })
-      var outgoingStore = new mqtt.Store({ clean: false })
-      var server2 = new Server(function (c) {
-        c.on('connect', function (packet) {
-          c.connack({returnCode: 0})
-        })
-        c.on('publish', function (packet) {
-          if (reconnect) {
-            server2.close()
-            done()
-          } else {
-            client.end(true, function () {
-              client.reconnect({
-                incomingStore: incomingStore,
-                outgoingStore: outgoingStore
-              })
-              reconnect = true
-            })
-          }
-        })
-      })
-
-      server2.listen(port + 50, function () {
-        client = mqtt.connect({
-          port: port + 50,
-          host: 'localhost',
-          clean: false,
-          clientId: 'cid1',
-          reconnectPeriod: 0,
-          incomingStore: incomingStore,
-          outgoingStore: outgoingStore
-        })
-
-        client.on('connect', function () {
-          if (!reconnect) {
-            client.publish('topic', 'payload', {qos: 2})
-          }
-        })
-        client.on('error', function () {})
-      })
-    })
-
-    it('should resend in-flight QoS 2 pubrel messages from the client if clean is false', function (done) {
-      var reconnect = false
-      var client = {}
-      var incomingStore = new mqtt.Store({ clean: false })
-      var outgoingStore = new mqtt.Store({ clean: false })
-      var server2 = new Server(function (c) {
-        c.on('connect', function (packet) {
-          c.connack({returnCode: 0})
-        })
-        c.on('publish', function (packet) {
-          if (!reconnect) {
-            c.pubrec({messageId: packet.messageId})
-          }
-        })
-        c.on('pubrel', function () {
-          if (reconnect) {
-            server2.close()
-            done()
-          } else {
-            client.end(true, function () {
-              client.reconnect({
-                incomingStore: incomingStore,
-                outgoingStore: outgoingStore
-              })
-              reconnect = true
-            })
-          }
-        })
-      })
-
-      server2.listen(port + 50, function () {
-        client = mqtt.connect({
-          port: port + 50,
-          host: 'localhost',
-          clean: false,
-          clientId: 'cid1',
-          reconnectPeriod: 0,
-          incomingStore: incomingStore,
-          outgoingStore: outgoingStore
-        })
-
-        client.on('connect', function () {
-          if (!reconnect) {
-            client.publish('topic', 'payload', {qos: 2})
-          }
-        })
-        client.on('error', function () {})
-      })
-    })
-
-    it('should resend in-flight publish messages by published order', function (done) {
-      var publishCount = 0
-      var reconnect = false
-      var disconnectOnce = true
-      var client = {}
-      var incomingStore = new mqtt.Store({ clean: false })
-      var outgoingStore = new mqtt.Store({ clean: false })
-      var server2 = new Server(function (c) {
-        // errors are not interesting for this test
-        // but they might happen on some platforms
-        c.on('error', function () {})
-
-        c.on('connect', function (packet) {
-          c.connack({returnCode: 0})
-        })
-        c.on('publish', function (packet) {
-          c.puback({messageId: packet.messageId})
-          if (reconnect) {
-            switch (publishCount++) {
-              case 0:
-                packet.payload.toString().should.equal('payload1')
-                break
-              case 1:
-                packet.payload.toString().should.equal('payload2')
-                break
-              case 2:
-                packet.payload.toString().should.equal('payload3')
-                server2.close()
-                done()
-                break
-            }
-          } else {
-            if (disconnectOnce) {
-              client.end(true, function () {
-                reconnect = true
-                client.reconnect({
-                  incomingStore: incomingStore,
-                  outgoingStore: outgoingStore
-                })
-              })
-              disconnectOnce = false
-            }
-          }
-        })
-      })
-
-      server2.listen(port + 50, function () {
-        client = mqtt.connect({
-          port: port + 50,
-          host: 'localhost',
-          clean: false,
-          clientId: 'cid1',
-          reconnectPeriod: 0,
-          incomingStore: incomingStore,
-          outgoingStore: outgoingStore
-        })
-
-        client.nextId = 65535
-
-        client.on('connect', function () {
-          if (!reconnect) {
-            client.publish('topic', 'payload1', {qos: 1})
-            client.publish('topic', 'payload2', {qos: 1})
-            client.publish('topic', 'payload3', {qos: 1})
-          }
-        })
-        client.on('error', function () {})
-      })
-    })
-
-    it('should be able to pub/sub if reconnect() is called at close handler', function (done) {
-      var client = connect({ reconnectPeriod: 0 })
-      var tryReconnect = true
-      var reconnectEvent = false
-
-      client.on('close', function () {
-        if (tryReconnect) {
-          tryReconnect = false
-          client.reconnect()
-        } else {
-          reconnectEvent.should.equal(true)
-          done()
-        }
-      })
-
-      client.on('reconnect', function () {
-        reconnectEvent = true
-      })
-
-      client.on('connect', function () {
-        if (tryReconnect) {
-          client.end()
-        } else {
-          client.subscribe('hello', function () {
-            client.end()
-          })
-        }
-      })
-    })
-
-    it('should be able to pub/sub if reconnect() is called at out of close handler', function (done) {
-      var client = connect({ reconnectPeriod: 0 })
-      var tryReconnect = true
-      var reconnectEvent = false
-
-      client.on('close', function () {
-        if (tryReconnect) {
-          tryReconnect = false
-          setTimeout(function () {
-            client.reconnect()
-          }, 100)
-        } else {
-          reconnectEvent.should.equal(true)
-          done()
-        }
-      })
-
-      client.on('reconnect', function () {
-        reconnectEvent = true
-      })
-
-      client.on('connect', function () {
-        if (tryReconnect) {
-          client.end()
-        } else {
-          client.subscribe('hello', function () {
-            client.end()
-          })
-        }
-      })
-    })
-
-    context('with alternate server client', function () {
-      var cachedClientListeners
-
-      beforeEach(function () {
-        cachedClientListeners = server.listeners('client')
-        server.removeAllListeners('client')
-      })
-
-      afterEach(function () {
-        server.removeAllListeners('client')
-        cachedClientListeners.forEach(function (listener) {
-          server.on('client', listener)
-        })
-      })
-
-      it('should resubscribe even if disconnect is before suback', function (done) {
-        var client = mqtt.connect(Object.assign({ reconnectPeriod: 100 }, config))
-        var subscribeCount = 0
-        var connectCount = 0
-
-        server.on('client', function (serverClient) {
-          serverClient.on('connect', function () {
-            connectCount++
-            serverClient.connack({returnCode: 0})
-          })
-
-          serverClient.on('subscribe', function () {
-            subscribeCount++
-
-            // disconnect before sending the suback on the first subscribe
-            if (subscribeCount === 1) {
-              client.stream.end()
-            }
-
-            // after the second connection, confirm that the only two
-            // subscribes have taken place, then cleanup and exit
-            if (connectCount >= 2) {
-              subscribeCount.should.equal(2)
-              client.end(true, done)
-            }
-          })
-        })
-
-        client.subscribe('hello')
-      })
-
-      it('should resubscribe exactly once', function (done) {
-        var client = mqtt.connect(Object.assign({ reconnectPeriod: 100 }, config))
-        var subscribeCount = 0
-
-        server.on('client', function (serverClient) {
-          serverClient.on('connect', function () {
-            serverClient.connack({returnCode: 0})
-          })
-
-          serverClient.on('subscribe', function () {
-            subscribeCount++
-
-            // disconnect before sending the suback on the first subscribe
-            if (subscribeCount === 1) {
-              client.stream.end()
-            }
-
-            // after the second connection, only two subs
-            // subscribes have taken place, then cleanup and exit
-            if (subscribeCount === 2) {
-              client.end(true, done)
-            }
-          })
-        })
-
-        client.subscribe('hello')
-      })
-    })
-  })
-}

+ 0 - 135
src/utils/mqtt/test/abstract_store.js

@@ -1,135 +0,0 @@
-'use strict'
-
-require('should')
-
-module.exports = function abstractStoreTest (build) {
-  var store
-
-  beforeEach(function (done) {
-    build(function (err, _store) {
-      store = _store
-      done(err)
-    })
-  })
-
-  afterEach(function (done) {
-    store.close(done)
-  })
-
-  it('should put and stream in-flight packets', function (done) {
-    var packet = {
-      topic: 'hello',
-      payload: 'world',
-      qos: 1,
-      messageId: 42
-    }
-
-    store.put(packet, function () {
-      store
-        .createStream()
-        .on('data', function (data) {
-          data.should.eql(packet)
-          done()
-        })
-    })
-  })
-
-  it('should support destroying the stream', function (done) {
-    var packet = {
-      topic: 'hello',
-      payload: 'world',
-      qos: 1,
-      messageId: 42
-    }
-
-    store.put(packet, function () {
-      var stream = store.createStream()
-      stream.on('close', done)
-      stream.destroy()
-    })
-  })
-
-  it('should add and del in-flight packets', function (done) {
-    var packet = {
-      topic: 'hello',
-      payload: 'world',
-      qos: 1,
-      messageId: 42
-    }
-
-    store.put(packet, function () {
-      store.del(packet, function () {
-        store
-          .createStream()
-          .on('data', function () {
-            done(new Error('this should never happen'))
-          })
-          .on('end', done)
-      })
-    })
-  })
-
-  it('should replace a packet when doing put with the same messageId', function (done) {
-    var packet1 = {
-      cmd: 'publish', // added
-      topic: 'hello',
-      payload: 'world',
-      qos: 2,
-      messageId: 42
-    }
-    var packet2 = {
-      cmd: 'pubrel', // added
-      qos: 2,
-      messageId: 42
-    }
-
-    store.put(packet1, function () {
-      store.put(packet2, function () {
-        store
-          .createStream()
-          .on('data', function (data) {
-            data.should.eql(packet2)
-            done()
-          })
-      })
-    })
-  })
-
-  it('should return the original packet on del', function (done) {
-    var packet = {
-      topic: 'hello',
-      payload: 'world',
-      qos: 1,
-      messageId: 42
-    }
-
-    store.put(packet, function () {
-      store.del({ messageId: 42 }, function (err, deleted) {
-        if (err) {
-          throw err
-        }
-        deleted.should.eql(packet)
-        done()
-      })
-    })
-  })
-
-  it('should get a packet with the same messageId', function (done) {
-    var packet = {
-      topic: 'hello',
-      payload: 'world',
-      qos: 1,
-      messageId: 42
-    }
-
-    store.put(packet, function () {
-      store.get({ messageId: 42 }, function (err, fromDb) {
-        if (err) {
-          throw err
-        }
-        fromDb.should.eql(packet)
-        done()
-      })
-    })
-  })
-}

+ 0 - 132
src/utils/mqtt/test/browser/server.js

@@ -1,132 +0,0 @@
-'use strict'
-
-var handleClient
-var websocket = require('websocket-stream')
-var WebSocketServer = require('ws').Server
-var Connection = require('mqtt-connection')
-var http = require('http')
-
-handleClient = function (client) {
-  var self = this
-
-  if (!self.clients) {
-    self.clients = {}
-  }
-
-  client.on('connect', function (packet) {
-    if (packet.clientId === 'invalid') {
-      client.connack({returnCode: 2})
-    } else {
-      client.connack({returnCode: 0})
-    }
-    self.clients[packet.clientId] = client
-    client.subscriptions = []
-  })
-
-  client.on('publish', function (packet) {
-    var i, k, c, s, publish
-    switch (packet.qos) {
-      case 0:
-        break
-      case 1:
-        client.puback(packet)
-        break
-      case 2:
-        client.pubrec(packet)
-        break
-    }
-
-    for (k in self.clients) {
-      c = self.clients[k]
-      publish = false
-
-      for (i = 0; i < c.subscriptions.length; i++) {
-        s = c.subscriptions[i]
-
-        if (s.test(packet.topic)) {
-          publish = true
-        }
-      }
-
-      if (publish) {
-        try {
-          c.publish({topic: packet.topic, payload: packet.payload})
-        } catch (error) {
-          delete self.clients[k]
-        }
-      }
-    }
-  })
-
-  client.on('pubrel', function (packet) {
-    client.pubcomp(packet)
-  })
-
-  client.on('pubrec', function (packet) {
-    client.pubrel(packet)
-  })
-
-  client.on('pubcomp', function () {
-    // Nothing to be done
-  })
-
-  client.on('subscribe', function (packet) {
-    var qos
-    var topic
-    var reg
-    var granted = []
-
-    for (var i = 0; i < packet.subscriptions.length; i++) {
-      qos = packet.subscriptions[i].qos
-      topic = packet.subscriptions[i].topic
-      reg = new RegExp(topic.replace('+', '[^/]+').replace('#', '.+') + '$')
-
-      granted.push(qos)
-      client.subscriptions.push(reg)
-    }
-
-    client.suback({messageId: packet.messageId, granted: granted})
-  })
-
-  client.on('unsubscribe', function (packet) {
-    client.unsuback(packet)
-  })
-
-  client.on('pingreq', function () {
-    client.pingresp()
-  })
-}
-
-function start (startPort, done) {
-  var server = http.createServer()
-  var wss = new WebSocketServer({server: server})
-
-  wss.on('connection', function (ws) {
-    var stream, connection
-
-    if (!(ws.protocol === 'mqtt' ||
-          ws.protocol === 'mqttv3.1')) {
-      return ws.close()
-    }
-
-    stream = websocket(ws)
-    connection = new Connection(stream)
-    handleClient.call(server, connection)
-  })
-  server.listen(startPort, done)
-  server.on('request', function (req, res) {
-    res.statusCode = 404
-    res.end('Not Found')
-  })
-  return server
-}
-
-if (require.main === module) {
-  start(process.env.PORT || process.env.ZUUL_PORT, function (err) {
-    if (err) {
-      console.error(err)
-      return
-    }
-    console.log('tunnelled server started on port', process.env.PORT || process.env.ZUUL_PORT)
-  })
-}

+ 0 - 92
src/utils/mqtt/test/browser/test.js

@@ -1,92 +0,0 @@
-'use strict'
-
-var mqtt = require('../../lib/connect')
-var _URL = require('url')
-var xtend = require('xtend')
-var parsed = _URL.parse(document.URL)
-var isHttps = parsed.protocol === 'https:'
-var port = parsed.port || (isHttps ? 443 : 80)
-var host = parsed.hostname
-var protocol = isHttps ? 'wss' : 'ws'
-
-function clientTests (buildClient) {
-  var client
-
-  beforeEach(function () {
-    client = buildClient()
-    client.on('offline', function () {
-      console.log('client offline')
-    })
-    client.on('connect', function () {
-      console.log('client connect')
-    })
-    client.on('reconnect', function () {
-      console.log('client reconnect')
-    })
-  })
-
-  afterEach(function (done) {
-    client.once('close', function () {
-      done()
-    })
-    client.end()
-  })
-
-  it('should connect', function (done) {
-    client.on('connect', function () {
-      done()
-    })
-  })
-
-  it('should publish and subscribe', function (done) {
-    client.subscribe('hello', function () {
-      done()
-    }).publish('hello', 'world')
-  })
-}
-
-function suiteFactory (configName, opts) {
-  function setVersion (base) {
-    return xtend(base || {}, opts)
-  }
-
-  var suiteName = 'MqttClient(' + configName + '=' + JSON.stringify(opts) + ')'
-  describe(suiteName, function () {
-    this.timeout(10000)
-
-    describe('specifying nothing', function () {
-      clientTests(function () {
-        return mqtt.connect(setVersion())
-      })
-    })
-
-    if (parsed.hostname === 'localhost') {
-      describe('specifying a port', function () {
-        clientTests(function () {
-          return mqtt.connect(setVersion({ protocol: protocol, port: port }))
-        })
-      })
-    }
-
-    describe('specifying a port and host', function () {
-      clientTests(function () {
-        return mqtt.connect(setVersion({ protocol: protocol, port: port, host: host }))
-      })
-    })
-
-    describe('specifying a URL', function () {
-      clientTests(function () {
-        return mqtt.connect(protocol + '://' + host + ':' + port, setVersion())
-      })
-    })
-
-    describe('specifying a URL with a path', function () {
-      clientTests(function () {
-        return mqtt.connect(protocol + '://' + host + ':' + port + '/mqtt', setVersion())
-      })
-    })
-  })
-}
-
-suiteFactory('v3', {protocolId: 'MQIsdp', protocolVersion: 3})
-suiteFactory('default', {})

+ 0 - 93
src/utils/mqtt/test/browser/wx.js

@@ -1,93 +0,0 @@
-'use strict'
-
-var mqtt = require('../../lib/connect')
-var _URL = require('url')
-var xtend = require('xtend')
-var parsed = _URL.parse(document.URL)
-var isHttps = parsed.protocol === 'https:'
-var port = parsed.port || (isHttps ? 443 : 80)
-var host = parsed.hostname
-var protocol = isHttps ? 'wxs' : 'wx'
-require('../helpers/wx')
-
-function clientTests (buildClient) {
-  var client
-
-  beforeEach(function () {
-    client = buildClient()
-    client.on('offline', function () {
-      console.log('client offline')
-    })
-    client.on('connect', function () {
-      console.log('client connect')
-    })
-    client.on('reconnect', function () {
-      console.log('client reconnect')
-    })
-  })
-
-  afterEach(function (done) {
-    client.once('close', function () {
-      done()
-    })
-    client.end()
-  })
-
-  it('should connect', function (done) {
-    client.on('connect', function () {
-      done()
-    })
-  })
-
-  it('should publish and subscribe', function (done) {
-    client.subscribe('hello', function () {
-      done()
-    }).publish('hello', 'world')
-  })
-}
-
-function suiteFactory (configName, opts) {
-  function setVersion (base) {
-    return xtend(base || {}, opts)
-  }
-
-  var suiteName = 'MqttClient(' + configName + '=' + JSON.stringify(opts) + ')'
-  describe(suiteName, function () {
-    this.timeout(10000)
-
-    describe('specifying nothing', function () {
-      clientTests(function () {
-        return mqtt.connect(setVersion())
-      })
-    })
-
-    if (parsed.hostname === 'localhost') {
-      describe('specifying a port', function () {
-        clientTests(function () {
-          return mqtt.connect(setVersion({ protocol: protocol, port: port }))
-        })
-      })
-    }
-
-    describe('specifying a port and host', function () {
-      clientTests(function () {
-        return mqtt.connect(setVersion({ protocol: protocol, port: port, host: host }))
-      })
-    })
-
-    describe('specifying a URL', function () {
-      clientTests(function () {
-        return mqtt.connect(protocol + '://' + host + ':' + port, setVersion())
-      })
-    })
-
-    describe('specifying a URL with a path', function () {
-      clientTests(function () {
-        return mqtt.connect(protocol + '://' + host + ':' + port + '/mqtt', setVersion())
-      })
-    })
-  })
-}
-
-suiteFactory('v3', {protocolId: 'MQIsdp', protocolVersion: 3})
-suiteFactory('default', {})

+ 0 - 544
src/utils/mqtt/test/client.js

@@ -1,544 +0,0 @@
-'use strict'
-
-var mqtt = require('..')
-var should = require('should')
-var fork = require('child_process').fork
-var path = require('path')
-var abstractClientTests = require('./abstract_client')
-var net = require('net')
-var eos = require('end-of-stream')
-var mqttPacket = require('mqtt-packet')
-var Buffer = require('safe-buffer').Buffer
-var Duplex = require('readable-stream').Duplex
-var Connection = require('mqtt-connection')
-var Server = require('./server')
-var port = 9876
-var server
-
-function connOnlyServer () {
-  return new Server(function (client) {
-    client.on('connect', function (packet) {
-      client.connack({returnCode: 0})
-    })
-  })
-}
-
-/**
- * Test server
- */
-function buildServer () {
-  return new Server(function (client) {
-    client.on('connect', function (packet) {
-      if (packet.clientId === 'invalid') {
-        client.connack({returnCode: 2})
-      } else {
-        client.connack({returnCode: 0})
-      }
-    })
-
-    client.on('publish', function (packet) {
-      setImmediate(function () {
-        switch (packet.qos) {
-          case 0:
-            break
-          case 1:
-            client.puback(packet)
-            break
-          case 2:
-            client.pubrec(packet)
-            break
-        }
-      })
-    })
-
-    client.on('pubrel', function (packet) {
-      client.pubcomp(packet)
-    })
-
-    client.on('pubrec', function (packet) {
-      client.pubrel(packet)
-    })
-
-    client.on('pubcomp', function () {
-      // Nothing to be done
-    })
-
-    client.on('subscribe', function (packet) {
-      client.suback({
-        messageId: packet.messageId,
-        granted: packet.subscriptions.map(function (e) {
-          return e.qos
-        })
-      })
-    })
-
-    client.on('unsubscribe', function (packet) {
-      client.unsuback(packet)
-    })
-
-    client.on('pingreq', function () {
-      client.pingresp()
-    })
-  })
-}
-
-server = buildServer().listen(port)
-
-describe('MqttClient', function () {
-  describe('creating', function () {
-    it('should allow instantiation of MqttClient without the \'new\' operator', function (done) {
-      should(function () {
-        var client
-        try {
-          client = mqtt.MqttClient(function () {
-            throw Error('break')
-          }, {})
-          client.end()
-        } catch (err) {
-          if (err.message !== 'break') {
-            throw err
-          }
-          done()
-        }
-      }).not.throw('Object #<Object> has no method \'_setupStream\'')
-    })
-  })
-
-  var config = { protocol: 'mqtt', port: port }
-  abstractClientTests(server, config)
-
-  describe('message ids', function () {
-    it('should increment the message id', function () {
-      var client = mqtt.connect(config)
-      var currentId = client._nextId()
-
-      client._nextId().should.equal(currentId + 1)
-      client.end()
-    })
-
-    it('should return 1 once the internal counter reached limit', function () {
-      var client = mqtt.connect(config)
-      client.nextId = 65535
-
-      client._nextId().should.equal(65535)
-      client._nextId().should.equal(1)
-      client.end()
-    })
-
-    it('should return 65535 for last message id once the internal counter reached limit', function () {
-      var client = mqtt.connect(config)
-      client.nextId = 65535
-
-      client._nextId().should.equal(65535)
-      client.getLastMessageId().should.equal(65535)
-      client._nextId().should.equal(1)
-      client.getLastMessageId().should.equal(1)
-      client.end()
-    })
-
-    it('should not throw an error if packet\'s messageId is not found when receiving a pubrel packet', function (done) {
-      var server2 = new Server(function (c) {
-        c.on('connect', function (packet) {
-          c.connack({returnCode: 0})
-          c.pubrel({ messageId: Math.floor(Math.random() * 9000) + 1000 })
-        })
-      })
-
-      server2.listen(port + 49, function () {
-        var client = mqtt.connect({
-          port: port + 49,
-          host: 'localhost'
-        })
-
-        client.on('packetsend', function (packet) {
-          if (packet.cmd === 'pubcomp') {
-            client.end()
-            server2.close()
-            done()
-          }
-        })
-      })
-    })
-
-    it('should not go overflow if the TCP frame contains a lot of PUBLISH packets', function (done) {
-      var parser = mqttPacket.parser()
-      var count = 0
-      var max = 1000
-      var duplex = new Duplex({
-        read: function (n) {},
-        write: function (chunk, enc, cb) {
-          parser.parse(chunk)
-          cb() // nothing to do
-        }
-      })
-      var client = new mqtt.MqttClient(function () {
-        return duplex
-      }, {})
-
-      client.on('message', function (t, p, packet) {
-        if (++count === max) {
-          done()
-        }
-      })
-
-      parser.on('packet', function (packet) {
-        var packets = []
-
-        if (packet.cmd === 'connect') {
-          duplex.push(mqttPacket.generate({
-            cmd: 'connack',
-            sessionPresent: false,
-            returnCode: 0
-          }))
-
-          for (var i = 0; i < max; i++) {
-            packets.push(mqttPacket.generate({
-              cmd: 'publish',
-              topic: Buffer.from('hello'),
-              payload: Buffer.from('world'),
-              retain: false,
-              dup: false,
-              messageId: i + 1,
-              qos: 1
-            }))
-          }
-
-          duplex.push(Buffer.concat(packets))
-        }
-      })
-    })
-  })
-
-  describe('flushing', function () {
-    it('should attempt to complete pending unsub and send on ping timeout', function (done) {
-      this.timeout(10000)
-      var server3 = connOnlyServer().listen(port + 72)
-      var pubCallbackCalled = false
-      var unsubscribeCallbackCalled = false
-      var client = mqtt.connect({
-        port: port + 72,
-        host: 'localhost',
-        keepalive: 1,
-        connectTimeout: 350,
-        reconnectPeriod: 0
-      })
-      client.once('connect', () => {
-        client.publish('fakeTopic', 'fakeMessage', {qos: 1}, (err, result) => {
-          should.exist(err)
-          pubCallbackCalled = true
-        })
-        client.unsubscribe('fakeTopic', (err, result) => {
-          should.exist(err)
-          unsubscribeCallbackCalled = true
-        })
-        setTimeout(() => {
-          client.end(() => {
-            should.equal(pubCallbackCalled && unsubscribeCallbackCalled, true, 'callbacks not invoked')
-            server3.close()
-            done()
-          })
-        }, 5000)
-      })
-    })
-  })
-
-  describe('reconnecting', function () {
-    it('should attempt to reconnect once server is down', function (done) {
-      this.timeout(15000)
-
-      var innerServer = fork(path.join(__dirname, 'helpers', 'server_process.js'))
-      var client = mqtt.connect({ port: 3000, host: 'localhost', keepalive: 1 })
-
-      client.once('connect', function () {
-        innerServer.kill('SIGINT') // mocks server shutdown
-
-        client.once('close', function () {
-          should.exist(client.reconnectTimer)
-          client.end()
-          done()
-        })
-      })
-    })
-
-    it('should reconnect to multiple host-ports-protocol combinations if servers is passed', function (done) {
-      this.timeout(15000)
-
-      var server2 = buildServer().listen(port + 42)
-
-      server2.on('listening', function () {
-        var client = mqtt.connect({
-          protocol: 'wss',
-          servers: [
-            { port: port + 42, host: 'localhost', protocol: 'ws' },
-            { port: port, host: 'localhost' }
-          ],
-          keepalive: 50
-        })
-        server2.on('client', function (c) {
-          should.equal(client.stream.socket.url, 'ws://localhost:9918/', 'Protocol for first connection should use ws.')
-          c.stream.destroy()
-          server2.close()
-        })
-
-        server.once('client', function () {
-          should.equal(client.stream.socket.url, 'wss://localhost:9876/', 'Protocol for second client should use the default protocol: wss, on port: port + 42.')
-          client.end()
-          done()
-        })
-
-        client.once('connect', function () {
-          client.stream.destroy()
-        })
-      })
-    })
-
-    it('should reconnect if a connack is not received in an interval', function (done) {
-      this.timeout(2000)
-
-      var server2 = net.createServer().listen(port + 43)
-
-      server2.on('connection', function (c) {
-        eos(c, function () {
-          server2.close()
-        })
-      })
-
-      server2.on('listening', function () {
-        var client = mqtt.connect({
-          servers: [
-            { port: port + 43, host: 'localhost_fake' },
-            { port: port, host: 'localhost' }
-          ],
-          connectTimeout: 500
-        })
-
-        server.once('client', function () {
-          client.end()
-          done()
-        })
-
-        client.once('connect', function () {
-          client.stream.destroy()
-        })
-      })
-    })
-
-    it('should not be cleared by the connack timer', function (done) {
-      this.timeout(4000)
-
-      var server2 = net.createServer().listen(port + 44)
-
-      server2.on('connection', function (c) {
-        c.destroy()
-      })
-
-      server2.once('listening', function () {
-        var reconnects = 0
-        var connectTimeout = 1000
-        var reconnectPeriod = 100
-        var expectedReconnects = Math.floor(connectTimeout / reconnectPeriod)
-        var client = mqtt.connect({
-          port: port + 44,
-          host: 'localhost',
-          connectTimeout: connectTimeout,
-          reconnectPeriod: reconnectPeriod
-        })
-
-        client.on('reconnect', function () {
-          reconnects++
-          if (reconnects >= expectedReconnects) {
-            client.end()
-            done()
-          }
-        })
-      })
-    })
-
-    it('should not keep requeueing the first message when offline', function (done) {
-      this.timeout(2500)
-
-      var server2 = buildServer().listen(port + 45)
-      var client = mqtt.connect({
-        port: port + 45,
-        host: 'localhost',
-        connectTimeout: 350,
-        reconnectPeriod: 300
-      })
-
-      server2.on('client', function (c) {
-        client.publish('hello', 'world', { qos: 1 }, function () {
-          c.destroy()
-          server2.close()
-          client.publish('hello', 'world', { qos: 1 })
-        })
-      })
-
-      setTimeout(function () {
-        if (client.queue.length === 0) {
-          client.end(true)
-          done()
-        } else {
-          client.end(true)
-        }
-      }, 2000)
-    })
-
-    it('should not send the same subscribe multiple times on a flaky connection', function (done) {
-      this.timeout(3500)
-
-      var KILL_COUNT = 4
-      var killedConnections = 0
-      var subIds = {}
-      var client = mqtt.connect({
-        port: port + 46,
-        host: 'localhost',
-        connectTimeout: 350,
-        reconnectPeriod: 300
-      })
-
-      var server2 = new Server(function (client) {
-        client.on('error', function () {})
-        client.on('connect', function (packet) {
-          if (packet.clientId === 'invalid') {
-            client.connack({returnCode: 2})
-          } else {
-            client.connack({returnCode: 0})
-          }
-        })
-      }).listen(port + 46)
-
-      server2.on('client', function (c) {
-        client.subscribe('topic', function () {
-          done()
-          client.end()
-          c.destroy()
-          server2.close()
-        })
-
-        c.on('subscribe', function (packet) {
-          if (killedConnections < KILL_COUNT) {
-            // Kill the first few sub attempts to simulate a flaky connection
-            killedConnections++
-            c.destroy()
-          } else {
-            // Keep track of acks
-            if (!subIds[packet.messageId]) {
-              subIds[packet.messageId] = 0
-            }
-            subIds[packet.messageId]++
-            if (subIds[packet.messageId] > 1) {
-              done(new Error('Multiple duplicate acked subscriptions received for messageId ' + packet.messageId))
-              client.end(true)
-              c.destroy()
-              server2.destroy()
-            }
-
-            c.suback({
-              messageId: packet.messageId,
-              granted: packet.subscriptions.map(function (e) {
-                return e.qos
-              })
-            })
-          }
-        })
-      })
-    })
-
-    it('should not fill the queue of subscribes if it cannot connect', function (done) {
-      this.timeout(2500)
-
-      var port2 = port + 48
-
-      var server2 = net.createServer(function (stream) {
-        var client = new Connection(stream)
-
-        client.on('error', function () {})
-        client.on('connect', function (packet) {
-          client.connack({returnCode: 0})
-          client.destroy()
-        })
-      })
-
-      server2.listen(port2, function () {
-        var client = mqtt.connect({
-          port: port2,
-          host: 'localhost',
-          connectTimeout: 350,
-          reconnectPeriod: 300
-        })
-
-        client.subscribe('hello')
-
-        setTimeout(function () {
-          client.queue.length.should.equal(1)
-          client.end()
-          done()
-        }, 1000)
-      })
-    })
-
-    it('should not send the same publish multiple times on a flaky connection', function (done) {
-      this.timeout(3500)
-
-      var KILL_COUNT = 4
-      var killedConnections = 0
-      var pubIds = {}
-      var client = mqtt.connect({
-        port: port + 47,
-        host: 'localhost',
-        connectTimeout: 350,
-        reconnectPeriod: 300
-      })
-
-      var server2 = net.createServer(function (stream) {
-        var client = new Connection(stream)
-        client.on('error', function () {})
-        client.on('connect', function (packet) {
-          if (packet.clientId === 'invalid') {
-            client.connack({returnCode: 2})
-          } else {
-            client.connack({returnCode: 0})
-          }
-        })
-
-        this.emit('client', client)
-      }).listen(port + 47)
-
-      server2.on('client', function (c) {
-        client.publish('topic', 'data', { qos: 1 }, function () {
-          done()
-          client.end()
-          c.destroy()
-          server2.destroy()
-        })
-
-        c.on('publish', function onPublish (packet) {
-          if (killedConnections < KILL_COUNT) {
-            // Kill the first few pub attempts to simulate a flaky connection
-            killedConnections++
-            c.destroy()
-
-            // to avoid receiving inflight messages
-            c.removeListener('publish', onPublish)
-          } else {
-            // Keep track of acks
-            if (!pubIds[packet.messageId]) {
-              pubIds[packet.messageId] = 0
-            }
-
-            pubIds[packet.messageId]++
-
-            if (pubIds[packet.messageId] > 1) {
-              done(new Error('Multiple duplicate acked publishes received for messageId ' + packet.messageId))
-              client.end(true)
-              c.destroy()
-              server2.destroy()
-            }
-
-            c.puback(packet)
-          }
-        })
-      })
-    })
-  })
-})

+ 0 - 16
src/utils/mqtt/test/helpers/private-csr.pem

@@ -1,16 +0,0 @@
------BEGIN CERTIFICATE REQUEST-----
-MIICijCCAXICAQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUx
-ITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcN
-AQEBBQADggEPADCCAQoCggEBANtzIZmqf7h3axO9mzo2VhiF/BF3Y4E/fDTkFy27
-PgssS/ipFOMe/IxyM/hA/o/bQb0BY+sH5s1020kNH79umtabWMaDmOi8bvmHWtVC
-cYhn3mhbRFWcORdTnfQ8uRYXZGeoupjlhfrKkQCoSAFKh1OzU7aNx4CjMAjSa4py
-trMAVNJ37RryhsfMuHAeG8+0Eo3qmYyaplpurtr8A3HWV65R2VFCwZ5hKG8I9X2F
-3UrYKHr4xlxOgjD8j2OfYZxpGHI6YexJ28aR0xlsWfzS+TKKFVxy8ntgPGL0ZXL3
-vss80mAcBl9FfsJzufn4IHOYspX1OEM0M7plMmQw/yNT9B8CAwEAAaAAMA0GCSqG
-SIb3DQEBBQUAA4IBAQBsONiE5HTjfR1pDrWPIhbLqMO3AqmuB5AwpQm8kAaM2Oz1
-DI/a8bHYyODMiyWUPTtwLMQWcJpAG2ZhE18gLqFwXZR1XSOxY1yF+uZ7Ls3hwzbq
-9A6O254B5wXBnXkVbzZwFshV5HWiZwVivF5GDyLRsMoS2EtUHoDEP4YIRK0kPL9H
-m3BB334KlWTc8NNXFFG62OL7q2fa8xRHlN8SYfeUjy79eEoBdHv5wL/ZN/YBCDNJ
-2zrYUvbOmfoq1e+6AczZ6xAHHeneUQuaOF225aMwHHZTiP2TlIeFXwBvzV1BWIJv
-dOaHX/f3NamKoGvwYyIR1FrI2FpXTJLRE/eu7TFD
------END CERTIFICATE REQUEST-----

+ 0 - 27
src/utils/mqtt/test/helpers/private-key.pem

@@ -1,27 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIIEpAIBAAKCAQEA23Mhmap/uHdrE72bOjZWGIX8EXdjgT98NOQXLbs+CyxL+KkU
-4x78jHIz+ED+j9tBvQFj6wfmzXTbSQ0fv26a1ptYxoOY6Lxu+Yda1UJxiGfeaFtE
-VZw5F1Od9Dy5FhdkZ6i6mOWF+sqRAKhIAUqHU7NTto3HgKMwCNJrinK2swBU0nft
-GvKGx8y4cB4bz7QSjeqZjJqmWm6u2vwDcdZXrlHZUULBnmEobwj1fYXdStgoevjG
-XE6CMPyPY59hnGkYcjph7EnbxpHTGWxZ/NL5MooVXHLye2A8YvRlcve+yzzSYBwG
-X0V+wnO5+fggc5iylfU4QzQzumUyZDD/I1P0HwIDAQABAoIBAQDNgNdqS5wnZs1D
-Qz/mF5QwiugugxsPoh/yd9as4LeNRwIt7ki9F/twmlHInTTGCpFZKcAkDNY6eMAR
-fNTKNA2UAw3zeLDs4ekai4KoSvx+vKYuG6m2cgGUsp0sZuD8qxM/b2auX+JDpQZ9
-Exm6+8wWucwfHE5DTI5i9In4sMweeuiEUYnndTzElkvnP/44h1fGSU1iGUKn/ftc
-P4X+3SU68KMT3kUsEBavtmSdyeG/lSFEjm73FwVIRZ+PfbQX2hDD+mmseAXGFKi1
-HudtQkEzTvYR+QAgvtjNgt/0qxFtPdj7Y+iRkCZQSJToAw8z6vwUn1qNCADauGMI
-X6KIm8XBAoGBAPiwMLYpIqp1rksINbqpbVqjtqsoejQuPYeEF7OXHbH9il7pWrQF
-wLbogo3YXX+a66RreVMhsUeq7+pIf/sK2lT73gDpFfvZnJG1ww94QkHBEPso0bN9
-pcGgceIK7KRRAiAl5Mjw6pZZNnIBxlIFaSbBqQau74NfdaalMBF2wi+3AoGBAOHm
-3ttFtVjVlb2fHoiGNZCZDv3gnsQXZlCxS+rQ4XEmEWKHAH4T3+Kzmo8jWoX+DGGD
-6UkxWHv7e+KrYIZDi7Dd2HFV0gHN6d1SNdPix3vN114bNOrbfqxuEVT5PdFHSuel
-5d3ix+3U+tpHamwb88eyeq6Q3t5Lcl3gIRGLzo7ZAoGBAKVuLzk+K/1Qw1zOXU+K
-nWAKP92j04caq3uWd13UTMC2dHGmsdvHZ+dEzHQnVisol1CM3exbIV8XavliuR/6
-nDqkQY5Bf4pFvE2Bp/yGdyzejblF8hmAn98qKBfCRKEZ8lwIWSUCfkr9laZJX+/4
-AXbypMn5XQL7YXw1rsAvTAYJAoGAV4ZL8kkf6jtWuRFdkyfsuQmUdWkCGpe2XK1U
-7LXhoyVMtw/3cOHibMOJrsvT1vaHdYDWcjVcQy084qXj0CF7jhtmMQM/StOtOMMR
-d/b1s1Idj6ia6CQDAGvk6zdmbB9jNj1gwoeLTuqmBsyEvz5VRZoxTlFzCE3TEew0
-48d3UIECgYBMxnLByVQA3pQWWIZZyqt+HgJAphYPdpnPalblQAbuCksKTZ/QKDkW
-dzih1PQROVrYrX7VwJ3/I8gXIuvKVtN1NKOS3a0JtbJQhpH4YbRwyQskXWYP8oYa
-MjBGPymNDhZh0zoGWzst5uR3NpdNV+7yNYPvyxzVNjlPjtAUqIxjBg==
------END RSA PRIVATE KEY-----

+ 0 - 19
src/utils/mqtt/test/helpers/public-cert.pem

@@ -1,19 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIDBjCCAe4CCQDkrq1PMPtmfzANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB
-VTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0
-cyBQdHkgTHRkMB4XDTEzMDEyNTEwMzEyOVoXDTEzMDIyNDEwMzEyOVowRTELMAkG
-A1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0
-IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
-ANtzIZmqf7h3axO9mzo2VhiF/BF3Y4E/fDTkFy27PgssS/ipFOMe/IxyM/hA/o/b
-Qb0BY+sH5s1020kNH79umtabWMaDmOi8bvmHWtVCcYhn3mhbRFWcORdTnfQ8uRYX
-ZGeoupjlhfrKkQCoSAFKh1OzU7aNx4CjMAjSa4pytrMAVNJ37RryhsfMuHAeG8+0
-Eo3qmYyaplpurtr8A3HWV65R2VFCwZ5hKG8I9X2F3UrYKHr4xlxOgjD8j2OfYZxp
-GHI6YexJ28aR0xlsWfzS+TKKFVxy8ntgPGL0ZXL3vss80mAcBl9FfsJzufn4IHOY
-spX1OEM0M7plMmQw/yNT9B8CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAeHAwoKYl
-6g9lUEwBDqm6ZxjgoYQi6V3loCjBcTr5OrMkLvvZrA55xsse0NRH40I/pvCaAZAZ
-EEna0fr5GPYi+y+I8EoU2W/+ehSqRAU8Fkdm0eR5MjyLWYOwd3ClUND8EpUNNSKH
-Xw9k9EQmyKsDxVsKWoJoO9rfFkUjooz07jGPCud18QCBs5i5ThbnQ9UP+26D8z5k
-1Dii69LIcLXA3Vtm6R5fT57zNusfx8bqA9yy7UThYaXIazNMWNxiJRXfv0J4zFdD
-RQ+SFdJ3p5jurPkc3oRWWPbn/Lpf0E5XlYTJImXT1WmWnQSaNtME4P+3kEL5x+v/
-u8zTLbobG4x0rQ==
------END CERTIFICATE-----

+ 0 - 9
src/utils/mqtt/test/helpers/public-key.pem

@@ -1,9 +0,0 @@
------BEGIN PUBLIC KEY-----
-MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA23Mhmap/uHdrE72bOjZW
-GIX8EXdjgT98NOQXLbs+CyxL+KkU4x78jHIz+ED+j9tBvQFj6wfmzXTbSQ0fv26a
-1ptYxoOY6Lxu+Yda1UJxiGfeaFtEVZw5F1Od9Dy5FhdkZ6i6mOWF+sqRAKhIAUqH
-U7NTto3HgKMwCNJrinK2swBU0nftGvKGx8y4cB4bz7QSjeqZjJqmWm6u2vwDcdZX
-rlHZUULBnmEobwj1fYXdStgoevjGXE6CMPyPY59hnGkYcjph7EnbxpHTGWxZ/NL5
-MooVXHLye2A8YvRlcve+yzzSYBwGX0V+wnO5+fggc5iylfU4QzQzumUyZDD/I1P0
-HwIDAQAB
------END PUBLIC KEY-----

+ 0 - 52
src/utils/mqtt/test/helpers/server.js

@@ -1,52 +0,0 @@
-'use strict'
-
-var Server = require('../server')
-var fs = require('fs')
-
-module.exports.init_server = function (PORT) {
-  var server = new Server(function (client) {
-    client.on('connect', function () {
-      client.connack(0)
-    })
-
-    client.on('publish', function (packet) {
-      switch (packet.qos) {
-        case 1:
-          client.puback({messageId: packet.messageId})
-          break
-        case 2:
-          client.pubrec({messageId: packet.messageId})
-          break
-        default:
-          break
-      }
-    })
-
-    client.on('pubrel', function (packet) {
-      client.pubcomp({messageId: packet.messageId})
-    })
-
-    client.on('pingreq', function () {
-      client.pingresp()
-    })
-
-    client.on('disconnect', function () {
-      client.stream.end()
-    })
-  })
-  server.listen(PORT)
-  return server
-}
-
-module.exports.init_secure_server = function (port, key, cert) {
-  var server = new Server.SecureServer({
-    key: fs.readFileSync(key),
-    cert: fs.readFileSync(cert)
-  }, function (client) {
-    client.on('connect', function () {
-      client.connack({returnCode: 0})
-    })
-  })
-  server.listen(port)
-  return server
-}

+ 0 - 9
src/utils/mqtt/test/helpers/server_process.js

@@ -1,9 +0,0 @@
-'use strict'
-
-var Server = require('../server')
-
-new Server(function (client) {
-  client.on('connect', function () {
-    client.connack({ returnCode: 0 })
-  })
-}).listen(3000, 'localhost')

+ 0 - 14
src/utils/mqtt/test/helpers/tls-cert.pem

@@ -1,14 +0,0 @@
------BEGIN CERTIFICATE-----
-MIICKTCCAZICCQDRSYqWgZyJmjANBgkqhkiG9w0BAQUFADBZMQswCQYDVQQGEwJB
-VTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0
-cyBQdHkgTHRkMRIwEAYDVQQDEwlsb2NhbGhvc3QwHhcNMTQwNjEzMTAwMzAzWhcN
-MjQwNjEwMTAwMzAzWjBZMQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0
-ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMRIwEAYDVQQDEwls
-b2NhbGhvc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMzFv8+9EBb1sG07
-TjdtbRksRwF7/CZsOWe+ef4ZYPolC5lzvNVYXsBIjL+ilhyKopBbwnOuX9+6FmYO
-G/N1lDZRssolGoOVM+1ma3Whmxz8C1g+xi95nP2OqtwP5Du6xhvOM265CiMaf8DH
-n63ZFxyi3d1CdNGamNQvrybCzJn7AgMBAAEwDQYJKoZIhvcNAQEFBQADgYEABmyp
-3wyBGjb2zSHK5pF9c9GXyHRL4/FkP6qzU5NWrfVAowdOczctJbc3hxPh34Encbr6
-KijYnbdP7/f8aZrStLGqgFYL3SHZY3zvgLTzOmGr9reHUkubHtN+mWHeYy1wVe3D
-qEOI8ygT4olVZmWAD+VLKgAb0J07rA/PKf82fBI=
------END CERTIFICATE-----

+ 0 - 11
src/utils/mqtt/test/helpers/tls-csr.pem

@@ -1,11 +0,0 @@
------BEGIN CERTIFICATE REQUEST-----
-MIIBmTCCAQICAQAwWTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUx
-ITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDESMBAGA1UEAxMJbG9j
-YWxob3N0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMxb/PvRAW9bBtO043
-bW0ZLEcBe/wmbDlnvnn+GWD6JQuZc7zVWF7ASIy/opYciqKQW8Jzrl/fuhZmDhvz
-dZQ2UbLKJRqDlTPtZmt1oZsc/AtYPsYveZz9jqrcD+Q7usYbzjNuuQojGn/Ax5+t
-2Rccot3dQnTRmpjUL68mwsyZ+wIDAQABoAAwDQYJKoZIhvcNAQEFBQADgYEALjPb
-zOEL8ahD+UFxwVCXTq4MsKwMlyZCcEVY0CksAgWpCkWr54JUp832p3nEylPRj/gx
-8fKWzz5DiO3RER8fzmkb+Kwa+JvXVHmTFzemxYGnxS/HRlF0ZoeAIgvq6ouIrqm9
-1P9gsuYmA5vtfc6Y/NVlSrcSYFH4ADF5DcRTi2Q=
------END CERTIFICATE REQUEST-----

+ 0 - 15
src/utils/mqtt/test/helpers/tls-key.pem

@@ -1,15 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIICWwIBAAKBgQDMxb/PvRAW9bBtO043bW0ZLEcBe/wmbDlnvnn+GWD6JQuZc7zV
-WF7ASIy/opYciqKQW8Jzrl/fuhZmDhvzdZQ2UbLKJRqDlTPtZmt1oZsc/AtYPsYv
-eZz9jqrcD+Q7usYbzjNuuQojGn/Ax5+t2Rccot3dQnTRmpjUL68mwsyZ+wIDAQAB
-AoGARg7p/xL6LEDGqbh+nCwOBWzGplVbAXJJeZsLdcoNCcge3dNhKcTgNf0cWnwv
-y3gLAkTClH12Q78Q5r2xBmyV1hqyEb9lrIqAlSS5GjnTWWhyzspcjKZWR5PAjOYo
-LlxNpCegWEjOUpD4Lwf9yjEu+xrDGVmsLF0PPRkAM32qh9ECQQD1vzyFr/hSn7Rh
-6IFFbLAVkIvsy+1Ca7tF6/7byHCdwqS5oUKaY+9DAr0TE+br87N2IzUCU5X7Cv74
-m+YiqhBlAkEA1VDfpq8puyIq2F6Ftx0xpYMv6XKhuRyAziT/DzIBdFVeOMIgUuk0
-7E4W0N/gDmUmEQFl3HYzUfdZrTUKzjzq3wJAZflsKOGDfu2skXBErEVUsC4iEinx
-Ez3XIUWzpQoAyUYqyqjDFYPglgL96Hu6uDCRSLWFWqjKtLi0Yv92OO4vDQJASuAk
-YQHDCCiqGWC0Vt4sewhdXPgbxDo5DCL4VIEc+ZStiga6CeBJ71hJse+jWeovPnDb
-LFNhGDhWhfHEZTgEyQJAXNuypDS5l73LPvc+yduPZiNEtwae9KbWaZUwC683a81s
-mkT7uroNYyK9ptZrz/LMJJotkqCjigXaA3kuzuNUCQ==
------END RSA PRIVATE KEY-----

+ 0 - 13
src/utils/mqtt/test/helpers/wrong-cert.pem

@@ -1,13 +0,0 @@
------BEGIN CERTIFICATE-----
-MIICATCCAWoCCQDEVSSDKkcTdjANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB
-VTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0
-cyBQdHkgTHRkMB4XDTE0MDUxMTE2MzMxMVoXDTE0MDYxMDE2MzMxMVowRTELMAkG
-A1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0
-IFdpZGdpdHMgUHR5IEx0ZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAyDMI
-VS2XSizZT8KeFYFQfKt7CcT5/Pkzw2BDJoMVLmrkfHdddjsTgswqHfzhO8Fmfg6B
-MxgsEz2aKi24hJxQFuQ1DGhyfKHnjxM5PqSLiOkQDKllnAOgqOBDXpca0jXypCk1
-IVhMspM2ylrnBXps3nTBLJxFBkZSBov/JDkkL+cCAwEAATANBgkqhkiG9w0BAQUF
-AAOBgQA8k93U0VDIpQ8lpScxrCtEu5jLZgB1fw0fdCUtDHaaM1v+LWr1xfCmFKyT
-kUMcJl4e1pkcSNfXcI7LdNt8EJqMabOi2UpW1+VZJn206D0f3XmNSmZbk8oozGrl
-qg2wSTZYlZClCTpWO2Y+iYzojY8kmLaQ2xbTxBz1XlshC8HvsA==
------END CERTIFICATE-----

+ 0 - 11
src/utils/mqtt/test/helpers/wrong-csr.pem

@@ -1,11 +0,0 @@
------BEGIN CERTIFICATE REQUEST-----
-MIIBhDCB7gIBADBFMQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEh
-MB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIGfMA0GCSqGSIb3DQEB
-AQUAA4GNADCBiQKBgQDIMwhVLZdKLNlPwp4VgVB8q3sJxPn8+TPDYEMmgxUuauR8
-d112OxOCzCod/OE7wWZ+DoEzGCwTPZoqLbiEnFAW5DUMaHJ8oeePEzk+pIuI6RAM
-qWWcA6Co4ENelxrSNfKkKTUhWEyykzbKWucFemzedMEsnEUGRlIGi/8kOSQv5wID
-AQABoAAwDQYJKoZIhvcNAQEFBQADgYEAFXqd8jhW+2hRvkRB1CCVBK5e6AQHq1rF
-s3B36O64hRHIr1KC+dWr8vv1t9Rkud+7E3ELHtxWCORIYpqQ2Ddldt4PP+MTNj2C
-qgwOpxM0VDxeeWml8fqx2uzfPhVduyHGm0yff2JS2KRVmnIPLTUuz/+udukIFDVO
-Sc4/W3qY7f8=
------END CERTIFICATE REQUEST-----

+ 0 - 15
src/utils/mqtt/test/helpers/wrong-key.pem

@@ -1,15 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIICXQIBAAKBgQDIMwhVLZdKLNlPwp4VgVB8q3sJxPn8+TPDYEMmgxUuauR8d112
-OxOCzCod/OE7wWZ+DoEzGCwTPZoqLbiEnFAW5DUMaHJ8oeePEzk+pIuI6RAMqWWc
-A6Co4ENelxrSNfKkKTUhWEyykzbKWucFemzedMEsnEUGRlIGi/8kOSQv5wIDAQAB
-AoGBALOzszgaG2I2jb4dmJ7/G4s8tc2YJTlhS4iFgOEx6rJmur/KuXcmIiZXMzsF
-wftMZ76hMHH3saB3vEk+DxHh6bR6cW/I82Vxts9suz2fRnd2mh5JHI+opXE53LVn
-hJcQ4k6LJ9MNVxlHwCTrSuJvtikDOOrCARHRvYzFRL4wXvmpAkEA+DFzXGDg8PxX
-RFp6RLLbqaUT6YXNi+E5ERuumru+rgRj+OF/dxNK3d1lcIJZjqVMDAgOsZ66/bkh
-GfCzJPREUwJBAM5/HeHmTEM5K5B0X8b6XEHTgWFUNTu4K36Ee5ySd8RYI8zjQ9wS
-NM1nXnx12npL7DSkShz9xgnTe0f8YmQnc50CQQCgdE/RXCxwf6LnZNsBCOSsIzXh
-VgiRsxSSs+PI0zGuDNaY8yfV0ponH1fSSeMeLk0gxiDBwg2/tGzq+UrHzEdTAkB1
-/U5O0K+MzbLlxIkhgdaLSlYoDdyo9e/sR7j12v8SMqaqIMWajtCa+VCU3yZqMM2T
-urgaXqr03GEZ3c0+mwhFAkAwWkczV1iwuedmWLKc36iQhoj+FRMUoxWe/fBixQls
-g0lDvwWiZ3M6hjCsBRckmt8eU2mUh79Odrj5fRWIwXaX
------END RSA PRIVATE KEY-----

+ 0 - 4
src/utils/mqtt/test/mocha.opts

@@ -1,4 +0,0 @@
---check-leaks
---timeout 5000
---exit
-

+ 0 - 230
src/utils/mqtt/test/mqtt.js

@@ -1,230 +0,0 @@
-'use strict'
-
-var fs = require('fs')
-var path = require('path')
-var mqtt = require('../')
-
-describe('mqtt', function () {
-  describe('#connect', function () {
-    var sslOpts, sslOpts2
-    it('should return an MqttClient when connect is called with mqtt:/ url', function () {
-      var c = mqtt.connect('mqtt://localhost:1883')
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.end()
-    })
-
-    it('should throw an error when called with no protocol specified', function () {
-      (function () {
-        var c = mqtt.connect('foo.bar.com')
-        c.end()
-      }).should.throw('Missing protocol')
-    })
-
-    it('should throw an error when called with no protocol specified - with options', function () {
-      (function () {
-        var c = mqtt.connect('tcp://foo.bar.com', { protocol: null })
-        c.end()
-      }).should.throw('Missing protocol')
-    })
-
-    it('should return an MqttClient with username option set', function () {
-      var c = mqtt.connect('mqtt://user:pass@localhost:1883')
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.options.should.have.property('username', 'user')
-      c.options.should.have.property('password', 'pass')
-      c.end()
-    })
-
-    it('should return an MqttClient with username and password options set', function () {
-      var c = mqtt.connect('mqtt://user@localhost:1883')
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.options.should.have.property('username', 'user')
-      c.end()
-    })
-
-    it('should return an MqttClient with the clientid with random value', function () {
-      var c = mqtt.connect('mqtt://user@localhost:1883')
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.options.should.have.property('clientId')
-      c.end()
-    })
-
-    it('should return an MqttClient with the clientid with empty string', function () {
-      var c = mqtt.connect('mqtt://user@localhost:1883?clientId=')
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.options.should.have.property('clientId', '')
-      c.end()
-    })
-
-    it('should return an MqttClient with the clientid option set', function () {
-      var c = mqtt.connect('mqtt://user@localhost:1883?clientId=123')
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.options.should.have.property('clientId', '123')
-      c.end()
-    })
-
-    it('should return an MqttClient when connect is called with tcp:/ url', function () {
-      var c = mqtt.connect('tcp://localhost')
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.end()
-    })
-
-    it('should return an MqttClient with correct host when called with a host and port', function () {
-      var c = mqtt.connect('tcp://user:pass@localhost:1883')
-
-      c.options.should.have.property('hostname', 'localhost')
-      c.options.should.have.property('port', 1883)
-      c.end()
-    })
-
-    sslOpts = {
-      keyPath: path.join(__dirname, 'helpers', 'private-key.pem'),
-      certPath: path.join(__dirname, 'helpers', 'public-cert.pem'),
-      caPaths: [path.join(__dirname, 'helpers', 'public-cert.pem')]
-    }
-
-    it('should return an MqttClient when connect is called with mqtts:/ url', function () {
-      var c = mqtt.connect('mqtts://localhost', sslOpts)
-
-      c.options.should.have.property('protocol', 'mqtts')
-
-      c.on('error', function () {})
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.end()
-    })
-
-    it('should return an MqttClient when connect is called with ssl:/ url', function () {
-      var c = mqtt.connect('ssl://localhost', sslOpts)
-
-      c.options.should.have.property('protocol', 'ssl')
-
-      c.on('error', function () {})
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.end()
-    })
-
-    it('should return an MqttClient when connect is called with ws:/ url', function () {
-      var c = mqtt.connect('ws://localhost', sslOpts)
-
-      c.options.should.have.property('protocol', 'ws')
-
-      c.on('error', function () {})
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.end()
-    })
-
-    it('should return an MqttClient when connect is called with wss:/ url', function () {
-      var c = mqtt.connect('wss://localhost', sslOpts)
-
-      c.options.should.have.property('protocol', 'wss')
-
-      c.on('error', function () {})
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.end()
-    })
-
-    sslOpts2 = {
-      key: fs.readFileSync(path.join(__dirname, 'helpers', 'private-key.pem')),
-      cert: fs.readFileSync(path.join(__dirname, 'helpers', 'public-cert.pem')),
-      ca: [fs.readFileSync(path.join(__dirname, 'helpers', 'public-cert.pem'))]
-    }
-
-    it('should throw an error when it is called with cert and key set but no protocol specified', function () {
-      // to do rewrite wrap function
-      (function () {
-        var c = mqtt.connect(sslOpts2)
-        c.end()
-      }).should.throw('Missing secure protocol key')
-    })
-
-    it('should throw an error when it is called with cert and key set and protocol other than allowed: mqtt,mqtts,ws,wss,wxs', function () {
-      (function () {
-        sslOpts2.protocol = 'UNKNOWNPROTOCOL'
-        var c = mqtt.connect(sslOpts2)
-        c.end()
-      }).should.throw()
-    })
-
-    it('should return a MqttClient with mqtts set when connect is called key and cert set and protocol mqtt', function () {
-      sslOpts2.protocol = 'mqtt'
-      var c = mqtt.connect(sslOpts2)
-
-      c.options.should.have.property('protocol', 'mqtts')
-
-      c.on('error', function () {})
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-    })
-
-    it('should return a MqttClient with mqtts set when connect is called key and cert set and protocol mqtts', function () {
-      sslOpts2.protocol = 'mqtts'
-      var c = mqtt.connect(sslOpts2)
-
-      c.options.should.have.property('protocol', 'mqtts')
-
-      c.on('error', function () {})
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-    })
-
-    it('should return a MqttClient with wss set when connect is called key and cert set and protocol ws', function () {
-      sslOpts2.protocol = 'ws'
-      var c = mqtt.connect(sslOpts2)
-
-      c.options.should.have.property('protocol', 'wss')
-
-      c.on('error', function () {})
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-    })
-
-    it('should return a MqttClient with wss set when connect is called key and cert set and protocol wss', function () {
-      sslOpts2.protocol = 'wss'
-      var c = mqtt.connect(sslOpts2)
-
-      c.options.should.have.property('protocol', 'wss')
-
-      c.on('error', function () {})
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-    })
-
-    it('should return an MqttClient with the clientid with option of clientId as empty string', function () {
-      var c = mqtt.connect('mqtt://localhost:1883', {
-        clientId: ''
-      })
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.options.should.have.property('clientId', '')
-    })
-
-    it('should return an MqttClient with the clientid with option of clientId empty', function () {
-      var c = mqtt.connect('mqtt://localhost:1883')
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.options.should.have.property('clientId')
-      c.end()
-    })
-
-    it('should return an MqttClient with the clientid with option of with specific clientId', function () {
-      var c = mqtt.connect('mqtt://localhost:1883', {
-        clientId: '123'
-      })
-
-      c.should.be.instanceOf(mqtt.MqttClient)
-      c.options.should.have.property('clientId', '123')
-      c.end()
-    })
-  })
-})

+ 0 - 9
src/utils/mqtt/test/mqtt_store.js

@@ -1,9 +0,0 @@
-'use strict'
-
-var mqtt = require('../lib/connect')
-
-describe('store in lib/connect/index.js (webpack entry point)', function () {
-  it('should create store', function (done) {
-    done(null, new mqtt.Store())
-  })
-})

+ 0 - 157
src/utils/mqtt/test/secure_client.js

@@ -1,157 +0,0 @@
-'use strict'
-
-var mqtt = require('..')
-var path = require('path')
-var abstractClientTests = require('./abstract_client')
-var fs = require('fs')
-var port = 9899
-var KEY = path.join(__dirname, 'helpers', 'tls-key.pem')
-var CERT = path.join(__dirname, 'helpers', 'tls-cert.pem')
-var WRONG_CERT = path.join(__dirname, 'helpers', 'wrong-cert.pem')
-var Server = require('./server')
-
-var server = new Server.SecureServer({
-  key: fs.readFileSync(KEY),
-  cert: fs.readFileSync(CERT)
-}, function (client) {
-  client.on('connect', function (packet) {
-    if (packet.clientId === 'invalid') {
-      client.connack({returnCode: 2})
-    } else {
-      server.emit('connect', client)
-      client.connack({returnCode: 0})
-    }
-  })
-
-  client.on('publish', function (packet) {
-    setImmediate(function () {
-      /* jshint -W027 */
-      /* eslint default-case:0 */
-      switch (packet.qos) {
-        case 0:
-          break
-        case 1:
-          client.puback(packet)
-          break
-        case 2:
-          client.pubrec(packet)
-          break
-      }
-      /* jshint +W027 */
-    })
-  })
-
-  client.on('pubrel', function (packet) {
-    client.pubcomp(packet)
-  })
-
-  client.on('pubrec', function (packet) {
-    client.pubrel(packet)
-  })
-
-  client.on('pubcomp', function () {
-    // Nothing to be done
-  })
-
-  client.on('subscribe', function (packet) {
-    client.suback({
-      messageId: packet.messageId,
-      granted: packet.subscriptions.map(function (e) {
-        return e.qos
-      })
-    })
-  })
-
-  client.on('unsubscribe', function (packet) {
-    client.unsuback(packet)
-  })
-
-  client.on('pingreq', function () {
-    client.pingresp()
-  })
-}).listen(port)
-
-describe('MqttSecureClient', function () {
-  var config = { protocol: 'mqtts', port: port, rejectUnauthorized: false }
-  abstractClientTests(server, config)
-
-  describe('with secure parameters', function () {
-    it('should validate successfully the CA', function (done) {
-      var client = mqtt.connect({
-        protocol: 'mqtts',
-        port: port,
-        ca: [fs.readFileSync(CERT)],
-        rejectUnauthorized: true
-      })
-
-      client.on('error', function (err) {
-        done(err)
-      })
-
-      server.once('connect', function () {
-        done()
-      })
-    })
-
-    it('should validate successfully the CA using URI', function (done) {
-      var client = mqtt.connect('mqtts://localhost:' + port, {
-        ca: [fs.readFileSync(CERT)],
-        rejectUnauthorized: true
-      })
-
-      client.on('error', function (err) {
-        done(err)
-      })
-
-      server.once('connect', function () {
-        done()
-      })
-    })
-
-    it('should validate successfully the CA using URI with path', function (done) {
-      var client = mqtt.connect('mqtts://localhost:' + port + '/', {
-        ca: [fs.readFileSync(CERT)],
-        rejectUnauthorized: true
-      })
-
-      client.on('error', function (err) {
-        done(err)
-      })
-
-      server.once('connect', function () {
-        done()
-      })
-    })
-
-    it('should validate unsuccessfully the CA', function (done) {
-      var client = mqtt.connect({
-        protocol: 'mqtts',
-        port: port,
-        ca: [fs.readFileSync(WRONG_CERT)],
-        rejectUnauthorized: true
-      })
-
-      client.once('error', function () {
-        done()
-        client.end()
-        client.on('error', function () {})
-      })
-    })
-
-    it('should emit close on TLS error', function (done) {
-      var client = mqtt.connect({
-        protocol: 'mqtts',
-        port: port,
-        ca: [fs.readFileSync(WRONG_CERT)],
-        rejectUnauthorized: true
-      })
-
-      client.on('error', function () {})
-
-      // TODO node v0.8.x emits multiple close events
-      client.once('close', function () {
-        done()
-      })
-    })
-  })
-})

+ 0 - 65
src/utils/mqtt/test/server.js

@@ -1,65 +0,0 @@
-'use strict'
-
-var net = require('net')
-var tls = require('tls')
-var inherits = require('inherits')
-var Connection = require('mqtt-connection')
-var MqttServer
-var MqttSecureServer
-
-function setupConnection (duplex) {
-  var connection = new Connection(duplex)
-  this.emit('client', connection)
-}
-
-/*
- * MqttServer
- *
- * @param {Function} listener - fired on client connection
- */
-MqttServer = module.exports = function Server (listener) {
-  if (!(this instanceof Server)) {
-    return new Server(listener)
-  }
-
-  net.Server.call(this)
-
-  this.on('connection', setupConnection)
-
-  if (listener) {
-    this.on('client', listener)
-  }
-
-  return this
-}
-inherits(MqttServer, net.Server)
-
-/**
- * MqttSecureServer
- *
- * @param {Object} opts - server options
- * @param {Function} listener
- */
-MqttSecureServer = module.exports.SecureServer =
-  function SecureServer (opts, listener) {
-    if (!(this instanceof SecureServer)) {
-      return new SecureServer(opts, listener)
-    }
-
-    // new MqttSecureServer(function(){})
-    if (typeof opts === 'function') {
-      listener = opts
-      opts = {}
-    }
-
-    tls.Server.call(this, opts)
-
-    if (listener) {
-      this.on('client', listener)
-    }
-
-    this.on('secureConnection', setupConnection)
-
-    return this
-  }
-inherits(MqttSecureServer, tls.Server)

+ 0 - 10
src/utils/mqtt/test/store.js

@@ -1,10 +0,0 @@
-'use strict'
-
-var Store = require('../lib/store')
-var abstractTest = require('../test/abstract_store')
-
-describe('in-memory store', function () {
-  abstractTest(function (done) {
-    done(null, new Store())
-  })
-})

+ 0 - 22
src/utils/mqtt/test/typescript/broker-connect-subscribe-and-publish.ts

@@ -1,22 +0,0 @@
-// relative path uses package.json {"types":"types/index.d.ts", ...}
-import {IClientOptions, Client, connect, IConnackPacket} from '../..'
-const BROKER = 'test.mosquitto.org'
-
-const PAYLOAD = 'hello from TS'
-const TOPIC = 'typescript-test-' + Math.random().toString(16).substr(2)
-const opts: IClientOptions = {}
-
-console.log(`connect(${JSON.stringify(BROKER)})`)
-const client:Client = connect(`mqtt://${BROKER}`, opts)
-
-client.subscribe({[TOPIC]: 2}, (err, granted) => {
-    granted.forEach(({topic, qos}) => {
-        console.log(`subscribed to ${topic} with qos=${qos}`)
-    })
-    client.publish(TOPIC, PAYLOAD, {qos: 2})
-}).on('message', (topic: string, payload: Buffer) => {
-    console.log(`message from ${topic}: ${payload}`)
-    client.end()
-}).on('connect', (packet: IConnackPacket) => {
-    console.log('connected!', JSON.stringify(packet))
-})

+ 0 - 14
src/utils/mqtt/test/typescript/tsconfig.json

@@ -1,14 +0,0 @@
-{
-  "compilerOptions": {
-    "module": "commonjs",
-    "target": "es5",
-    "moduleResolution": "node",
-    "noEmitOnError": true,
-    "noImplicitAny": true,
-    "alwaysStrict": true,
-    "strictNullChecks": true,
-    "noImplicitReturns": true,
-    "noImplicitThis": true,
-    "sourceMap": true
-  }
-}

+ 0 - 13
src/utils/mqtt/test/util.js

@@ -1,13 +0,0 @@
-'use strict'
-
-var through = require('through2')
-
-module.exports.testStream = function () {
-  return through(function (buf, enc, cb) {
-    var that = this
-    setImmediate(function () {
-      that.push(buf)
-      cb()
-    })
-  })
-}

+ 0 - 144
src/utils/mqtt/test/websocket_client.js

@@ -1,144 +0,0 @@
-'use strict'
-
-var http = require('http')
-var websocket = require('websocket-stream')
-var WebSocketServer = require('ws').Server
-var Connection = require('mqtt-connection')
-var abstractClientTests = require('./abstract_client')
-var mqtt = require('../')
-var xtend = require('xtend')
-var assert = require('assert')
-var port = 9999
-var server = http.createServer()
-
-function attachWebsocketServer (wsServer) {
-  var wss = new WebSocketServer({server: wsServer, perMessageDeflate: false})
-
-  wss.on('connection', function (ws) {
-    var stream = websocket(ws)
-    var connection = new Connection(stream)
-
-    wsServer.emit('client', connection)
-    stream.on('error', function () {})
-    connection.on('error', function () {})
-  })
-
-  return wsServer
-}
-
-attachWebsocketServer(server)
-
-server.on('client', function (client) {
-  client.on('connect', function (packet) {
-    if (packet.clientId === 'invalid') {
-      client.connack({ returnCode: 2 })
-    } else {
-      server.emit('connect', client)
-      client.connack({returnCode: 0})
-    }
-  })
-
-  client.on('publish', function (packet) {
-    setImmediate(function () {
-      switch (packet.qos) {
-        case 0:
-          break
-        case 1:
-          client.puback(packet)
-          break
-        case 2:
-          client.pubrec(packet)
-          break
-      }
-    })
-  })
-
-  client.on('pubrel', function (packet) {
-    client.pubcomp(packet)
-  })
-
-  client.on('pubrec', function (packet) {
-    client.pubrel(packet)
-  })
-
-  client.on('pubcomp', function () {
-    // Nothing to be done
-  })
-
-  client.on('subscribe', function (packet) {
-    client.suback({
-      messageId: packet.messageId,
-      granted: packet.subscriptions.map(function (e) {
-        return e.qos
-      })
-    })
-  })
-
-  client.on('unsubscribe', function (packet) {
-    client.unsuback(packet)
-  })
-
-  client.on('pingreq', function () {
-    client.pingresp()
-  })
-}).listen(port)
-
-describe('Websocket Client', function () {
-  var baseConfig = { protocol: 'ws', port: port }
-
-  function makeOptions (custom) {
-    // xtend returns a new object. Does not mutate arguments
-    return xtend(baseConfig, custom || {})
-  }
-
-  it('should use mqtt as the protocol by default', function (done) {
-    server.once('client', function (client) {
-      client.stream.socket.protocol.should.equal('mqtt')
-    })
-    mqtt.connect(makeOptions()).on('connect', function () {
-      this.end(true, done)
-    })
-  })
-
-  it('should be able transform the url (for e.g. to sign it)', function (done) {
-    var baseUrl = 'ws://localhost:9999/mqtt'
-    var sig = '?AUTH=token'
-    var expected = baseUrl + sig
-    var actual
-    var opts = makeOptions({
-      path: '/mqtt',
-      transformWsUrl: function (url, opt, client) {
-        assert.equal(url, baseUrl)
-        assert.strictEqual(opt, opts)
-        assert.strictEqual(client.options, opts)
-        assert.strictEqual(typeof opt.transformWsUrl, 'function')
-        assert(client instanceof mqtt.MqttClient)
-        url += sig
-        actual = url
-        return url
-      }})
-    mqtt.connect(opts)
-      .on('connect', function () {
-        assert.equal(this.stream.socket.url, expected)
-        assert.equal(actual, expected)
-        this.end(true, done)
-      })
-  })
-
-  it('should use mqttv3.1 as the protocol if using v3.1', function (done) {
-    server.once('client', function (client) {
-      client.stream.socket.protocol.should.equal('mqttv3.1')
-    })
-
-    var opts = makeOptions({
-      protocolId: 'MQIsdp',
-      protocolVersion: 3
-    })
-
-    mqtt.connect(opts).on('connect', function () {
-      this.end(true, done)
-    })
-  })
-
-  abstractClientTests(server, makeOptions())
-})

+ 0 - 27
src/utils/mqtt/types/index.d.ts

@@ -1,27 +0,0 @@
-export * from './lib/client'
-export * from './lib/connect'
-export * from './lib/store'
-export * from './lib/client-options'
-import { MqttClient } from './lib/client'
-export { MqttClient as Client }
-export {
-  QoS,
-  PacketCmd,
-  IPacket,
-  IConnectPacket,
-  IPublishPacket,
-  IConnackPacket,
-  ISubscription,
-  ISubscribePacket,
-  ISubackPacket,
-  IUnsubscribePacket,
-  IUnsubackPacket,
-  IPubackPacket,
-  IPubcompPacket,
-  IPubrelPacket,
-  IPubrecPacket,
-  IPingreqPacket,
-  IPingrespPacket,
-  IDisconnectPacket,
-  Packet
-} from 'mqtt-packet'

+ 0 - 137
src/utils/mqtt/types/lib/client-options.d.ts

@@ -1,137 +0,0 @@
-import { MqttClient } from './client'
-import { Store } from './store'
-import { QoS } from 'mqtt-packet'
-
-export interface IClientOptions extends ISecureClientOptions {
-  port?: number // port is made into a number subsequently
-  host?: string // host does NOT include port
-  hostname?: string
-  path?: string
-  protocol?: 'wss' | 'ws' | 'mqtt' | 'mqtts' | 'tcp' | 'ssl' | 'wx' | 'wxs'
-
-  wsOptions?: {
-    [x: string]: any
-  }
-  /**
-   *  10 seconds, set to 0 to disable
-   */
-  keepalive?: number
-  /**
-   * 'mqttjs_' + Math.random().toString(16).substr(2, 8)
-   */
-  clientId?: string
-  /**
-   * 'MQTT'
-   */
-  protocolId?: string
-  /**
-   * 4
-   */
-  protocolVersion?: number
-  /**
-   * true, set to false to receive QoS 1 and 2 messages while offline
-   */
-  clean?: boolean
-  /**
-   * 1000 milliseconds, interval between two reconnections
-   */
-  reconnectPeriod?: number
-  /**
-   * 30 * 1000 milliseconds, time to wait before a CONNACK is received
-   */
-  connectTimeout?: number
-  /**
-   * the username required by your broker, if any
-   */
-  username?: string
-  /**
-   * the password required by your broker, if any
-   */
-  password?: string
-  /**
-   * a Store for the incoming packets
-   */
-  incomingStore?: Store
-  /**
-   * a Store for the outgoing packets
-   */
-  outgoingStore?: Store
-  queueQoSZero?: boolean
-  reschedulePings?: boolean
-  servers?: Array<{
-    host: string
-    port: number
-    protocol?: 'wss' | 'ws' | 'mqtt' | 'mqtts' | 'tcp' | 'ssl' | 'wx' | 'wxs'
-  }>
-  /**
-   * true, set to false to disable re-subscribe functionality
-   */
-  resubscribe?: boolean
-  /**
-   * a message that will sent by the broker automatically when the client disconnect badly.
-   */
-  will?: {
-    /**
-     * the topic to publish
-     */
-    topic: string
-    /**
-     * the message to publish
-     */
-    payload: string
-    /**
-     * the QoS
-     */
-    qos: QoS
-    /**
-     * the retain flag
-     */
-    retain: boolean
-  }
-  transformWsUrl?: (url: string, options: IClientOptions, client: MqttClient) => string
-}
-export interface ISecureClientOptions {
-  /**
-   * optional private keys in PEM format
-   */
-  key?: string | string[] | Buffer | Buffer[] | Object[]
-  /**
-   * optional cert chains in PEM format
-   */
-  cert?: string | string[] | Buffer | Buffer[]
-  /**
-   * Optionally override the trusted CA certificates in PEM format
-   */
-  ca?: string | string[] | Buffer | Buffer[]
-  rejectUnauthorized?: boolean
-}
-export interface IClientPublishOptions {
-  /**
-   * the QoS
-   */
-  qos: QoS
-  /**
-   * the retain flag
-   */
-  retain?: boolean
-  /**
-   * whether or not mark a message as duplicate
-   */
-  dup?: boolean
-}
-export interface IClientSubscribeOptions {
-  /**
-   * the QoS
-   */
-  qos: QoS
-}
-export interface IClientReconnectOptions {
-  /**
-   * a Store for the incoming packets
-   */
-  incomingStore?: Store
-  /**
-   * a Store for the outgoing packets
-   */
-  outgoingStore?: Store
-}

+ 0 - 196
src/utils/mqtt/types/lib/client.d.ts

@@ -1,196 +0,0 @@
-/// <reference types="node" />
-
-import * as events from 'events'
-import {
-  IClientOptions,
-  IClientPublishOptions,
-  IClientSubscribeOptions,
-  IClientReconnectOptions
-} from './client-options'
-import { Store } from './store'
-import { Packet, QoS } from 'mqtt-packet'
-
-export interface ISubscriptionGrant {
-  /**
-   *  is a subscribed to topic
-   */
-  topic: string
-  /**
-   *  is the granted qos level on it, may return 128 on error
-   */
-  qos: QoS | number
-}
-export interface ISubscriptionRequest {
-  /**
-   *  is a subscribed to topic
-   */
-  topic: string
-  /**
-   *  is the granted qos level on it
-   */
-  qos: QoS
-}
-export interface ISubscriptionMap {
-  /**
-   * object which has topic names as object keys and as value the QoS, like {'test1': 0, 'test2': 1}.
-   */
-  [topic: string]: QoS
-}
-
-export declare type ClientSubscribeCallback = (err: Error, granted: ISubscriptionGrant[]) => void
-export declare type OnMessageCallback = (topic: string, payload: Buffer, packet: Packet) => void
-export declare type OnPacketCallback = (packet: Packet) => void
-export declare type OnErrorCallback = (error: Error) => void
-export declare type PacketCallback = (error?: Error, packet?: Packet) => any
-export declare type CloseCallback = () => void
-
-export interface IStream extends events.EventEmitter {
-  pipe (to: any): any
-  destroy (): any
-  end (): any
-}
-/**
- * MqttClient constructor
- *
- * @param {Stream} stream - stream
- * @param {Object} [options] - connection options
- * (see Connection#connect)
- */
-export declare class MqttClient extends events.EventEmitter {
-  public connected: boolean
-  public disconnecting: boolean
-  public disconnected: boolean
-  public reconnecting: boolean
-  public incomingStore: Store
-  public outgoingStore: Store
-  public options: IClientOptions
-  public queueQoSZero: boolean
-
-  constructor (streamBuilder: (client: MqttClient) => IStream, options: IClientOptions)
-
-  public on (event: 'message', cb: OnMessageCallback): this
-  public on (event: 'packetsend' | 'packetreceive', cb: OnPacketCallback): this
-  public on (event: 'error', cb: OnErrorCallback): this
-  public on (event: string, cb: Function): this
-
-  public once (event: 'message', cb: OnMessageCallback): this
-  public once (event:
-                'packetsend'
-                | 'packetreceive', cb: OnPacketCallback): this
-  public once (event: 'error', cb: OnErrorCallback): this
-  public once (event: string, cb: Function): this
-
-  /**
-   * publish - publish <message> to <topic>
-   *
-   * @param {String} topic - topic to publish to
-   * @param {(String|Buffer)} message - message to publish
-   *
-   * @param {Object}    [opts] - publish options, includes:
-   *   @param {Number}  [opts.qos] - qos level to publish on
-   *   @param {Boolean} [opts.retain] - whether or not to retain the message
-   *
-   * @param {Function} [callback] - function(err){}
-   *    called when publish succeeds or fails
-   * @returns {Client} this - for chaining
-   * @api public
-   *
-   * @example client.publish('topic', 'message')
-   * @example
-   *     client.publish('topic', 'message', {qos: 1, retain: true})
-   * @example client.publish('topic', 'message', console.log)
-   */
-  public publish (topic: string, message: string | Buffer,
-                 opts: IClientPublishOptions, callback?: PacketCallback): this
-  public publish (topic: string, message: string | Buffer,
-                 callback?: PacketCallback): this
-
-  /**
-   * subscribe - subscribe to <topic>
-   *
-   * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
-   * @param {Object} [opts] - optional subscription options, includes:
-   * @param  {Number} [opts.qos] - subscribe qos level
-   * @param {Function} [callback] - function(err, granted){} where:
-   *    {Error} err - subscription error (none at the moment!)
-   *    {Array} granted - array of {topic: 't', qos: 0}
-   * @returns {MqttClient} this - for chaining
-   * @api public
-   * @example client.subscribe('topic')
-   * @example client.subscribe('topic', {qos: 1})
-   * @example client.subscribe({'topic': 0, 'topic2': 1}, console.log)
-   * @example client.subscribe('topic', console.log)
-   */
-  public subscribe (topic:
-                     string
-                     | string[], opts: IClientSubscribeOptions, callback?: ClientSubscribeCallback): this
-  public subscribe (topic:
-                     string
-                     | string[]
-                     | ISubscriptionMap, callback?: ClientSubscribeCallback): this
-
-  /**
-   * unsubscribe - unsubscribe from topic(s)
-   *
-   * @param {String, Array} topic - topics to unsubscribe from
-   * @param {Function} [callback] - callback fired on unsuback
-   * @returns {MqttClient} this - for chaining
-   * @api public
-   * @example client.unsubscribe('topic')
-   * @example client.unsubscribe('topic', console.log)
-   */
-  public unsubscribe (topic: string | string[], callback?: PacketCallback): this
-
-  /**
-   * end - close connection
-   *
-   * @returns {MqttClient} this - for chaining
-   * @param {Boolean} force - do not wait for all in-flight messages to be acked
-   * @param {Function} cb - called when the client has been closed
-   *
-   * @api public
-   */
-  public end (force?: boolean, cb?: CloseCallback): this
-
-  /**
-   * removeOutgoingMessage - remove a message in outgoing store
-   * the outgoing callback will be called withe Error('Message removed') if the message is removed
-   *
-   * @param {Number} mid - messageId to remove message
-   * @returns {MqttClient} this - for chaining
-   * @api public
-   *
-   * @example client.removeOutgoingMessage(client.getLastMessageId());
-   */
-  public removeOutgoingMessage (mid: number): this
-
-  /**
-   * reconnect - connect again using the same options as connect()
-   *
-   * @param {Object} [opts] - optional reconnect options, includes:
-   *    {Store} incomingStore - a store for the incoming packets
-   *    {Store} outgoingStore - a store for the outgoing packets
-   *    if opts is not given, current stores are used
-   *
-   * @returns {MqttClient} this - for chaining
-   *
-   * @api public
-   */
-  public reconnect (opts?: IClientReconnectOptions): this
-
-  /**
-   * Handle messages with backpressure support, one at a time.
-   * Override at will.
-   *
-   * @param packet packet the packet
-   * @param callback callback call when finished
-   * @api public
-   */
-  public handleMessage (packet: Packet, callback: PacketCallback): void
-
-  /**
-   * getLastMessageId
-   */
-  public getLastMessageId (): number
-}
-export { IClientOptions }

+ 0 - 10
src/utils/mqtt/types/lib/connect/index.d.ts

@@ -1,10 +0,0 @@
-import { IClientOptions, MqttClient } from '../client'
-/**
- * connect - connect to an MQTT broker.
- *
- * @param {String} [brokerUrl] - url of the broker, optional
- * @param {Object} opts - see MqttClient#constructor
- */
-declare function connect (brokerUrl?: string | any, opts?: IClientOptions): MqttClient
-export { connect }
-export { MqttClient }

+ 0 - 6
src/utils/mqtt/types/lib/store-options.d.ts

@@ -1,6 +0,0 @@
-export interface IStoreOptions {
-  /**
-   * true, clear _inflights at close
-   */
-  clean?: boolean
-}

+ 0 - 46
src/utils/mqtt/types/lib/store.d.ts

@@ -1,46 +0,0 @@
-import {
-  IStoreOptions
-} from './store-options'
-
-/**
- * In-memory implementation of the message store
- * This can actually be saved into files.
- *
- */
-declare class Store {
-  /**
-   * Store constructor
-   *
-   * @param {Object} [options] - store options
-   */
-  constructor (options: IStoreOptions)
-
-  /**
-   * Adds a packet to the store, a packet is
-   * anything that has a messageId property.
-   *
-   */
-  public put (packet: any, cb?: Function): this
-
-  /**
-   * Creates a stream with all the packets in the store
-   *
-   */
-  public createStream (): any
-
-  /**
-   * deletes a packet from the store.
-   */
-  public del (packet: any, cb: Function): this
-
-  /**
-   * get a packet from the store.
-   */
-  public get (packet: any, cb: Function): this
-
-  /**
-   * Close the store
-   */
-  public close (cb: Function): void
-}
-export { Store }

+ 11 - 9
src/views/equipment-center/real-time-data/european-gourd.vue

@@ -42,7 +42,7 @@
             <div class="item" v-if="currentData?.stroke">
               <div>
                 <div class="text1">
-                  {{ formatValue(currentData?.stroke.value, currentData?.stroke.translate) }}
+                  {{ currentData?.stroke.value??'' }}
                   <span style="font-weight: 400; font-size: 16px">{{ currentData?.stroke.unit }}</span>
                 </div>
                 <div class="text2">
@@ -64,7 +64,7 @@
             <div class="item" v-if="currentData?.weight">
               <div>
                 <div class="text1">
-                  {{ formatValue(currentData?.weight.value, currentData?.weight.translate) }}
+                  {{ currentData?.weight.value??'' }}
                   <span style="font-weight: 400; font-size: 16px">{{ currentData?.weight.unit }}</span>
                 </div>
                 <div class="text2">
@@ -95,7 +95,7 @@
         <div class="g-fx-j right__item" v-for="(el, i) in currentData?.matchVariables" :key="i">
           <div class="text">{{ el.name }}</div>
           <div class="text2">
-            {{ formatValue(el.vValue, el.translate) + el.unitName }}
+            {{ el.vValue??'' + el.unitName }}
             <div :style="{ backgroundColor: getMatchBgColor(el) }"></div>
           </div>
         </div>
@@ -103,7 +103,7 @@
         <div class="g-fx-j right__item" v-for="(el, i) in currentData?.valueVariables" :key="i">
           <div class="text">{{ el.variableName }}</div>
           <div class="text2">
-            {{ formatValue(el.value, el.translate) + el.unitName }}
+            {{ el.value??'' + el.unitName }}
           </div>
         </div>
       </div>
@@ -148,7 +148,7 @@ onMounted(async () => {
 const getDeviceInfo = async () => {
   const data = await fetchDeviceInfoAll(deviceId.value)
   equipmentInfo.value = data
-  onSubscribe([`Byte/${equipmentInfo.value.code}`],(topic: any, payload: any) => {
+  onSubscribe([`Byte/${equipmentInfo.value.code}`], (topic: any, payload: any) => {
     parseData(payload)
   })
 }
@@ -198,7 +198,8 @@ const parseData = (payload: any) => {
     //载荷
     var weight = item.weight
     if (weight != null) {
-      weight.value = toData(byteArray, weight.dataType, weight.address)
+      const result = toData(byteArray, weight.dataType, weight.address)
+      weight.value = formatValue(result, weight.translate)
       var light = weight.light
       if (light != null) {
         light.value = light.isReverse != toData(byteArray, 1, light.address)
@@ -209,8 +210,8 @@ const parseData = (payload: any) => {
     //高度或者 行程
     var stroke = item.stroke
     if (stroke != null) {
-      var value = toData(byteArray, stroke.dataType, stroke.address)
-      stroke.value = value < 0 ? '0' : value
+      const result = toData(byteArray, stroke.dataType, stroke.address)
+      stroke.value = formatValue(result, stroke.translate)
     }
 
     //档位
@@ -244,7 +245,8 @@ const parseData = (payload: any) => {
     })
 
     item.matchVariables.forEach((m: any) => {
-      m.vValue = toData(byteArray, m.dataType, m.vAddress)
+      const result = toData(byteArray, m.dataType, m.vAddress)
+      m.vValue = formatValue(result, m.translate)
 
       var sAddress = m.sAddress
       if (sAddress.indexOf(',') > 0) {

+ 8 - 5
src/views/equipment-center/real-time-data/index.vue

@@ -51,7 +51,7 @@
             </div>
             <div class="item-info__el" v-if="item?.weight">
               <div class="distance">
-                {{ formatValue(item?.weight?.value, item?.weight?.translate) }}
+                {{ item?.weight?.value }}
                 <span style="font-size: 12px">{{ item.weight?.unit || item.weight?.unitName }}</span>
               </div>
               <div class="text">
@@ -85,14 +85,14 @@
             <div class="item-info3__el" v-for="el in item?.matchVariables">
               <div class="text">{{ el.variableName }}</div>
               <div class="g-fx" style="align-items: center">
-                <div>{{ formatValue(el.value, el.translate) + ' ' + el.unitName }}</div>
+                <div>{{ el.value??'' + el.unitName }}</div>
                 <div style="margin-left: 10px" class="line" :style="{ background: getMatchBgColor(el) }"></div>
               </div>
             </div>
             <div class="item-info3__el" v-for="el in item?.valueVariables">
               <div class="text">{{ el.variableName }}</div>
               <div class="g-fx" style="align-items: center">
-                <div>{{ formatValue(el.value, el.translate) + el.unitName }}</div>
+                <div>{{ el.value??'' + el.unitName }}</div>
               </div>
             </div>
           </div>
@@ -169,7 +169,7 @@ const parseData = (payload: any) => {
       }
       var weight = group.weight
       if (weight?.code == mqttCode) {
-        weight.value = mqttValue
+        weight.value = formatValue(mqttValue, weight.translate)
         return
       }
 
@@ -181,7 +181,7 @@ const parseData = (payload: any) => {
 
       var stroke = group.stroke
       if (stroke?.code == mqttCode) {
-        stroke.value = mqttValue
+        stroke.value = formatValue(mqttValue, stroke.translate)
         return
       }
 
@@ -205,6 +205,7 @@ const parseData = (payload: any) => {
           variable.value = mqttValue === 'true' || mqttValue === true ? '开启' : '闭合'
         } else {
           let value = formatValue(mqttValue, variable.translate)
+          console.log("variable解析",value)
           variable.value = evaluateFormula(value, variable.formula)
         }
         return
@@ -265,6 +266,7 @@ const evaluateFormula = (value: any, formula: any) => {
   if (formula == null || formula == undefined || formula === '') {
     return value
   }
+  console.log("函数计算",formula)
   //函数模板
   const array = formula.split(",")
   //字符串模本
@@ -275,6 +277,7 @@ const evaluateFormula = (value: any, formula: any) => {
     const result = eval(func)
     templete = templete.replace(`{${index}}`, Math.floor(parseFloat(result)))
   })
+  console.log("函数计算",templete)
   return templete
 }