@aws-amplify/pubsub
Version:
Pubsub category of aws-amplify
1 lines • 174 kB
Source Map (JSON)
{"version":3,"file":"paho-mqtt.mjs","sources":["../../../src/vendor/paho-mqtt.js"],"sourcesContent":["/*******************************************************************************\n * Copyright (c) 2013 IBM Corp.\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * and Eclipse Distribution License v1.0 which accompany this distribution.\n *\n * The Eclipse Public License is available at\n * http://www.eclipse.org/legal/epl-v10.html\n * and the Eclipse Distribution License is available at\n * http://www.eclipse.org/org/documents/edl-v10.php.\n *\n * Contributors:\n * Andrew Banks - initial API and implementation and initial documentation\n *******************************************************************************/\n\n// Only expose a single object name in the global namespace.\n// Everything must go through this module. Global Paho module\n// only has a single public function, client, which returns\n// a Paho client object given connection details.\n\n/**\n * Send and receive messages using web browsers.\n * <p>\n * This programming interface lets a JavaScript client application use the MQTT V3.1 or\n * V3.1.1 protocol to connect to an MQTT-supporting messaging server.\n *\n * The function supported includes:\n * <ol>\n * <li>Connecting to and disconnecting from a server. The server is identified by its host name and port number.\n * <li>Specifying options that relate to the communications link with the server,\n * for example the frequency of keep-alive heartbeats, and whether SSL/TLS is required.\n * <li>Subscribing to and receiving messages from MQTT Topics.\n * <li>Publishing messages to MQTT Topics.\n * </ol>\n * <p>\n * The API consists of two main objects:\n * <dl>\n * <dt><b>{@link Paho.Client}</b></dt>\n * <dd>This contains methods that provide the functionality of the API,\n * including provision of callbacks that notify the application when a message\n * arrives from or is delivered to the messaging server,\n * or when the status of its connection to the messaging server changes.</dd>\n * <dt><b>{@link Paho.Message}</b></dt>\n * <dd>This encapsulates the payload of the message along with various attributes\n * associated with its delivery, in particular the destination to which it has\n * been (or is about to be) sent.</dd>\n * </dl>\n * <p>\n * The programming interface validates parameters passed to it, and will throw\n * an Error containing an error message intended for developer use, if it detects\n * an error with any parameter.\n * <p>\n * Example:\n *\n * <code><pre>\nvar client = new Paho.MQTT.Client(location.hostname, Number(location.port), \"clientId\");\nclient.onConnectionLost = onConnectionLost;\nclient.onMessageArrived = onMessageArrived;\nclient.connect({onSuccess:onConnect});\n\nfunction onConnect() {\n // Once a connection has been made, make a subscription and send a message.\n console.log(\"onConnect\");\n client.subscribe(\"/World\");\n var message = new Paho.MQTT.Message(\"Hello\");\n message.destinationName = \"/World\";\n client.send(message);\n};\nfunction onConnectionLost(responseObject) {\n if (responseObject.errorCode !== 0)\n\tconsole.log(\"onConnectionLost:\"+responseObject.errorMessage);\n};\nfunction onMessageArrived(message) {\n console.log(\"onMessageArrived:\"+message.payloadString);\n client.disconnect();\n};\n * </pre></code>\n * @namespace Paho\n */\n\n/* jshint shadow:true */\n(function ExportLibrary(root, factory) {\n\tif (typeof exports === 'object' && typeof module === 'object') {\n\t\tmodule.exports = factory();\n\t} else if (typeof define === 'function' && define.amd) {\n\t\tdefine(factory);\n\t} else if (typeof exports === 'object') {\n\t\texports = factory();\n\t} else {\n\t\t//if (typeof root.Paho === \"undefined\"){\n\t\t//\troot.Paho = {};\n\t\t//}\n\t\troot.Paho = factory();\n\t}\n})(this, function LibraryFactory() {\n\tvar PahoMQTT = (function (global) {\n\t\t// Private variables below, these are only visible inside the function closure\n\t\t// which is used to define the module.\n\t\tvar version = '@VERSION@-@BUILDLEVEL@';\n\n\t\t// 2023-01-05: AWS Amplify change to incorporate upstream pull request:\n\t\t// https://github.com/eclipse/paho.mqtt.javascript/pull/247\n\n\t\t/**\n\t\t * @private\n\t\t */\n\t\tvar localStorage = (function () {\n\t\t\ttry {\n\t\t\t\t// When third-party cookies are disabled accessing localStorage will cause an error\n\t\t\t\tif (global.localStorage) return global.localStorage;\n\t\t\t} catch (e) {\n\t\t\t\tvar data = {};\n\n\t\t\t\treturn {\n\t\t\t\t\tsetItem: function (key, item) {\n\t\t\t\t\t\tdata[key] = item;\n\t\t\t\t\t},\n\t\t\t\t\tgetItem: function (key) {\n\t\t\t\t\t\treturn data[key];\n\t\t\t\t\t},\n\t\t\t\t\tremoveItem: function (key) {\n\t\t\t\t\t\tdelete data[key];\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t})();\n\n\t\t// End of AWS Amplify change\n\n\t\t/**\n\t\t * Unique message type identifiers, with associated\n\t\t * associated integer values.\n\t\t * @private\n\t\t */\n\t\tvar MESSAGE_TYPE = {\n\t\t\tCONNECT: 1,\n\t\t\tCONNACK: 2,\n\t\t\tPUBLISH: 3,\n\t\t\tPUBACK: 4,\n\t\t\tPUBREC: 5,\n\t\t\tPUBREL: 6,\n\t\t\tPUBCOMP: 7,\n\t\t\tSUBSCRIBE: 8,\n\t\t\tSUBACK: 9,\n\t\t\tUNSUBSCRIBE: 10,\n\t\t\tUNSUBACK: 11,\n\t\t\tPINGREQ: 12,\n\t\t\tPINGRESP: 13,\n\t\t\tDISCONNECT: 14,\n\t\t};\n\n\t\t// Collection of utility methods used to simplify module code\n\t\t// and promote the DRY pattern.\n\n\t\t/**\n\t\t * Validate an object's parameter names to ensure they\n\t\t * match a list of expected variables name for this option\n\t\t * type. Used to ensure option object passed into the API don't\n\t\t * contain erroneous parameters.\n\t\t * @param {Object} obj - User options object\n\t\t * @param {Object} keys - valid keys and types that may exist in obj.\n\t\t * @throws {Error} Invalid option parameter found.\n\t\t * @private\n\t\t */\n\t\tvar validate = function (obj, keys) {\n\t\t\tfor (var key in obj) {\n\t\t\t\tif (obj.hasOwnProperty(key)) {\n\t\t\t\t\tif (keys.hasOwnProperty(key)) {\n\t\t\t\t\t\tif (typeof obj[key] !== keys[key])\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\tformat(ERROR.INVALID_TYPE, [typeof obj[key], key]),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar errorStr =\n\t\t\t\t\t\t\t'Unknown property, ' + key + '. Valid properties are:';\n\t\t\t\t\t\tfor (var validKey in keys)\n\t\t\t\t\t\t\tif (keys.hasOwnProperty(validKey))\n\t\t\t\t\t\t\t\terrorStr = errorStr + ' ' + validKey;\n\t\t\t\t\t\tthrow new Error(errorStr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t/**\n\t\t * Return a new function which runs the user function bound\n\t\t * to a fixed scope.\n\t\t * @param {function} User function\n\t\t * @param {object} Function scope\n\t\t * @return {function} User function bound to another scope\n\t\t * @private\n\t\t */\n\t\tvar scope = function (f, scope) {\n\t\t\treturn function () {\n\t\t\t\treturn f.apply(scope, arguments);\n\t\t\t};\n\t\t};\n\n\t\t/**\n\t\t * Unique message type identifiers, with associated\n\t\t * associated integer values.\n\t\t * @private\n\t\t */\n\t\tvar ERROR = {\n\t\t\tOK: { code: 0, text: 'AMQJSC0000I OK.' },\n\t\t\tCONNECT_TIMEOUT: { code: 1, text: 'AMQJSC0001E Connect timed out.' },\n\t\t\tSUBSCRIBE_TIMEOUT: { code: 2, text: 'AMQJS0002E Subscribe timed out.' },\n\t\t\tUNSUBSCRIBE_TIMEOUT: {\n\t\t\t\tcode: 3,\n\t\t\t\ttext: 'AMQJS0003E Unsubscribe timed out.',\n\t\t\t},\n\t\t\tPING_TIMEOUT: { code: 4, text: 'AMQJS0004E Ping timed out.' },\n\t\t\tINTERNAL_ERROR: {\n\t\t\t\tcode: 5,\n\t\t\t\ttext: 'AMQJS0005E Internal error. Error Message: {0}, Stack trace: {1}',\n\t\t\t},\n\t\t\tCONNACK_RETURNCODE: {\n\t\t\t\tcode: 6,\n\t\t\t\ttext: 'AMQJS0006E Bad Connack return code:{0} {1}.',\n\t\t\t},\n\t\t\tSOCKET_ERROR: { code: 7, text: 'AMQJS0007E Socket error:{0}.' },\n\t\t\tSOCKET_CLOSE: { code: 8, text: 'AMQJS0008I Socket closed.' },\n\t\t\tMALFORMED_UTF: {\n\t\t\t\tcode: 9,\n\t\t\t\ttext: 'AMQJS0009E Malformed UTF data:{0} {1} {2}.',\n\t\t\t},\n\t\t\tUNSUPPORTED: {\n\t\t\t\tcode: 10,\n\t\t\t\ttext: 'AMQJS0010E {0} is not supported by this browser.',\n\t\t\t},\n\t\t\tINVALID_STATE: { code: 11, text: 'AMQJS0011E Invalid state {0}.' },\n\t\t\tINVALID_TYPE: { code: 12, text: 'AMQJS0012E Invalid type {0} for {1}.' },\n\t\t\tINVALID_ARGUMENT: {\n\t\t\t\tcode: 13,\n\t\t\t\ttext: 'AMQJS0013E Invalid argument {0} for {1}.',\n\t\t\t},\n\t\t\tUNSUPPORTED_OPERATION: {\n\t\t\t\tcode: 14,\n\t\t\t\ttext: 'AMQJS0014E Unsupported operation.',\n\t\t\t},\n\t\t\tINVALID_STORED_DATA: {\n\t\t\t\tcode: 15,\n\t\t\t\ttext: 'AMQJS0015E Invalid data in local storage key={0} value={1}.',\n\t\t\t},\n\t\t\tINVALID_MQTT_MESSAGE_TYPE: {\n\t\t\t\tcode: 16,\n\t\t\t\ttext: 'AMQJS0016E Invalid MQTT message type {0}.',\n\t\t\t},\n\t\t\tMALFORMED_UNICODE: {\n\t\t\t\tcode: 17,\n\t\t\t\ttext: 'AMQJS0017E Malformed Unicode string:{0} {1}.',\n\t\t\t},\n\t\t\tBUFFER_FULL: {\n\t\t\t\tcode: 18,\n\t\t\t\ttext: 'AMQJS0018E Message buffer is full, maximum buffer size: {0}.',\n\t\t\t},\n\t\t};\n\n\t\t/** CONNACK RC Meaning. */\n\t\tvar CONNACK_RC = {\n\t\t\t0: 'Connection Accepted',\n\t\t\t1: 'Connection Refused: unacceptable protocol version',\n\t\t\t2: 'Connection Refused: identifier rejected',\n\t\t\t3: 'Connection Refused: server unavailable',\n\t\t\t4: 'Connection Refused: bad user name or password',\n\t\t\t5: 'Connection Refused: not authorized',\n\t\t};\n\n\t\t/**\n\t\t * Format an error message text.\n\t\t * @private\n\t\t * @param {error} ERROR value above.\n\t\t * @param {substitutions} [array] substituted into the text.\n\t\t * @return the text with the substitutions made.\n\t\t */\n\t\tvar format = function (error, substitutions) {\n\t\t\tvar text = error.text;\n\t\t\tif (substitutions) {\n\t\t\t\tvar field, start;\n\t\t\t\tfor (var i = 0; i < substitutions.length; i++) {\n\t\t\t\t\tfield = '{' + i + '}';\n\t\t\t\t\tstart = text.indexOf(field);\n\t\t\t\t\tif (start > 0) {\n\t\t\t\t\t\tvar part1 = text.substring(0, start);\n\t\t\t\t\t\tvar part2 = text.substring(start + field.length);\n\t\t\t\t\t\ttext = part1 + substitutions[i] + part2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn text;\n\t\t};\n\n\t\t//MQTT protocol and version 6 M Q I s d p 3\n\t\tvar MqttProtoIdentifierv3 = [\n\t\t\t0x00, 0x06, 0x4d, 0x51, 0x49, 0x73, 0x64, 0x70, 0x03,\n\t\t];\n\t\t//MQTT proto/version for 311 4 M Q T T 4\n\t\tvar MqttProtoIdentifierv4 = [0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04];\n\n\t\t/**\n\t\t * Construct an MQTT wire protocol message.\n\t\t * @param type MQTT packet type.\n\t\t * @param options optional wire message attributes.\n\t\t *\n\t\t * Optional properties\n\t\t *\n\t\t * messageIdentifier: message ID in the range [0..65535]\n\t\t * payloadMessage:\tApplication Message - PUBLISH only\n\t\t * connectStrings:\tarray of 0 or more Strings to be put into the CONNECT payload\n\t\t * topics:\t\t\tarray of strings (SUBSCRIBE, UNSUBSCRIBE)\n\t\t * requestQoS:\t\tarray of QoS values [0..2]\n\t\t *\n\t\t * \"Flag\" properties\n\t\t * cleanSession:\ttrue if present / false if absent (CONNECT)\n\t\t * willMessage: \ttrue if present / false if absent (CONNECT)\n\t\t * isRetained:\t\ttrue if present / false if absent (CONNECT)\n\t\t * userName:\t\ttrue if present / false if absent (CONNECT)\n\t\t * password:\t\ttrue if present / false if absent (CONNECT)\n\t\t * keepAliveInterval:\tinteger [0..65535] (CONNECT)\n\t\t *\n\t\t * @private\n\t\t * @ignore\n\t\t */\n\t\tvar WireMessage = function (type, options) {\n\t\t\tthis.type = type;\n\t\t\tfor (var name in options) {\n\t\t\t\tif (options.hasOwnProperty(name)) {\n\t\t\t\t\tthis[name] = options[name];\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tWireMessage.prototype.encode = function () {\n\t\t\t// Compute the first byte of the fixed header\n\t\t\tvar first = (this.type & 0x0f) << 4;\n\n\t\t\t/*\n\t\t\t * Now calculate the length of the variable header + payload by adding up the lengths\n\t\t\t * of all the component parts\n\t\t\t */\n\n\t\t\tvar remLength = 0;\n\t\t\tvar topicStrLength = [];\n\t\t\tvar destinationNameLength = 0;\n\t\t\tvar willMessagePayloadBytes;\n\n\t\t\t// if the message contains a messageIdentifier then we need two bytes for that\n\t\t\tif (this.messageIdentifier !== undefined) remLength += 2;\n\n\t\t\tswitch (this.type) {\n\t\t\t\t// If this a Connect then we need to include 12 bytes for its header\n\t\t\t\tcase MESSAGE_TYPE.CONNECT:\n\t\t\t\t\tswitch (this.mqttVersion) {\n\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t\tremLength += MqttProtoIdentifierv3.length + 3;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 4:\n\t\t\t\t\t\t\tremLength += MqttProtoIdentifierv4.length + 3;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tremLength += UTF8Length(this.clientId) + 2;\n\t\t\t\t\tif (this.willMessage !== undefined) {\n\t\t\t\t\t\tremLength += UTF8Length(this.willMessage.destinationName) + 2;\n\t\t\t\t\t\t// Will message is always a string, sent as UTF-8 characters with a preceding length.\n\t\t\t\t\t\twillMessagePayloadBytes = this.willMessage.payloadBytes;\n\t\t\t\t\t\tif (!(willMessagePayloadBytes instanceof Uint8Array))\n\t\t\t\t\t\t\twillMessagePayloadBytes = new Uint8Array(payloadBytes);\n\t\t\t\t\t\tremLength += willMessagePayloadBytes.byteLength + 2;\n\t\t\t\t\t}\n\t\t\t\t\tif (this.userName !== undefined)\n\t\t\t\t\t\tremLength += UTF8Length(this.userName) + 2;\n\t\t\t\t\tif (this.password !== undefined)\n\t\t\t\t\t\tremLength += UTF8Length(this.password) + 2;\n\t\t\t\t\tbreak;\n\n\t\t\t\t// Subscribe, Unsubscribe can both contain topic strings\n\t\t\t\tcase MESSAGE_TYPE.SUBSCRIBE:\n\t\t\t\t\tfirst |= 0x02; // Qos = 1;\n\t\t\t\t\tfor (var i = 0; i < this.topics.length; i++) {\n\t\t\t\t\t\ttopicStrLength[i] = UTF8Length(this.topics[i]);\n\t\t\t\t\t\tremLength += topicStrLength[i] + 2;\n\t\t\t\t\t}\n\t\t\t\t\tremLength += this.requestedQos.length; // 1 byte for each topic's Qos\n\t\t\t\t\t// QoS on Subscribe only\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MESSAGE_TYPE.UNSUBSCRIBE:\n\t\t\t\t\tfirst |= 0x02; // Qos = 1;\n\t\t\t\t\tfor (var i = 0; i < this.topics.length; i++) {\n\t\t\t\t\t\ttopicStrLength[i] = UTF8Length(this.topics[i]);\n\t\t\t\t\t\tremLength += topicStrLength[i] + 2;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MESSAGE_TYPE.PUBREL:\n\t\t\t\t\tfirst |= 0x02; // Qos = 1;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MESSAGE_TYPE.PUBLISH:\n\t\t\t\t\tif (this.payloadMessage.duplicate) first |= 0x08;\n\t\t\t\t\tfirst = first |= this.payloadMessage.qos << 1;\n\t\t\t\t\tif (this.payloadMessage.retained) first |= 0x01;\n\t\t\t\t\tdestinationNameLength = UTF8Length(\n\t\t\t\t\t\tthis.payloadMessage.destinationName,\n\t\t\t\t\t);\n\t\t\t\t\tremLength += destinationNameLength + 2;\n\t\t\t\t\tvar payloadBytes = this.payloadMessage.payloadBytes;\n\t\t\t\t\tremLength += payloadBytes.byteLength;\n\t\t\t\t\tif (payloadBytes instanceof ArrayBuffer)\n\t\t\t\t\t\tpayloadBytes = new Uint8Array(payloadBytes);\n\t\t\t\t\telse if (!(payloadBytes instanceof Uint8Array))\n\t\t\t\t\t\tpayloadBytes = new Uint8Array(payloadBytes.buffer);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MESSAGE_TYPE.DISCONNECT:\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Now we can allocate a buffer for the message\n\n\t\t\tvar mbi = encodeMBI(remLength); // Convert the length to MQTT MBI format\n\t\t\tvar pos = mbi.length + 1; // Offset of start of variable header\n\t\t\tvar buffer = new ArrayBuffer(remLength + pos);\n\t\t\tvar byteStream = new Uint8Array(buffer); // view it as a sequence of bytes\n\n\t\t\t//Write the fixed header into the buffer\n\t\t\tbyteStream[0] = first;\n\t\t\tbyteStream.set(mbi, 1);\n\n\t\t\t// If this is a PUBLISH then the variable header starts with a topic\n\t\t\tif (this.type == MESSAGE_TYPE.PUBLISH)\n\t\t\t\tpos = writeString(\n\t\t\t\t\tthis.payloadMessage.destinationName,\n\t\t\t\t\tdestinationNameLength,\n\t\t\t\t\tbyteStream,\n\t\t\t\t\tpos,\n\t\t\t\t);\n\t\t\t// If this is a CONNECT then the variable header contains the protocol name/version, flags and keepalive time\n\t\t\telse if (this.type == MESSAGE_TYPE.CONNECT) {\n\t\t\t\tswitch (this.mqttVersion) {\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\tbyteStream.set(MqttProtoIdentifierv3, pos);\n\t\t\t\t\t\tpos += MqttProtoIdentifierv3.length;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 4:\n\t\t\t\t\t\tbyteStream.set(MqttProtoIdentifierv4, pos);\n\t\t\t\t\t\tpos += MqttProtoIdentifierv4.length;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tvar connectFlags = 0;\n\t\t\t\tif (this.cleanSession) connectFlags = 0x02;\n\t\t\t\tif (this.willMessage !== undefined) {\n\t\t\t\t\tconnectFlags |= 0x04;\n\t\t\t\t\tconnectFlags |= this.willMessage.qos << 3;\n\t\t\t\t\tif (this.willMessage.retained) {\n\t\t\t\t\t\tconnectFlags |= 0x20;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (this.userName !== undefined) connectFlags |= 0x80;\n\t\t\t\tif (this.password !== undefined) connectFlags |= 0x40;\n\t\t\t\tbyteStream[pos++] = connectFlags;\n\t\t\t\tpos = writeUint16(this.keepAliveInterval, byteStream, pos);\n\t\t\t}\n\n\t\t\t// Output the messageIdentifier - if there is one\n\t\t\tif (this.messageIdentifier !== undefined)\n\t\t\t\tpos = writeUint16(this.messageIdentifier, byteStream, pos);\n\n\t\t\tswitch (this.type) {\n\t\t\t\tcase MESSAGE_TYPE.CONNECT:\n\t\t\t\t\tpos = writeString(\n\t\t\t\t\t\tthis.clientId,\n\t\t\t\t\t\tUTF8Length(this.clientId),\n\t\t\t\t\t\tbyteStream,\n\t\t\t\t\t\tpos,\n\t\t\t\t\t);\n\t\t\t\t\tif (this.willMessage !== undefined) {\n\t\t\t\t\t\tpos = writeString(\n\t\t\t\t\t\t\tthis.willMessage.destinationName,\n\t\t\t\t\t\t\tUTF8Length(this.willMessage.destinationName),\n\t\t\t\t\t\t\tbyteStream,\n\t\t\t\t\t\t\tpos,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tpos = writeUint16(\n\t\t\t\t\t\t\twillMessagePayloadBytes.byteLength,\n\t\t\t\t\t\t\tbyteStream,\n\t\t\t\t\t\t\tpos,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbyteStream.set(willMessagePayloadBytes, pos);\n\t\t\t\t\t\tpos += willMessagePayloadBytes.byteLength;\n\t\t\t\t\t}\n\t\t\t\t\tif (this.userName !== undefined)\n\t\t\t\t\t\tpos = writeString(\n\t\t\t\t\t\t\tthis.userName,\n\t\t\t\t\t\t\tUTF8Length(this.userName),\n\t\t\t\t\t\t\tbyteStream,\n\t\t\t\t\t\t\tpos,\n\t\t\t\t\t\t);\n\t\t\t\t\tif (this.password !== undefined)\n\t\t\t\t\t\tpos = writeString(\n\t\t\t\t\t\t\tthis.password,\n\t\t\t\t\t\t\tUTF8Length(this.password),\n\t\t\t\t\t\t\tbyteStream,\n\t\t\t\t\t\t\tpos,\n\t\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MESSAGE_TYPE.PUBLISH:\n\t\t\t\t\t// PUBLISH has a text or binary payload, if text do not add a 2 byte length field, just the UTF characters.\n\t\t\t\t\tbyteStream.set(payloadBytes, pos);\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t// \t case MESSAGE_TYPE.PUBREC:\n\t\t\t\t// \t case MESSAGE_TYPE.PUBREL:\n\t\t\t\t// \t case MESSAGE_TYPE.PUBCOMP:\n\t\t\t\t// \t \tbreak;\n\n\t\t\t\tcase MESSAGE_TYPE.SUBSCRIBE:\n\t\t\t\t\t// SUBSCRIBE has a list of topic strings and request QoS\n\t\t\t\t\tfor (var i = 0; i < this.topics.length; i++) {\n\t\t\t\t\t\tpos = writeString(\n\t\t\t\t\t\t\tthis.topics[i],\n\t\t\t\t\t\t\ttopicStrLength[i],\n\t\t\t\t\t\t\tbyteStream,\n\t\t\t\t\t\t\tpos,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbyteStream[pos++] = this.requestedQos[i];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MESSAGE_TYPE.UNSUBSCRIBE:\n\t\t\t\t\t// UNSUBSCRIBE has a list of topic strings\n\t\t\t\t\tfor (var i = 0; i < this.topics.length; i++)\n\t\t\t\t\t\tpos = writeString(\n\t\t\t\t\t\t\tthis.topics[i],\n\t\t\t\t\t\t\ttopicStrLength[i],\n\t\t\t\t\t\t\tbyteStream,\n\t\t\t\t\t\t\tpos,\n\t\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t// Do nothing.\n\t\t\t}\n\n\t\t\treturn buffer;\n\t\t};\n\n\t\tfunction decodeMessage(input, pos) {\n\t\t\tvar startingPos = pos;\n\t\t\tvar first = input[pos];\n\t\t\tvar type = first >> 4;\n\t\t\tvar messageInfo = (first &= 0x0f);\n\t\t\tpos += 1;\n\n\t\t\t// Decode the remaining length (MBI format)\n\n\t\t\tvar digit;\n\t\t\tvar remLength = 0;\n\t\t\tvar multiplier = 1;\n\t\t\tdo {\n\t\t\t\tif (pos == input.length) {\n\t\t\t\t\treturn [null, startingPos];\n\t\t\t\t}\n\t\t\t\tdigit = input[pos++];\n\t\t\t\tremLength += (digit & 0x7f) * multiplier;\n\t\t\t\tmultiplier *= 128;\n\t\t\t} while ((digit & 0x80) !== 0);\n\n\t\t\tvar endPos = pos + remLength;\n\t\t\tif (endPos > input.length) {\n\t\t\t\treturn [null, startingPos];\n\t\t\t}\n\n\t\t\tvar wireMessage = new WireMessage(type);\n\t\t\tswitch (type) {\n\t\t\t\tcase MESSAGE_TYPE.CONNACK:\n\t\t\t\t\tvar connectAcknowledgeFlags = input[pos++];\n\t\t\t\t\tif (connectAcknowledgeFlags & 0x01) wireMessage.sessionPresent = true;\n\t\t\t\t\twireMessage.returnCode = input[pos++];\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MESSAGE_TYPE.PUBLISH:\n\t\t\t\t\tvar qos = (messageInfo >> 1) & 0x03;\n\n\t\t\t\t\tvar len = readUint16(input, pos);\n\t\t\t\t\tpos += 2;\n\t\t\t\t\tvar topicName = parseUTF8(input, pos, len);\n\t\t\t\t\tpos += len;\n\t\t\t\t\t// If QoS 1 or 2 there will be a messageIdentifier\n\t\t\t\t\tif (qos > 0) {\n\t\t\t\t\t\twireMessage.messageIdentifier = readUint16(input, pos);\n\t\t\t\t\t\tpos += 2;\n\t\t\t\t\t}\n\n\t\t\t\t\tvar message = new Message(input.subarray(pos, endPos));\n\t\t\t\t\tif ((messageInfo & 0x01) == 0x01) message.retained = true;\n\t\t\t\t\tif ((messageInfo & 0x08) == 0x08) message.duplicate = true;\n\t\t\t\t\tmessage.qos = qos;\n\t\t\t\t\tmessage.destinationName = topicName;\n\t\t\t\t\twireMessage.payloadMessage = message;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MESSAGE_TYPE.PUBACK:\n\t\t\t\tcase MESSAGE_TYPE.PUBREC:\n\t\t\t\tcase MESSAGE_TYPE.PUBREL:\n\t\t\t\tcase MESSAGE_TYPE.PUBCOMP:\n\t\t\t\tcase MESSAGE_TYPE.UNSUBACK:\n\t\t\t\t\twireMessage.messageIdentifier = readUint16(input, pos);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MESSAGE_TYPE.SUBACK:\n\t\t\t\t\twireMessage.messageIdentifier = readUint16(input, pos);\n\t\t\t\t\tpos += 2;\n\t\t\t\t\twireMessage.returnCode = input.subarray(pos, endPos);\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\treturn [wireMessage, endPos];\n\t\t}\n\n\t\tfunction writeUint16(input, buffer, offset) {\n\t\t\tbuffer[offset++] = input >> 8; //MSB\n\t\t\tbuffer[offset++] = input % 256; //LSB\n\t\t\treturn offset;\n\t\t}\n\n\t\tfunction writeString(input, utf8Length, buffer, offset) {\n\t\t\toffset = writeUint16(utf8Length, buffer, offset);\n\t\t\tstringToUTF8(input, buffer, offset);\n\t\t\treturn offset + utf8Length;\n\t\t}\n\n\t\tfunction readUint16(buffer, offset) {\n\t\t\treturn 256 * buffer[offset] + buffer[offset + 1];\n\t\t}\n\n\t\t/**\n\t\t * Encodes an MQTT Multi-Byte Integer\n\t\t * @private\n\t\t */\n\t\tfunction encodeMBI(number) {\n\t\t\tvar output = new Array(1);\n\t\t\tvar numBytes = 0;\n\n\t\t\tdo {\n\t\t\t\tvar digit = number % 128;\n\t\t\t\tnumber = number >> 7;\n\t\t\t\tif (number > 0) {\n\t\t\t\t\tdigit |= 0x80;\n\t\t\t\t}\n\t\t\t\toutput[numBytes++] = digit;\n\t\t\t} while (number > 0 && numBytes < 4);\n\n\t\t\treturn output;\n\t\t}\n\n\t\t/**\n\t\t * Takes a String and calculates its length in bytes when encoded in UTF8.\n\t\t * @private\n\t\t */\n\t\tfunction UTF8Length(input) {\n\t\t\tvar output = 0;\n\t\t\tfor (var i = 0; i < input.length; i++) {\n\t\t\t\tvar charCode = input.charCodeAt(i);\n\t\t\t\tif (charCode > 0x7ff) {\n\t\t\t\t\t// Surrogate pair means its a 4 byte character\n\t\t\t\t\tif (0xd800 <= charCode && charCode <= 0xdbff) {\n\t\t\t\t\t\ti++;\n\t\t\t\t\t\toutput++;\n\t\t\t\t\t}\n\t\t\t\t\toutput += 3;\n\t\t\t\t} else if (charCode > 0x7f) output += 2;\n\t\t\t\telse output++;\n\t\t\t}\n\t\t\treturn output;\n\t\t}\n\n\t\t/**\n\t\t * Takes a String and writes it into an array as UTF8 encoded bytes.\n\t\t * @private\n\t\t */\n\t\tfunction stringToUTF8(input, output, start) {\n\t\t\tvar pos = start;\n\t\t\tfor (var i = 0; i < input.length; i++) {\n\t\t\t\tvar charCode = input.charCodeAt(i);\n\n\t\t\t\t// Check for a surrogate pair.\n\t\t\t\tif (0xd800 <= charCode && charCode <= 0xdbff) {\n\t\t\t\t\tvar lowCharCode = input.charCodeAt(++i);\n\t\t\t\t\tif (isNaN(lowCharCode)) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\tformat(ERROR.MALFORMED_UNICODE, [charCode, lowCharCode]),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tcharCode =\n\t\t\t\t\t\t((charCode - 0xd800) << 10) + (lowCharCode - 0xdc00) + 0x10000;\n\t\t\t\t}\n\n\t\t\t\tif (charCode <= 0x7f) {\n\t\t\t\t\toutput[pos++] = charCode;\n\t\t\t\t} else if (charCode <= 0x7ff) {\n\t\t\t\t\toutput[pos++] = ((charCode >> 6) & 0x1f) | 0xc0;\n\t\t\t\t\toutput[pos++] = (charCode & 0x3f) | 0x80;\n\t\t\t\t} else if (charCode <= 0xffff) {\n\t\t\t\t\toutput[pos++] = ((charCode >> 12) & 0x0f) | 0xe0;\n\t\t\t\t\toutput[pos++] = ((charCode >> 6) & 0x3f) | 0x80;\n\t\t\t\t\toutput[pos++] = (charCode & 0x3f) | 0x80;\n\t\t\t\t} else {\n\t\t\t\t\toutput[pos++] = ((charCode >> 18) & 0x07) | 0xf0;\n\t\t\t\t\toutput[pos++] = ((charCode >> 12) & 0x3f) | 0x80;\n\t\t\t\t\toutput[pos++] = ((charCode >> 6) & 0x3f) | 0x80;\n\t\t\t\t\toutput[pos++] = (charCode & 0x3f) | 0x80;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn output;\n\t\t}\n\n\t\tfunction parseUTF8(input, offset, length) {\n\t\t\tvar output = '';\n\t\t\tvar utf16;\n\t\t\tvar pos = offset;\n\n\t\t\twhile (pos < offset + length) {\n\t\t\t\tvar byte1 = input[pos++];\n\t\t\t\tif (byte1 < 128) utf16 = byte1;\n\t\t\t\telse {\n\t\t\t\t\tvar byte2 = input[pos++] - 128;\n\t\t\t\t\tif (byte2 < 0)\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\tformat(ERROR.MALFORMED_UTF, [\n\t\t\t\t\t\t\t\tbyte1.toString(16),\n\t\t\t\t\t\t\t\tbyte2.toString(16),\n\t\t\t\t\t\t\t\t'',\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t);\n\t\t\t\t\tif (byte1 < 0xe0)\n\t\t\t\t\t\t// 2 byte character\n\t\t\t\t\t\tutf16 = 64 * (byte1 - 0xc0) + byte2;\n\t\t\t\t\telse {\n\t\t\t\t\t\tvar byte3 = input[pos++] - 128;\n\t\t\t\t\t\tif (byte3 < 0)\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\tformat(ERROR.MALFORMED_UTF, [\n\t\t\t\t\t\t\t\t\tbyte1.toString(16),\n\t\t\t\t\t\t\t\t\tbyte2.toString(16),\n\t\t\t\t\t\t\t\t\tbyte3.toString(16),\n\t\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\tif (byte1 < 0xf0)\n\t\t\t\t\t\t\t// 3 byte character\n\t\t\t\t\t\t\tutf16 = 4096 * (byte1 - 0xe0) + 64 * byte2 + byte3;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tvar byte4 = input[pos++] - 128;\n\t\t\t\t\t\t\tif (byte4 < 0)\n\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\tformat(ERROR.MALFORMED_UTF, [\n\t\t\t\t\t\t\t\t\t\tbyte1.toString(16),\n\t\t\t\t\t\t\t\t\t\tbyte2.toString(16),\n\t\t\t\t\t\t\t\t\t\tbyte3.toString(16),\n\t\t\t\t\t\t\t\t\t\tbyte4.toString(16),\n\t\t\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (byte1 < 0xf8)\n\t\t\t\t\t\t\t\t// 4 byte character\n\t\t\t\t\t\t\t\tutf16 =\n\t\t\t\t\t\t\t\t\t262144 * (byte1 - 0xf0) + 4096 * byte2 + 64 * byte3 + byte4;\n\t\t\t\t\t\t\t// longer encodings are not supported\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\tformat(ERROR.MALFORMED_UTF, [\n\t\t\t\t\t\t\t\t\t\tbyte1.toString(16),\n\t\t\t\t\t\t\t\t\t\tbyte2.toString(16),\n\t\t\t\t\t\t\t\t\t\tbyte3.toString(16),\n\t\t\t\t\t\t\t\t\t\tbyte4.toString(16),\n\t\t\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (utf16 > 0xffff) {\n\t\t\t\t\t// 4 byte character - express as a surrogate pair\n\t\t\t\t\tutf16 -= 0x10000;\n\t\t\t\t\toutput += String.fromCharCode(0xd800 + (utf16 >> 10)); // lead character\n\t\t\t\t\tutf16 = 0xdc00 + (utf16 & 0x3ff); // trail character\n\t\t\t\t}\n\t\t\t\toutput += String.fromCharCode(utf16);\n\t\t\t}\n\t\t\treturn output;\n\t\t}\n\n\t\t/**\n\t\t * Repeat keepalive requests, monitor responses.\n\t\t * @ignore\n\t\t */\n\t\tvar Pinger = function (client, keepAliveInterval) {\n\t\t\tthis._client = client;\n\t\t\tthis._keepAliveInterval = keepAliveInterval * 1000;\n\t\t\tthis.isReset = false;\n\n\t\t\tvar pingReq = new WireMessage(MESSAGE_TYPE.PINGREQ).encode();\n\n\t\t\tvar doTimeout = function (pinger) {\n\t\t\t\treturn function () {\n\t\t\t\t\treturn doPing.apply(pinger);\n\t\t\t\t};\n\t\t\t};\n\n\t\t\t/** @ignore */\n\t\t\tvar doPing = function () {\n\t\t\t\tif (!this.isReset) {\n\t\t\t\t\tthis._client._trace('Pinger.doPing', 'Timed out');\n\t\t\t\t\tthis._client._disconnected(\n\t\t\t\t\t\tERROR.PING_TIMEOUT.code,\n\t\t\t\t\t\tformat(ERROR.PING_TIMEOUT),\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tthis.isReset = false;\n\t\t\t\t\tthis._client._trace('Pinger.doPing', 'send PINGREQ');\n\t\t\t\t\tthis._client.socket.send(pingReq);\n\t\t\t\t\tthis.timeout = setTimeout(doTimeout(this), this._keepAliveInterval);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tthis.reset = function () {\n\t\t\t\tthis.isReset = true;\n\t\t\t\tclearTimeout(this.timeout);\n\t\t\t\tif (this._keepAliveInterval > 0)\n\t\t\t\t\tthis.timeout = setTimeout(doTimeout(this), this._keepAliveInterval);\n\t\t\t};\n\n\t\t\tthis.cancel = function () {\n\t\t\t\tclearTimeout(this.timeout);\n\t\t\t};\n\t\t};\n\n\t\t/**\n\t\t * Monitor request completion.\n\t\t * @ignore\n\t\t */\n\t\tvar Timeout = function (client, timeoutSeconds, action, args) {\n\t\t\tif (!timeoutSeconds) timeoutSeconds = 30;\n\n\t\t\tvar doTimeout = function (action, client, args) {\n\t\t\t\treturn function () {\n\t\t\t\t\treturn action.apply(client, args);\n\t\t\t\t};\n\t\t\t};\n\t\t\tthis.timeout = setTimeout(\n\t\t\t\tdoTimeout(action, client, args),\n\t\t\t\ttimeoutSeconds * 1000,\n\t\t\t);\n\n\t\t\tthis.cancel = function () {\n\t\t\t\tclearTimeout(this.timeout);\n\t\t\t};\n\t\t};\n\n\t\t/**\n\t\t * Internal implementation of the Websockets MQTT V3.1 client.\n\t\t *\n\t\t * @name Paho.ClientImpl @constructor\n\t\t * @param {String} host the DNS nameof the webSocket host.\n\t\t * @param {Number} port the port number for that host.\n\t\t * @param {String} clientId the MQ client identifier.\n\t\t */\n\t\tvar ClientImpl = function (uri, host, port, path, clientId) {\n\t\t\t// Check dependencies are satisfied in this browser.\n\t\t\tif (!('WebSocket' in global && global.WebSocket !== null)) {\n\t\t\t\tthrow new Error(format(ERROR.UNSUPPORTED, ['WebSocket']));\n\t\t\t}\n\t\t\tif (!('ArrayBuffer' in global && global.ArrayBuffer !== null)) {\n\t\t\t\tthrow new Error(format(ERROR.UNSUPPORTED, ['ArrayBuffer']));\n\t\t\t}\n\t\t\tthis._trace('Paho.Client', uri, host, port, path, clientId);\n\n\t\t\tthis.host = host;\n\t\t\tthis.port = port;\n\t\t\tthis.path = path;\n\t\t\tthis.uri = uri;\n\t\t\tthis.clientId = clientId;\n\t\t\tthis._wsuri = null;\n\n\t\t\t// Local storagekeys are qualified with the following string.\n\t\t\t// The conditional inclusion of path in the key is for backward\n\t\t\t// compatibility to when the path was not configurable and assumed to\n\t\t\t// be /mqtt\n\t\t\tthis._localKey =\n\t\t\t\thost +\n\t\t\t\t':' +\n\t\t\t\tport +\n\t\t\t\t(path != '/mqtt' ? ':' + path : '') +\n\t\t\t\t':' +\n\t\t\t\tclientId +\n\t\t\t\t':';\n\n\t\t\t// Create private instance-only message queue\n\t\t\t// Internal queue of messages to be sent, in sending order.\n\t\t\tthis._msg_queue = [];\n\t\t\tthis._buffered_msg_queue = [];\n\n\t\t\t// Messages we have sent and are expecting a response for, indexed by their respective message ids.\n\t\t\tthis._sentMessages = {};\n\n\t\t\t// Messages we have received and acknowleged and are expecting a confirm message for\n\t\t\t// indexed by their respective message ids.\n\t\t\tthis._receivedMessages = {};\n\n\t\t\t// Internal list of callbacks to be executed when messages\n\t\t\t// have been successfully sent over web socket, e.g. disconnect\n\t\t\t// when it doesn't have to wait for ACK, just message is dispatched.\n\t\t\tthis._notify_msg_sent = {};\n\n\t\t\t// Unique identifier for SEND messages, incrementing\n\t\t\t// counter as messages are sent.\n\t\t\tthis._message_identifier = 1;\n\n\t\t\t// Used to determine the transmission sequence of stored sent messages.\n\t\t\tthis._sequence = 0;\n\n\t\t\t// Load the local state, if any, from the saved version, only restore state relevant to this client.\n\t\t\tfor (var key in localStorage)\n\t\t\t\tif (\n\t\t\t\t\tkey.indexOf('Sent:' + this._localKey) === 0 ||\n\t\t\t\t\tkey.indexOf('Received:' + this._localKey) === 0\n\t\t\t\t)\n\t\t\t\t\tthis.restore(key);\n\t\t};\n\n\t\t// Messaging Client public instance members.\n\t\tClientImpl.prototype.host = null;\n\t\tClientImpl.prototype.port = null;\n\t\tClientImpl.prototype.path = null;\n\t\tClientImpl.prototype.uri = null;\n\t\tClientImpl.prototype.clientId = null;\n\n\t\t// Messaging Client private instance members.\n\t\tClientImpl.prototype.socket = null;\n\t\t/* true once we have received an acknowledgement to a CONNECT packet. */\n\t\tClientImpl.prototype.connected = false;\n\t\t/* The largest message identifier allowed, may not be larger than 2**16 but\n\t\t * if set smaller reduces the maximum number of outbound messages allowed.\n\t\t */\n\t\tClientImpl.prototype.maxMessageIdentifier = 65536;\n\t\tClientImpl.prototype.connectOptions = null;\n\t\tClientImpl.prototype.hostIndex = null;\n\t\tClientImpl.prototype.onConnected = null;\n\t\tClientImpl.prototype.onConnectionLost = null;\n\t\tClientImpl.prototype.onMessageDelivered = null;\n\t\tClientImpl.prototype.onMessageArrived = null;\n\t\tClientImpl.prototype.traceFunction = null;\n\t\tClientImpl.prototype._msg_queue = null;\n\t\tClientImpl.prototype._buffered_msg_queue = null;\n\t\tClientImpl.prototype._connectTimeout = null;\n\t\t/* The sendPinger monitors how long we allow before we send data to prove to the server that we are alive. */\n\t\tClientImpl.prototype.sendPinger = null;\n\t\t/* The receivePinger monitors how long we allow before we require evidence that the server is alive. */\n\t\tClientImpl.prototype.receivePinger = null;\n\t\tClientImpl.prototype._reconnectInterval = 1; // Reconnect Delay, starts at 1 second\n\t\tClientImpl.prototype._reconnecting = false;\n\t\tClientImpl.prototype._reconnectTimeout = null;\n\t\tClientImpl.prototype.disconnectedPublishing = false;\n\t\tClientImpl.prototype.disconnectedBufferSize = 5000;\n\n\t\tClientImpl.prototype.receiveBuffer = null;\n\n\t\tClientImpl.prototype._traceBuffer = null;\n\t\tClientImpl.prototype._MAX_TRACE_ENTRIES = 100;\n\n\t\tClientImpl.prototype.connect = function (connectOptions) {\n\t\t\tvar connectOptionsMasked = this._traceMask(connectOptions, 'password');\n\t\t\tthis._trace(\n\t\t\t\t'Client.connect',\n\t\t\t\tconnectOptionsMasked,\n\t\t\t\tthis.socket,\n\t\t\t\tthis.connected,\n\t\t\t);\n\n\t\t\tif (this.connected)\n\t\t\t\tthrow new Error(format(ERROR.INVALID_STATE, ['already connected']));\n\t\t\tif (this.socket)\n\t\t\t\tthrow new Error(format(ERROR.INVALID_STATE, ['already connected']));\n\n\t\t\tif (this._reconnecting) {\n\t\t\t\t// connect() function is called while reconnect is in progress.\n\t\t\t\t// Terminate the auto reconnect process to use new connect options.\n\t\t\t\tthis._reconnectTimeout.cancel();\n\t\t\t\tthis._reconnectTimeout = null;\n\t\t\t\tthis._reconnecting = false;\n\t\t\t}\n\n\t\t\tthis.connectOptions = connectOptions;\n\t\t\tthis._reconnectInterval = 1;\n\t\t\tthis._reconnecting = false;\n\t\t\tif (connectOptions.uris) {\n\t\t\t\tthis.hostIndex = 0;\n\t\t\t\tthis._doConnect(connectOptions.uris[0]);\n\t\t\t} else {\n\t\t\t\tthis._doConnect(this.uri);\n\t\t\t}\n\t\t};\n\n\t\tClientImpl.prototype.subscribe = function (filter, subscribeOptions) {\n\t\t\tthis._trace('Client.subscribe', filter, subscribeOptions);\n\n\t\t\tif (!this.connected)\n\t\t\t\tthrow new Error(format(ERROR.INVALID_STATE, ['not connected']));\n\n\t\t\tvar wireMessage = new WireMessage(MESSAGE_TYPE.SUBSCRIBE);\n\t\t\twireMessage.topics = filter.constructor === Array ? filter : [filter];\n\t\t\tif (subscribeOptions.qos === undefined) subscribeOptions.qos = 0;\n\t\t\twireMessage.requestedQos = [];\n\t\t\tfor (var i = 0; i < wireMessage.topics.length; i++)\n\t\t\t\twireMessage.requestedQos[i] = subscribeOptions.qos;\n\n\t\t\tif (subscribeOptions.onSuccess) {\n\t\t\t\twireMessage.onSuccess = function (grantedQos) {\n\t\t\t\t\tsubscribeOptions.onSuccess({\n\t\t\t\t\t\tinvocationContext: subscribeOptions.invocationContext,\n\t\t\t\t\t\tgrantedQos: grantedQos,\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (subscribeOptions.onFailure) {\n\t\t\t\twireMessage.onFailure = function (errorCode) {\n\t\t\t\t\tsubscribeOptions.onFailure({\n\t\t\t\t\t\tinvocationContext: subscribeOptions.invocationContext,\n\t\t\t\t\t\terrorCode: errorCode,\n\t\t\t\t\t\terrorMessage: format(errorCode),\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (subscribeOptions.timeout) {\n\t\t\t\twireMessage.timeOut = new Timeout(\n\t\t\t\t\tthis,\n\t\t\t\t\tsubscribeOptions.timeout,\n\t\t\t\t\tsubscribeOptions.onFailure,\n\t\t\t\t\t[\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tinvocationContext: subscribeOptions.invocationContext,\n\t\t\t\t\t\t\terrorCode: ERROR.SUBSCRIBE_TIMEOUT.code,\n\t\t\t\t\t\t\terrorMessage: format(ERROR.SUBSCRIBE_TIMEOUT),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// All subscriptions return a SUBACK.\n\t\t\tthis._requires_ack(wireMessage);\n\t\t\tthis._schedule_message(wireMessage);\n\t\t};\n\n\t\t/** @ignore */\n\t\tClientImpl.prototype.unsubscribe = function (filter, unsubscribeOptions) {\n\t\t\tthis._trace('Client.unsubscribe', filter, unsubscribeOptions);\n\n\t\t\tif (!this.connected)\n\t\t\t\tthrow new Error(format(ERROR.INVALID_STATE, ['not connected']));\n\n\t\t\tvar wireMessage = new WireMessage(MESSAGE_TYPE.UNSUBSCRIBE);\n\t\t\twireMessage.topics = filter.constructor === Array ? filter : [filter];\n\n\t\t\tif (unsubscribeOptions.onSuccess) {\n\t\t\t\twireMessage.callback = function () {\n\t\t\t\t\tunsubscribeOptions.onSuccess({\n\t\t\t\t\t\tinvocationContext: unsubscribeOptions.invocationContext,\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (unsubscribeOptions.timeout) {\n\t\t\t\twireMessage.timeOut = new Timeout(\n\t\t\t\t\tthis,\n\t\t\t\t\tunsubscribeOptions.timeout,\n\t\t\t\t\tunsubscribeOptions.onFailure,\n\t\t\t\t\t[\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tinvocationContext: unsubscribeOptions.invocationContext,\n\t\t\t\t\t\t\terrorCode: ERROR.UNSUBSCRIBE_TIMEOUT.code,\n\t\t\t\t\t\t\terrorMessage: format(ERROR.UNSUBSCRIBE_TIMEOUT),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// All unsubscribes return a SUBACK.\n\t\t\tthis._requires_ack(wireMessage);\n\t\t\tthis._schedule_message(wireMessage);\n\t\t};\n\n\t\tClientImpl.prototype.send = function (message) {\n\t\t\tthis._trace('Client.send', message);\n\n\t\t\tvar wireMessage = new WireMessage(MESSAGE_TYPE.PUBLISH);\n\t\t\twireMessage.payloadMessage = message;\n\n\t\t\tif (this.connected) {\n\t\t\t\t// Mark qos 1 & 2 message as \"ACK required\"\n\t\t\t\t// For qos 0 message, invoke onMessageDelivered callback if there is one.\n\t\t\t\t// Then schedule the message.\n\t\t\t\tif (message.qos > 0) {\n\t\t\t\t\tthis._requires_ack(wireMessage);\n\t\t\t\t} else if (this.onMessageDelivered) {\n\t\t\t\t\tthis._notify_msg_sent[wireMessage] = this.onMessageDelivered(\n\t\t\t\t\t\twireMessage.payloadMessage,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthis._schedule_message(wireMessage);\n\t\t\t} else {\n\t\t\t\t// Currently disconnected, will not schedule this message\n\t\t\t\t// Check if reconnecting is in progress and disconnected publish is enabled.\n\t\t\t\tif (this._reconnecting && this.disconnectedPublishing) {\n\t\t\t\t\t// Check the limit which include the \"required ACK\" messages\n\t\t\t\t\tvar messageCount =\n\t\t\t\t\t\tObject.keys(this._sentMessages).length +\n\t\t\t\t\t\tthis._buffered_msg_queue.length;\n\t\t\t\t\tif (messageCount > this.disconnectedBufferSize) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\tformat(ERROR.BUFFER_FULL, [this.disconnectedBufferSize]),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (message.qos > 0) {\n\t\t\t\t\t\t\t// Mark this message as \"ACK required\"\n\t\t\t\t\t\t\tthis._requires_ack(wireMessage);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\twireMessage.sequence = ++this._sequence;\n\t\t\t\t\t\t\t// Add messages in fifo order to array, by adding to start\n\t\t\t\t\t\t\tthis._buffered_msg_queue.unshift(wireMessage);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error(format(ERROR.INVALID_STATE, ['not connected']));\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tClientImpl.prototype.disconnect = function () {\n\t\t\tthis._trace('Client.disconnect');\n\n\t\t\tif (this._reconnecting) {\n\t\t\t\t// disconnect() function is called while reconnect is in progress.\n\t\t\t\t// Terminate the auto reconnect process.\n\t\t\t\tthis._reconnectTimeout.cancel();\n\t\t\t\tthis._reconnectTimeout = null;\n\t\t\t\tthis._reconnecting = false;\n\t\t\t}\n\n\t\t\tif (!this.socket)\n\t\t\t\tthrow new Error(\n\t\t\t\t\tformat(ERROR.INVALID_STATE, ['not connecting or connected']),\n\t\t\t\t);\n\n\t\t\tvar wireMessage = new WireMessage(MESSAGE_TYPE.DISCONNECT);\n\n\t\t\t// Run the disconnected call back as soon as the message has been sent,\n\t\t\t// in case of a failure later on in the disconnect processing.\n\t\t\t// as a consequence, the _disconected call back may be run several times.\n\t\t\tthis._notify_msg_sent[wireMessage] = scope(this._disconnected, this);\n\n\t\t\tthis._schedule_message(wireMessage);\n\t\t};\n\n\t\tClientImpl.prototype.getTraceLog = function () {\n\t\t\tif (this._traceBuffer !== null) {\n\t\t\t\tthis._trace('Client.getTraceLog', new Date());\n\t\t\t\tthis._trace(\n\t\t\t\t\t'Client.getTraceLog in flight messages',\n\t\t\t\t\tthis._sentMessages.length,\n\t\t\t\t);\n\t\t\t\tfor (var key in this._sentMessages)\n\t\t\t\t\tthis._trace('_sentMessages ', key, this._sentMessages[key]);\n\t\t\t\tfor (var key in this._receivedMessages)\n\t\t\t\t\tthis._trace('_receivedMessages ', key, this._receivedMessages[key]);\n\n\t\t\t\treturn this._traceBuffer;\n\t\t\t}\n\t\t};\n\n\t\tClientImpl.prototype.startTrace = function () {\n\t\t\tif (this._traceBuffer === null) {\n\t\t\t\tthis._traceBuffer = [];\n\t\t\t}\n\t\t\tthis._trace('Client.startTrace', new Date(), version);\n\t\t};\n\n\t\tClientImpl.prototype.stopTrace = function () {\n\t\t\tdelete this._traceBuffer;\n\t\t};\n\n\t\tClientImpl.prototype._doConnect = function (wsurl) {\n\t\t\t// When the socket is open, this client will send the CONNECT WireMessage using the saved parameters.\n\t\t\tif (this.connectOptions.useSSL) {\n\t\t\t\tvar uriParts = wsurl.split(':');\n\t\t\t\turiParts[0] = 'wss';\n\t\t\t\twsurl = uriParts.join(':');\n\t\t\t}\n\t\t\tthis._wsuri = wsurl;\n\t\t\tthis.connected = false;\n\n\t\t\tif (this.connectOptions.mqttVersion < 4) {\n\t\t\t\tthis.socket = new WebSocket(wsurl, ['mqttv3.1']);\n\t\t\t} else {\n\t\t\t\tthis.socket = new WebSocket(wsurl, ['mqtt']);\n\t\t\t}\n\t\t\tthis.socket.binaryType = 'arraybuffer';\n\t\t\tthis.socket.onopen = scope(this._on_socket_open, this);\n\t\t\tthis.socket.onmessage = scope(this._on_socket_message, this);\n\t\t\tthis.socket.onerror = scope(this._on_socket_error, this);\n\t\t\tthis.socket.onclose = scope(this._on_socket_close, this);\n\n\t\t\tthis.sendPinger = new Pinger(this, this.connectOptions.keepAliveInterval);\n\t\t\tthis.receivePinger = new Pinger(\n\t\t\t\tthis,\n\t\t\t\tthis.connectOptions.keepAliveInterval,\n\t\t\t);\n\t\t\tif (this._connectTimeout) {\n\t\t\t\tthis._connectTimeout.cancel();\n\t\t\t\tthis._connectTimeout = null;\n\t\t\t}\n\t\t\tthis._connectTimeout = new Timeout(\n\t\t\t\tthis,\n\t\t\t\tthis.connectOptions.timeout,\n\t\t\t\tthis._disconnected,\n\t\t\t\t[ERROR.CONNECT_TIMEOUT.code, format(ERROR.CONNECT_TIMEOUT)],\n\t\t\t);\n\t\t};\n\n\t\t// Schedule a new message to be sent over the WebSockets\n\t\t// connection. CONNECT messages cause WebSocket connection\n\t\t// to be started. All other messages are queued internally\n\t\t// until this has happened. When WS connection starts, process\n\t\t// all outstanding messages.\n\t\tClientImpl.prototype._schedule_message = function (message) {\n\t\t\t// Add messages in fifo order to array, by adding to start\n\t\t\tthis._msg_queue.unshift(message);\n\t\t\t// Process outstanding messages in the queue if we have an open socket, and have received CONNACK.\n\t\t\tif (this.connected) {\n\t\t\t\tthis._process_queue();\n\t\t\t}\n\t\t};\n\n\t\tClientImpl.prototype.store = function (prefix, wireMessage) {\n\t\t\tvar storedMessage = {\n\t\t\t\ttype: wireMessage.type,\n\t\t\t\tmessageIdentifier: wireMessage.messageIdentifier,\n\t\t\t\tversion: 1,\n\t\t\t};\n\n\t\t\tswitch (wireMessage.type) {\n\t\t\t\tcase MESSAGE_TYPE.PUBLISH:\n\t\t\t\t\tif (wireMessage.pubRecReceived) storedMessage.pubRecReceived = true;\n\n\t\t\t\t\t// Convert the payload to a hex string.\n\t\t\t\t\tstoredMessage.payloadMessage = {};\n\t\t\t\t\tvar hex = '';\n\t\t\t\t\tvar messageBytes = wireMessage.payloadMessage.payloadBytes;\n\t\t\t\t\tfor (var i = 0; i < messageBytes.length; i++) {\n\t\t\t\t\t\tif (messageBytes[i] <= 0xf)\n\t\t\t\t\t\t\thex = hex + '0' + messageBytes[i].toString(16);\n\t\t\t\t\t\telse hex = hex + messageBytes[i].toString(16);\n\t\t\t\t\t}\n\t\t\t\t\tstoredMessage.payloadMessage.payloadHex = hex;\n\n\t\t\t\t\tstoredMessage.payloadMessage.qos = wireMessage.payloadMessage.qos;\n\t\t\t\t\tstoredMessage.payloadMessage.destinationName =\n\t\t\t\t\t\twireMessage.payloadMessage.destinationName;\n\t\t\t\t\tif (wireMessage.payloadMessage.duplicate)\n\t\t\t\t\t\tstoredMessage.payloadMessage.duplicate = true;\n\t\t\t\t\tif (wireMessage.payloadMessage.retained)\n\t\t\t\t\t\tstoredMessage.payloadMessage.retained = true;\n\n\t\t\t\t\t// Add a sequence number to sent messages.\n\t\t\t\t\tif (prefix.indexOf('Sent:') === 0) {\n\t\t\t\t\t\tif (wireMessage.sequence === undefined)\n\t\t\t\t\t\t\twireMessage.sequence = ++this._sequence;\n\t\t\t\t\t\tstoredMessage.sequence = wireMessage.sequence;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tthrow Error(\n\t\t\t\t\t\tformat(ERROR.INVALID_STORED_DATA, [\n\t\t\t\t\t\t\tprefix + this._localKey + wireMessage.messageIdentifier,\n\t\t\t\t\t\t\tstoredMessage,\n\t\t\t\t\t\t]),\n\t\t\t\t\t);\n\t\t\t}\n\t\t\tlocalStorage.setItem(\n\t\t\t\tprefix + this._localKey + wireMessage.messageIdentifier,\n\t\t\t\tJSON.stringify(storedMessage),\n\t\t\t);\n\t\t};\n\n\t\tClientImpl.prototype.restore = function (key) {\n\t\t\tvar value = localStorage.getItem(key);\n\t\t\tvar storedMessage = JSON.parse(value);\n\n\t\t\tvar wireMessage = new WireMessage(storedMessage.type, storedMessage);\n\n\t\t\tswitch (storedMessage.type) {\n\t\t\t\tcase MESSAGE_TYPE.PUBLISH:\n\t\t\t\t\t// Replace the payload message with a Message object.\n\t\t\t\t\tvar hex = storedMessage.payloadMessage.payloadHex;\n\t\t\t\t\tvar buffer = new ArrayBuffer(hex.length / 2);\n\t\t\t\t\tvar byteStream = new Uint8Array(buffer);\n\t\t\t\t\tvar i = 0;\n\t\t\t\t\twhile (hex.length >= 2) {\n\t\t\t\t\t\tvar x = parseInt(hex.substring(0, 2), 16);\n\t\t\t\t\t\thex = hex.substring(2, hex.length);\n\t\t\t\t\t\tbyteStream[i++] = x;\n\t\t\t\t\t}\n\t\t\t\t\tvar payloadMessage = new Message(byteStream);\n\n\t\t\t\t\tpayloadMessage.qos = storedMessage.payloadMessage.qos;\n\t\t\t\t\tpayloadMessage.destinationName =\n\t\t\t\t\t\tstoredMessage.payloadMessage.destinationName;\n\t\t\t\t\tif (storedMessage.payloadMessage.duplicate)\n\t\t\t\t\t\tpayloadMessage.duplicate = true;\n\t\t\t\t\tif (storedMessage.payloadMessage.retained)\n\t\t\t\t\t\tpayloadMessage.retained = true;\n\t\t\t\t\twireMessage.payloadMessage = payloadMessage;\n\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tthrow Error(format(ERROR.INVALID_STORED_DATA, [key, value]));\n\t\t\t}\n\n\t\t\tif (key.indexOf('Sent:' + this._localKey) === 0) {\n\t\t\t\twireMessage.payloadMessage.duplicate = true;\n\t\t\t\tthis._sentMessages[wireMessage.messageIdentifier] = wireMessage;\n\t\t\t} else if (key.indexOf('Received:' + this._localKey) === 0) {\n\t\t\t\tthis._receivedMessages[wireMessage.messageIdentifier] = wireMessage;\n\t\t\t}\n\t\t};\n\n\t\tClientImpl.prototype._process_queue = function () {\n\t\t\tvar message = null;\n\n\t\t\t// Send all queued messages down socket connection\n\t\t\twhile ((message = this._msg_queue.pop())) {\n\t\t\t\tthis._socket_send(message);\n\t\t\t\t// Notify listeners that message was successfully sent\n\t\t\t\tif (this._notify_msg_sent[message]) {\n\t\t\t\t\tthis._notify_msg_sent[message]();\n\t\t\t\t\tdelete this._notify_msg_sent[message];\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t/**\n\t\t * Expect an ACK response for this message. Add message to the set of in progress\n\t\t * messages and set an unused identifier in this message.\n\t\t * @ignore\n\t\t */\n\t\tClientImpl.prototype._requires_ack = function (wireMessage) {\n\t\t\tvar messageCount = Object.keys(this._sentMessages).length;\n\t\t\tif (messageCount > this.maxMessageIdentifier)\n\t\t\t\tthrow Error('Too many messages:' + messageCount);\n\n\t\t\twhile (this._sentMessages[this._message_identifier] !== undefined) {\n\t\t\t\tthis._message_identifier++;\n\t\t\t}\n\t\t\twireMessage.messageIdentifier = this._message_identifier;\n\t\t\tthis._sentMessages[wireMessage.messageIdentifier] = wireMessage;\n\t\t\tif (wireMessage.type === MESSAGE_TYPE.PUBLISH) {\n\t\t\t\tthis.store('Sent:', wireMessage);\n\t\t\t}\n\t\t\tif (this._message_identifier === this.maxMessageIdentifier) {\n\t\t\t\tthis._message_identifier = 1;\n\t\t\t}\n\t\t};\n\n\t\t/**\n\t\t * Called when the underlying websocket has been opened.\n\t\t * @ignore\n\t\t */\n\t\tClientImpl.prototype._on_socket_open = function () {\n\t\t\t// Create the CONNECT message object.\n\t\t\tvar wireMessage = new WireMessage(\n\t\t\t\tMESSAGE_TYPE.CONNECT,\n\t\t\t\tthis.connectOptions,\n\t\t\t);\n\t\t\twireMessage.clientId = this.clientId;\n\t\t\tthis._socket_send(wireMessage);\n\t\t};\n\n\t\t/**\n\t\t * Called when the underlying websocket has received a complete packet.\n\t\t * @ignore\n\t\t */\n\t\tClientImpl.prototype._on_socket_message = function (event) {\n\t\t\tthis._trace('Client._on_socket_message', event.data);\n\t\t\tvar messages = this._deframeMessages(event.data);\n\t\t\tfor (var i = 0; i < messages.length; i += 1) {\n\t\t\t\tthis._handleMessage(messages[i]);\n\t\t\t}\n\t\t};\n\n\t\tClientImpl.prototype._deframeMessages = function (data) {\n\t\t\tvar byteArray = new Uint8Array(data);\n\t\t\tvar messages = [];\n\t\t\tif (this.receiveBuffer) {\n\t\t\t\tvar newDat