* MqttClient constructor * * @param {Stream} stream - stream * @param {Object} [options] - connection options * (see Connection#connect)
(streamBuilder, options)
| 63 | * (see Connection#connect) |
| 64 | */ |
| 65 | function MqttClient (streamBuilder, options) { |
| 66 | var k, |
| 67 | that = this; |
| 68 | |
| 69 | if (!(this instanceof MqttClient)) { |
| 70 | return new MqttClient(streamBuilder, options); |
| 71 | } |
| 72 | |
| 73 | this.options = options || {}; |
| 74 | |
| 75 | // Defaults |
| 76 | for (k in defaultConnectOptions) { |
| 77 | if ('undefined' === typeof this.options[k]) { |
| 78 | this.options[k] = defaultConnectOptions[k]; |
| 79 | } else { |
| 80 | this.options[k] = options[k]; |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | this.options.clientId = this.options.clientId || defaultId(); |
| 85 | |
| 86 | this.streamBuilder = streamBuilder; |
| 87 | |
| 88 | // Inflight message storages |
| 89 | this.outgoingStore = this.options.outgoingStore || new Store(); |
| 90 | this.incomingStore = this.options.incomingStore || new Store(); |
| 91 | |
| 92 | // Ping timer, setup in _setupPingTimer |
| 93 | this.pingTimer = null; |
| 94 | // Is the client connected? |
| 95 | this.connected = false; |
| 96 | // Are we disconnecting? |
| 97 | this.disconnecting = false; |
| 98 | // Packet queue |
| 99 | this.queue = []; |
| 100 | // Are we intentionally disconnecting? |
| 101 | this.disconnecting = false; |
| 102 | // Reconnect timer |
| 103 | this.reconnectTimer = null; |
| 104 | // MessageIDs starting with 1 |
| 105 | this.nextId = Math.floor(Math.random() * 65535); |
| 106 | |
| 107 | // Inflight callbacks |
| 108 | this.outgoing = {}; |
| 109 | |
| 110 | // Mark connected on connect |
| 111 | this.on('connect', function () { |
| 112 | this.connected = true; |
| 113 | }); |
| 114 | |
| 115 | // Mark disconnected on stream close |
| 116 | this.on('close', function () { |
| 117 | this.connected = false; |
| 118 | }); |
| 119 | |
| 120 | // Setup ping timer |
| 121 | this.on('connect', this._setupPingTimer); |
| 122 |