UNPKG

94.8 kBJavaScriptView Raw
1/*******************************************************************************
2 * Copyright (c) 2013 IBM Corp.
3 *
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * and Eclipse Distribution License v1.0 which accompany this distribution.
7 *
8 * The Eclipse Public License is available at
9 * http://www.eclipse.org/legal/epl-v10.html
10 * and the Eclipse Distribution License is available at
11 * http://www.eclipse.org/org/documents/edl-v10.php.
12 *
13 * Contributors:
14 * Andrew Banks - initial API and implementation and initial documentation
15 *******************************************************************************/
16
17// Only expose a single object name in the global namespace.
18// Everything must go through this module. Global Paho module
19// only has a single public function, client, which returns
20// a Paho client object given connection details.
21
22/**
23 * Send and receive messages using web browsers.
24 * <p>
25 * This programming interface lets a JavaScript client application use the MQTT V3.1 or
26 * V3.1.1 protocol to connect to an MQTT-supporting messaging server.
27 *
28 * The function supported includes:
29 * <ol>
30 * <li>Connecting to and disconnecting from a server. The server is identified by its host name and port number.
31 * <li>Specifying options that relate to the communications link with the server,
32 * for example the frequency of keep-alive heartbeats, and whether SSL/TLS is required.
33 * <li>Subscribing to and receiving messages from MQTT Topics.
34 * <li>Publishing messages to MQTT Topics.
35 * </ol>
36 * <p>
37 * The API consists of two main objects:
38 * <dl>
39 * <dt><b>{@link Paho.Client}</b></dt>
40 * <dd>This contains methods that provide the functionality of the API,
41 * including provision of callbacks that notify the application when a message
42 * arrives from or is delivered to the messaging server,
43 * or when the status of its connection to the messaging server changes.</dd>
44 * <dt><b>{@link Paho.Message}</b></dt>
45 * <dd>This encapsulates the payload of the message along with various attributes
46 * associated with its delivery, in particular the destination to which it has
47 * been (or is about to be) sent.</dd>
48 * </dl>
49 * <p>
50 * The programming interface validates parameters passed to it, and will throw
51 * an Error containing an error message intended for developer use, if it detects
52 * an error with any parameter.
53 * <p>
54 * Example:
55 *
56 * <code><pre>
57var client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId");
58client.onConnectionLost = onConnectionLost;
59client.onMessageArrived = onMessageArrived;
60client.connect({onSuccess:onConnect});
61
62function onConnect() {
63 // Once a connection has been made, make a subscription and send a message.
64 console.log("onConnect");
65 client.subscribe("/World");
66 var message = new Paho.MQTT.Message("Hello");
67 message.destinationName = "/World";
68 client.send(message);
69};
70function onConnectionLost(responseObject) {
71 if (responseObject.errorCode !== 0)
72 console.log("onConnectionLost:"+responseObject.errorMessage);
73};
74function onMessageArrived(message) {
75 console.log("onMessageArrived:"+message.payloadString);
76 client.disconnect();
77};
78 * </pre></code>
79 * @namespace Paho
80 */
81
82/* jshint shadow:true */
83(function ExportLibrary(root, factory) {
84 if (typeof exports === 'object' && typeof module === 'object') {
85 module.exports = factory();
86 } else if (typeof define === 'function' && define.amd) {
87 define(factory);
88 } else if (typeof exports === 'object') {
89 exports = factory();
90 } else {
91 //if (typeof root.Paho === "undefined"){
92 // root.Paho = {};
93 //}
94 root.Paho = factory();
95 }
96})(this, function LibraryFactory() {
97 var PahoMQTT = (function (global) {
98 // Private variables below, these are only visible inside the function closure
99 // which is used to define the module.
100 var version = '@VERSION@-@BUILDLEVEL@';
101
102 // 2023-01-05: AWS Amplify change to incorporate upstream pull request:
103 // https://github.com/eclipse/paho.mqtt.javascript/pull/247
104
105 /**
106 * @private
107 */
108 var localStorage = (function () {
109 try {
110 // When third-party cookies are disabled accessing localStorage will cause an error
111 if (global.localStorage) return global.localStorage;
112 } catch (e) {
113 var data = {};
114
115 return {
116 setItem: function (key, item) {
117 data[key] = item;
118 },
119 getItem: function (key) {
120 return data[key];
121 },
122 removeItem: function (key) {
123 delete data[key];
124 },
125 };
126 }
127 })();
128
129 // End of AWS Amplify change
130
131 /**
132 * Unique message type identifiers, with associated
133 * associated integer values.
134 * @private
135 */
136 var MESSAGE_TYPE = {
137 CONNECT: 1,
138 CONNACK: 2,
139 PUBLISH: 3,
140 PUBACK: 4,
141 PUBREC: 5,
142 PUBREL: 6,
143 PUBCOMP: 7,
144 SUBSCRIBE: 8,
145 SUBACK: 9,
146 UNSUBSCRIBE: 10,
147 UNSUBACK: 11,
148 PINGREQ: 12,
149 PINGRESP: 13,
150 DISCONNECT: 14,
151 };
152
153 // Collection of utility methods used to simplify module code
154 // and promote the DRY pattern.
155
156 /**
157 * Validate an object's parameter names to ensure they
158 * match a list of expected variables name for this option
159 * type. Used to ensure option object passed into the API don't
160 * contain erroneous parameters.
161 * @param {Object} obj - User options object
162 * @param {Object} keys - valid keys and types that may exist in obj.
163 * @throws {Error} Invalid option parameter found.
164 * @private
165 */
166 var validate = function (obj, keys) {
167 for (var key in obj) {
168 if (obj.hasOwnProperty(key)) {
169 if (keys.hasOwnProperty(key)) {
170 if (typeof obj[key] !== keys[key])
171 throw new Error(
172 format(ERROR.INVALID_TYPE, [typeof obj[key], key])
173 );
174 } else {
175 var errorStr =
176 'Unknown property, ' + key + '. Valid properties are:';
177 for (var validKey in keys)
178 if (keys.hasOwnProperty(validKey))
179 errorStr = errorStr + ' ' + validKey;
180 throw new Error(errorStr);
181 }
182 }
183 }
184 };
185
186 /**
187 * Return a new function which runs the user function bound
188 * to a fixed scope.
189 * @param {function} User function
190 * @param {object} Function scope
191 * @return {function} User function bound to another scope
192 * @private
193 */
194 var scope = function (f, scope) {
195 return function () {
196 return f.apply(scope, arguments);
197 };
198 };
199
200 /**
201 * Unique message type identifiers, with associated
202 * associated integer values.
203 * @private
204 */
205 var ERROR = {
206 OK: { code: 0, text: 'AMQJSC0000I OK.' },
207 CONNECT_TIMEOUT: { code: 1, text: 'AMQJSC0001E Connect timed out.' },
208 SUBSCRIBE_TIMEOUT: { code: 2, text: 'AMQJS0002E Subscribe timed out.' },
209 UNSUBSCRIBE_TIMEOUT: {
210 code: 3,
211 text: 'AMQJS0003E Unsubscribe timed out.',
212 },
213 PING_TIMEOUT: { code: 4, text: 'AMQJS0004E Ping timed out.' },
214 INTERNAL_ERROR: {
215 code: 5,
216 text: 'AMQJS0005E Internal error. Error Message: {0}, Stack trace: {1}',
217 },
218 CONNACK_RETURNCODE: {
219 code: 6,
220 text: 'AMQJS0006E Bad Connack return code:{0} {1}.',
221 },
222 SOCKET_ERROR: { code: 7, text: 'AMQJS0007E Socket error:{0}.' },
223 SOCKET_CLOSE: { code: 8, text: 'AMQJS0008I Socket closed.' },
224 MALFORMED_UTF: {
225 code: 9,
226 text: 'AMQJS0009E Malformed UTF data:{0} {1} {2}.',
227 },
228 UNSUPPORTED: {
229 code: 10,
230 text: 'AMQJS0010E {0} is not supported by this browser.',
231 },
232 INVALID_STATE: { code: 11, text: 'AMQJS0011E Invalid state {0}.' },
233 INVALID_TYPE: { code: 12, text: 'AMQJS0012E Invalid type {0} for {1}.' },
234 INVALID_ARGUMENT: {
235 code: 13,
236 text: 'AMQJS0013E Invalid argument {0} for {1}.',
237 },
238 UNSUPPORTED_OPERATION: {
239 code: 14,
240 text: 'AMQJS0014E Unsupported operation.',
241 },
242 INVALID_STORED_DATA: {
243 code: 15,
244 text: 'AMQJS0015E Invalid data in local storage key={0} value={1}.',
245 },
246 INVALID_MQTT_MESSAGE_TYPE: {
247 code: 16,
248 text: 'AMQJS0016E Invalid MQTT message type {0}.',
249 },
250 MALFORMED_UNICODE: {
251 code: 17,
252 text: 'AMQJS0017E Malformed Unicode string:{0} {1}.',
253 },
254 BUFFER_FULL: {
255 code: 18,
256 text: 'AMQJS0018E Message buffer is full, maximum buffer size: {0}.',
257 },
258 };
259
260 /** CONNACK RC Meaning. */
261 var CONNACK_RC = {
262 0: 'Connection Accepted',
263 1: 'Connection Refused: unacceptable protocol version',
264 2: 'Connection Refused: identifier rejected',
265 3: 'Connection Refused: server unavailable',
266 4: 'Connection Refused: bad user name or password',
267 5: 'Connection Refused: not authorized',
268 };
269
270 /**
271 * Format an error message text.
272 * @private
273 * @param {error} ERROR value above.
274 * @param {substitutions} [array] substituted into the text.
275 * @return the text with the substitutions made.
276 */
277 var format = function (error, substitutions) {
278 var text = error.text;
279 if (substitutions) {
280 var field, start;
281 for (var i = 0; i < substitutions.length; i++) {
282 field = '{' + i + '}';
283 start = text.indexOf(field);
284 if (start > 0) {
285 var part1 = text.substring(0, start);
286 var part2 = text.substring(start + field.length);
287 text = part1 + substitutions[i] + part2;
288 }
289 }
290 }
291 return text;
292 };
293
294 //MQTT protocol and version 6 M Q I s d p 3
295 var MqttProtoIdentifierv3 = [
296 0x00, 0x06, 0x4d, 0x51, 0x49, 0x73, 0x64, 0x70, 0x03,
297 ];
298 //MQTT proto/version for 311 4 M Q T T 4
299 var MqttProtoIdentifierv4 = [0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x04];
300
301 /**
302 * Construct an MQTT wire protocol message.
303 * @param type MQTT packet type.
304 * @param options optional wire message attributes.
305 *
306 * Optional properties
307 *
308 * messageIdentifier: message ID in the range [0..65535]
309 * payloadMessage: Application Message - PUBLISH only
310 * connectStrings: array of 0 or more Strings to be put into the CONNECT payload
311 * topics: array of strings (SUBSCRIBE, UNSUBSCRIBE)
312 * requestQoS: array of QoS values [0..2]
313 *
314 * "Flag" properties
315 * cleanSession: true if present / false if absent (CONNECT)
316 * willMessage: true if present / false if absent (CONNECT)
317 * isRetained: true if present / false if absent (CONNECT)
318 * userName: true if present / false if absent (CONNECT)
319 * password: true if present / false if absent (CONNECT)
320 * keepAliveInterval: integer [0..65535] (CONNECT)
321 *
322 * @private
323 * @ignore
324 */
325 var WireMessage = function (type, options) {
326 this.type = type;
327 for (var name in options) {
328 if (options.hasOwnProperty(name)) {
329 this[name] = options[name];
330 }
331 }
332 };
333
334 WireMessage.prototype.encode = function () {
335 // Compute the first byte of the fixed header
336 var first = (this.type & 0x0f) << 4;
337
338 /*
339 * Now calculate the length of the variable header + payload by adding up the lengths
340 * of all the component parts
341 */
342
343 var remLength = 0;
344 var topicStrLength = [];
345 var destinationNameLength = 0;
346 var willMessagePayloadBytes;
347
348 // if the message contains a messageIdentifier then we need two bytes for that
349 if (this.messageIdentifier !== undefined) remLength += 2;
350
351 switch (this.type) {
352 // If this a Connect then we need to include 12 bytes for its header
353 case MESSAGE_TYPE.CONNECT:
354 switch (this.mqttVersion) {
355 case 3:
356 remLength += MqttProtoIdentifierv3.length + 3;
357 break;
358 case 4:
359 remLength += MqttProtoIdentifierv4.length + 3;
360 break;
361 }
362
363 remLength += UTF8Length(this.clientId) + 2;
364 if (this.willMessage !== undefined) {
365 remLength += UTF8Length(this.willMessage.destinationName) + 2;
366 // Will message is always a string, sent as UTF-8 characters with a preceding length.
367 willMessagePayloadBytes = this.willMessage.payloadBytes;
368 if (!(willMessagePayloadBytes instanceof Uint8Array))
369 willMessagePayloadBytes = new Uint8Array(payloadBytes);
370 remLength += willMessagePayloadBytes.byteLength + 2;
371 }
372 if (this.userName !== undefined)
373 remLength += UTF8Length(this.userName) + 2;
374 if (this.password !== undefined)
375 remLength += UTF8Length(this.password) + 2;
376 break;
377
378 // Subscribe, Unsubscribe can both contain topic strings
379 case MESSAGE_TYPE.SUBSCRIBE:
380 first |= 0x02; // Qos = 1;
381 for (var i = 0; i < this.topics.length; i++) {
382 topicStrLength[i] = UTF8Length(this.topics[i]);
383 remLength += topicStrLength[i] + 2;
384 }
385 remLength += this.requestedQos.length; // 1 byte for each topic's Qos
386 // QoS on Subscribe only
387 break;
388
389 case MESSAGE_TYPE.UNSUBSCRIBE:
390 first |= 0x02; // Qos = 1;
391 for (var i = 0; i < this.topics.length; i++) {
392 topicStrLength[i] = UTF8Length(this.topics[i]);
393 remLength += topicStrLength[i] + 2;
394 }
395 break;
396
397 case MESSAGE_TYPE.PUBREL:
398 first |= 0x02; // Qos = 1;
399 break;
400
401 case MESSAGE_TYPE.PUBLISH:
402 if (this.payloadMessage.duplicate) first |= 0x08;
403 first = first |= this.payloadMessage.qos << 1;
404 if (this.payloadMessage.retained) first |= 0x01;
405 destinationNameLength = UTF8Length(
406 this.payloadMessage.destinationName
407 );
408 remLength += destinationNameLength + 2;
409 var payloadBytes = this.payloadMessage.payloadBytes;
410 remLength += payloadBytes.byteLength;
411 if (payloadBytes instanceof ArrayBuffer)
412 payloadBytes = new Uint8Array(payloadBytes);
413 else if (!(payloadBytes instanceof Uint8Array))
414 payloadBytes = new Uint8Array(payloadBytes.buffer);
415 break;
416
417 case MESSAGE_TYPE.DISCONNECT:
418 break;
419
420 default:
421 break;
422 }
423
424 // Now we can allocate a buffer for the message
425
426 var mbi = encodeMBI(remLength); // Convert the length to MQTT MBI format
427 var pos = mbi.length + 1; // Offset of start of variable header
428 var buffer = new ArrayBuffer(remLength + pos);
429 var byteStream = new Uint8Array(buffer); // view it as a sequence of bytes
430
431 //Write the fixed header into the buffer
432 byteStream[0] = first;
433 byteStream.set(mbi, 1);
434
435 // If this is a PUBLISH then the variable header starts with a topic
436 if (this.type == MESSAGE_TYPE.PUBLISH)
437 pos = writeString(
438 this.payloadMessage.destinationName,
439 destinationNameLength,
440 byteStream,
441 pos
442 );
443 // If this is a CONNECT then the variable header contains the protocol name/version, flags and keepalive time
444 else if (this.type == MESSAGE_TYPE.CONNECT) {
445 switch (this.mqttVersion) {
446 case 3:
447 byteStream.set(MqttProtoIdentifierv3, pos);
448 pos += MqttProtoIdentifierv3.length;
449 break;
450 case 4:
451 byteStream.set(MqttProtoIdentifierv4, pos);
452 pos += MqttProtoIdentifierv4.length;
453 break;
454 }
455 var connectFlags = 0;
456 if (this.cleanSession) connectFlags = 0x02;
457 if (this.willMessage !== undefined) {
458 connectFlags |= 0x04;
459 connectFlags |= this.willMessage.qos << 3;
460 if (this.willMessage.retained) {
461 connectFlags |= 0x20;
462 }
463 }
464 if (this.userName !== undefined) connectFlags |= 0x80;
465 if (this.password !== undefined) connectFlags |= 0x40;
466 byteStream[pos++] = connectFlags;
467 pos = writeUint16(this.keepAliveInterval, byteStream, pos);
468 }
469
470 // Output the messageIdentifier - if there is one
471 if (this.messageIdentifier !== undefined)
472 pos = writeUint16(this.messageIdentifier, byteStream, pos);
473
474 switch (this.type) {
475 case MESSAGE_TYPE.CONNECT:
476 pos = writeString(
477 this.clientId,
478 UTF8Length(this.clientId),
479 byteStream,
480 pos
481 );
482 if (this.willMessage !== undefined) {
483 pos = writeString(
484 this.willMessage.destinationName,
485 UTF8Length(this.willMessage.destinationName),
486 byteStream,
487 pos
488 );
489 pos = writeUint16(
490 willMessagePayloadBytes.byteLength,
491 byteStream,
492 pos
493 );
494 byteStream.set(willMessagePayloadBytes, pos);
495 pos += willMessagePayloadBytes.byteLength;
496 }
497 if (this.userName !== undefined)
498 pos = writeString(
499 this.userName,
500 UTF8Length(this.userName),
501 byteStream,
502 pos
503 );
504 if (this.password !== undefined)
505 pos = writeString(
506 this.password,
507 UTF8Length(this.password),
508 byteStream,
509 pos
510 );
511 break;
512
513 case MESSAGE_TYPE.PUBLISH:
514 // PUBLISH has a text or binary payload, if text do not add a 2 byte length field, just the UTF characters.
515 byteStream.set(payloadBytes, pos);
516
517 break;
518
519 // case MESSAGE_TYPE.PUBREC:
520 // case MESSAGE_TYPE.PUBREL:
521 // case MESSAGE_TYPE.PUBCOMP:
522 // break;
523
524 case MESSAGE_TYPE.SUBSCRIBE:
525 // SUBSCRIBE has a list of topic strings and request QoS
526 for (var i = 0; i < this.topics.length; i++) {
527 pos = writeString(
528 this.topics[i],
529 topicStrLength[i],
530 byteStream,
531 pos
532 );
533 byteStream[pos++] = this.requestedQos[i];
534 }
535 break;
536
537 case MESSAGE_TYPE.UNSUBSCRIBE:
538 // UNSUBSCRIBE has a list of topic strings
539 for (var i = 0; i < this.topics.length; i++)
540 pos = writeString(
541 this.topics[i],
542 topicStrLength[i],
543 byteStream,
544 pos
545 );
546 break;
547
548 default:
549 // Do nothing.
550 }
551
552 return buffer;
553 };
554
555 function decodeMessage(input, pos) {
556 var startingPos = pos;
557 var first = input[pos];
558 var type = first >> 4;
559 var messageInfo = (first &= 0x0f);
560 pos += 1;
561
562 // Decode the remaining length (MBI format)
563
564 var digit;
565 var remLength = 0;
566 var multiplier = 1;
567 do {
568 if (pos == input.length) {
569 return [null, startingPos];
570 }
571 digit = input[pos++];
572 remLength += (digit & 0x7f) * multiplier;
573 multiplier *= 128;
574 } while ((digit & 0x80) !== 0);
575
576 var endPos = pos + remLength;
577 if (endPos > input.length) {
578 return [null, startingPos];
579 }
580
581 var wireMessage = new WireMessage(type);
582 switch (type) {
583 case MESSAGE_TYPE.CONNACK:
584 var connectAcknowledgeFlags = input[pos++];
585 if (connectAcknowledgeFlags & 0x01) wireMessage.sessionPresent = true;
586 wireMessage.returnCode = input[pos++];
587 break;
588
589 case MESSAGE_TYPE.PUBLISH:
590 var qos = (messageInfo >> 1) & 0x03;
591
592 var len = readUint16(input, pos);
593 pos += 2;
594 var topicName = parseUTF8(input, pos, len);
595 pos += len;
596 // If QoS 1 or 2 there will be a messageIdentifier
597 if (qos > 0) {
598 wireMessage.messageIdentifier = readUint16(input, pos);
599 pos += 2;
600 }
601
602 var message = new Message(input.subarray(pos, endPos));
603 if ((messageInfo & 0x01) == 0x01) message.retained = true;
604 if ((messageInfo & 0x08) == 0x08) message.duplicate = true;
605 message.qos = qos;
606 message.destinationName = topicName;
607 wireMessage.payloadMessage = message;
608 break;
609
610 case MESSAGE_TYPE.PUBACK:
611 case MESSAGE_TYPE.PUBREC:
612 case MESSAGE_TYPE.PUBREL:
613 case MESSAGE_TYPE.PUBCOMP:
614 case MESSAGE_TYPE.UNSUBACK:
615 wireMessage.messageIdentifier = readUint16(input, pos);
616 break;
617
618 case MESSAGE_TYPE.SUBACK:
619 wireMessage.messageIdentifier = readUint16(input, pos);
620 pos += 2;
621 wireMessage.returnCode = input.subarray(pos, endPos);
622 break;
623
624 default:
625 break;
626 }
627
628 return [wireMessage, endPos];
629 }
630
631 function writeUint16(input, buffer, offset) {
632 buffer[offset++] = input >> 8; //MSB
633 buffer[offset++] = input % 256; //LSB
634 return offset;
635 }
636
637 function writeString(input, utf8Length, buffer, offset) {
638 offset = writeUint16(utf8Length, buffer, offset);
639 stringToUTF8(input, buffer, offset);
640 return offset + utf8Length;
641 }
642
643 function readUint16(buffer, offset) {
644 return 256 * buffer[offset] + buffer[offset + 1];
645 }
646
647 /**
648 * Encodes an MQTT Multi-Byte Integer
649 * @private
650 */
651 function encodeMBI(number) {
652 var output = new Array(1);
653 var numBytes = 0;
654
655 do {
656 var digit = number % 128;
657 number = number >> 7;
658 if (number > 0) {
659 digit |= 0x80;
660 }
661 output[numBytes++] = digit;
662 } while (number > 0 && numBytes < 4);
663
664 return output;
665 }
666
667 /**
668 * Takes a String and calculates its length in bytes when encoded in UTF8.
669 * @private
670 */
671 function UTF8Length(input) {
672 var output = 0;
673 for (var i = 0; i < input.length; i++) {
674 var charCode = input.charCodeAt(i);
675 if (charCode > 0x7ff) {
676 // Surrogate pair means its a 4 byte character
677 if (0xd800 <= charCode && charCode <= 0xdbff) {
678 i++;
679 output++;
680 }
681 output += 3;
682 } else if (charCode > 0x7f) output += 2;
683 else output++;
684 }
685 return output;
686 }
687
688 /**
689 * Takes a String and writes it into an array as UTF8 encoded bytes.
690 * @private
691 */
692 function stringToUTF8(input, output, start) {
693 var pos = start;
694 for (var i = 0; i < input.length; i++) {
695 var charCode = input.charCodeAt(i);
696
697 // Check for a surrogate pair.
698 if (0xd800 <= charCode && charCode <= 0xdbff) {
699 var lowCharCode = input.charCodeAt(++i);
700 if (isNaN(lowCharCode)) {
701 throw new Error(
702 format(ERROR.MALFORMED_UNICODE, [charCode, lowCharCode])
703 );
704 }
705 charCode =
706 ((charCode - 0xd800) << 10) + (lowCharCode - 0xdc00) + 0x10000;
707 }
708
709 if (charCode <= 0x7f) {
710 output[pos++] = charCode;
711 } else if (charCode <= 0x7ff) {
712 output[pos++] = ((charCode >> 6) & 0x1f) | 0xc0;
713 output[pos++] = (charCode & 0x3f) | 0x80;
714 } else if (charCode <= 0xffff) {
715 output[pos++] = ((charCode >> 12) & 0x0f) | 0xe0;
716 output[pos++] = ((charCode >> 6) & 0x3f) | 0x80;
717 output[pos++] = (charCode & 0x3f) | 0x80;
718 } else {
719 output[pos++] = ((charCode >> 18) & 0x07) | 0xf0;
720 output[pos++] = ((charCode >> 12) & 0x3f) | 0x80;
721 output[pos++] = ((charCode >> 6) & 0x3f) | 0x80;
722 output[pos++] = (charCode & 0x3f) | 0x80;
723 }
724 }
725 return output;
726 }
727
728 function parseUTF8(input, offset, length) {
729 var output = '';
730 var utf16;
731 var pos = offset;
732
733 while (pos < offset + length) {
734 var byte1 = input[pos++];
735 if (byte1 < 128) utf16 = byte1;
736 else {
737 var byte2 = input[pos++] - 128;
738 if (byte2 < 0)
739 throw new Error(
740 format(ERROR.MALFORMED_UTF, [
741 byte1.toString(16),
742 byte2.toString(16),
743 '',
744 ])
745 );
746 if (byte1 < 0xe0)
747 // 2 byte character
748 utf16 = 64 * (byte1 - 0xc0) + byte2;
749 else {
750 var byte3 = input[pos++] - 128;
751 if (byte3 < 0)
752 throw new Error(
753 format(ERROR.MALFORMED_UTF, [
754 byte1.toString(16),
755 byte2.toString(16),
756 byte3.toString(16),
757 ])
758 );
759 if (byte1 < 0xf0)
760 // 3 byte character
761 utf16 = 4096 * (byte1 - 0xe0) + 64 * byte2 + byte3;
762 else {
763 var byte4 = input[pos++] - 128;
764 if (byte4 < 0)
765 throw new Error(
766 format(ERROR.MALFORMED_UTF, [
767 byte1.toString(16),
768 byte2.toString(16),
769 byte3.toString(16),
770 byte4.toString(16),
771 ])
772 );
773 if (byte1 < 0xf8)
774 // 4 byte character
775 utf16 =
776 262144 * (byte1 - 0xf0) + 4096 * byte2 + 64 * byte3 + byte4;
777 // longer encodings are not supported
778 else
779 throw new Error(
780 format(ERROR.MALFORMED_UTF, [
781 byte1.toString(16),
782 byte2.toString(16),
783 byte3.toString(16),
784 byte4.toString(16),
785 ])
786 );
787 }
788 }
789 }
790
791 if (utf16 > 0xffff) {
792 // 4 byte character - express as a surrogate pair
793 utf16 -= 0x10000;
794 output += String.fromCharCode(0xd800 + (utf16 >> 10)); // lead character
795 utf16 = 0xdc00 + (utf16 & 0x3ff); // trail character
796 }
797 output += String.fromCharCode(utf16);
798 }
799 return output;
800 }
801
802 /**
803 * Repeat keepalive requests, monitor responses.
804 * @ignore
805 */
806 var Pinger = function (client, keepAliveInterval) {
807 this._client = client;
808 this._keepAliveInterval = keepAliveInterval * 1000;
809 this.isReset = false;
810
811 var pingReq = new WireMessage(MESSAGE_TYPE.PINGREQ).encode();
812
813 var doTimeout = function (pinger) {
814 return function () {
815 return doPing.apply(pinger);
816 };
817 };
818
819 /** @ignore */
820 var doPing = function () {
821 if (!this.isReset) {
822 this._client._trace('Pinger.doPing', 'Timed out');
823 this._client._disconnected(
824 ERROR.PING_TIMEOUT.code,
825 format(ERROR.PING_TIMEOUT)
826 );
827 } else {
828 this.isReset = false;
829 this._client._trace('Pinger.doPing', 'send PINGREQ');
830 this._client.socket.send(pingReq);
831 this.timeout = setTimeout(doTimeout(this), this._keepAliveInterval);
832 }
833 };
834
835 this.reset = function () {
836 this.isReset = true;
837 clearTimeout(this.timeout);
838 if (this._keepAliveInterval > 0)
839 this.timeout = setTimeout(doTimeout(this), this._keepAliveInterval);
840 };
841
842 this.cancel = function () {
843 clearTimeout(this.timeout);
844 };
845 };
846
847 /**
848 * Monitor request completion.
849 * @ignore
850 */
851 var Timeout = function (client, timeoutSeconds, action, args) {
852 if (!timeoutSeconds) timeoutSeconds = 30;
853
854 var doTimeout = function (action, client, args) {
855 return function () {
856 return action.apply(client, args);
857 };
858 };
859 this.timeout = setTimeout(
860 doTimeout(action, client, args),
861 timeoutSeconds * 1000
862 );
863
864 this.cancel = function () {
865 clearTimeout(this.timeout);
866 };
867 };
868
869 /**
870 * Internal implementation of the Websockets MQTT V3.1 client.
871 *
872 * @name Paho.ClientImpl @constructor
873 * @param {String} host the DNS nameof the webSocket host.
874 * @param {Number} port the port number for that host.
875 * @param {String} clientId the MQ client identifier.
876 */
877 var ClientImpl = function (uri, host, port, path, clientId) {
878 // Check dependencies are satisfied in this browser.
879 if (!('WebSocket' in global && global.WebSocket !== null)) {
880 throw new Error(format(ERROR.UNSUPPORTED, ['WebSocket']));
881 }
882 if (!('ArrayBuffer' in global && global.ArrayBuffer !== null)) {
883 throw new Error(format(ERROR.UNSUPPORTED, ['ArrayBuffer']));
884 }
885 this._trace('Paho.Client', uri, host, port, path, clientId);
886
887 this.host = host;
888 this.port = port;
889 this.path = path;
890 this.uri = uri;
891 this.clientId = clientId;
892 this._wsuri = null;
893
894 // Local storagekeys are qualified with the following string.
895 // The conditional inclusion of path in the key is for backward
896 // compatibility to when the path was not configurable and assumed to
897 // be /mqtt
898 this._localKey =
899 host +
900 ':' +
901 port +
902 (path != '/mqtt' ? ':' + path : '') +
903 ':' +
904 clientId +
905 ':';
906
907 // Create private instance-only message queue
908 // Internal queue of messages to be sent, in sending order.
909 this._msg_queue = [];
910 this._buffered_msg_queue = [];
911
912 // Messages we have sent and are expecting a response for, indexed by their respective message ids.
913 this._sentMessages = {};
914
915 // Messages we have received and acknowleged and are expecting a confirm message for
916 // indexed by their respective message ids.
917 this._receivedMessages = {};
918
919 // Internal list of callbacks to be executed when messages
920 // have been successfully sent over web socket, e.g. disconnect
921 // when it doesn't have to wait for ACK, just message is dispatched.
922 this._notify_msg_sent = {};
923
924 // Unique identifier for SEND messages, incrementing
925 // counter as messages are sent.
926 this._message_identifier = 1;
927
928 // Used to determine the transmission sequence of stored sent messages.
929 this._sequence = 0;
930
931 // Load the local state, if any, from the saved version, only restore state relevant to this client.
932 for (var key in localStorage)
933 if (
934 key.indexOf('Sent:' + this._localKey) === 0 ||
935 key.indexOf('Received:' + this._localKey) === 0
936 )
937 this.restore(key);
938 };
939
940 // Messaging Client public instance members.
941 ClientImpl.prototype.host = null;
942 ClientImpl.prototype.port = null;
943 ClientImpl.prototype.path = null;
944 ClientImpl.prototype.uri = null;
945 ClientImpl.prototype.clientId = null;
946
947 // Messaging Client private instance members.
948 ClientImpl.prototype.socket = null;
949 /* true once we have received an acknowledgement to a CONNECT packet. */
950 ClientImpl.prototype.connected = false;
951 /* The largest message identifier allowed, may not be larger than 2**16 but
952 * if set smaller reduces the maximum number of outbound messages allowed.
953 */
954 ClientImpl.prototype.maxMessageIdentifier = 65536;
955 ClientImpl.prototype.connectOptions = null;
956 ClientImpl.prototype.hostIndex = null;
957 ClientImpl.prototype.onConnected = null;
958 ClientImpl.prototype.onConnectionLost = null;
959 ClientImpl.prototype.onMessageDelivered = null;
960 ClientImpl.prototype.onMessageArrived = null;
961 ClientImpl.prototype.traceFunction = null;
962 ClientImpl.prototype._msg_queue = null;
963 ClientImpl.prototype._buffered_msg_queue = null;
964 ClientImpl.prototype._connectTimeout = null;
965 /* The sendPinger monitors how long we allow before we send data to prove to the server that we are alive. */
966 ClientImpl.prototype.sendPinger = null;
967 /* The receivePinger monitors how long we allow before we require evidence that the server is alive. */
968 ClientImpl.prototype.receivePinger = null;
969 ClientImpl.prototype._reconnectInterval = 1; // Reconnect Delay, starts at 1 second
970 ClientImpl.prototype._reconnecting = false;
971 ClientImpl.prototype._reconnectTimeout = null;
972 ClientImpl.prototype.disconnectedPublishing = false;
973 ClientImpl.prototype.disconnectedBufferSize = 5000;
974
975 ClientImpl.prototype.receiveBuffer = null;
976
977 ClientImpl.prototype._traceBuffer = null;
978 ClientImpl.prototype._MAX_TRACE_ENTRIES = 100;
979
980 ClientImpl.prototype.connect = function (connectOptions) {
981 var connectOptionsMasked = this._traceMask(connectOptions, 'password');
982 this._trace(
983 'Client.connect',
984 connectOptionsMasked,
985 this.socket,
986 this.connected
987 );
988
989 if (this.connected)
990 throw new Error(format(ERROR.INVALID_STATE, ['already connected']));
991 if (this.socket)
992 throw new Error(format(ERROR.INVALID_STATE, ['already connected']));
993
994 if (this._reconnecting) {
995 // connect() function is called while reconnect is in progress.
996 // Terminate the auto reconnect process to use new connect options.
997 this._reconnectTimeout.cancel();
998 this._reconnectTimeout = null;
999 this._reconnecting = false;
1000 }
1001
1002 this.connectOptions = connectOptions;
1003 this._reconnectInterval = 1;
1004 this._reconnecting = false;
1005 if (connectOptions.uris) {
1006 this.hostIndex = 0;
1007 this._doConnect(connectOptions.uris[0]);
1008 } else {
1009 this._doConnect(this.uri);
1010 }
1011 };
1012
1013 ClientImpl.prototype.subscribe = function (filter, subscribeOptions) {
1014 this._trace('Client.subscribe', filter, subscribeOptions);
1015
1016 if (!this.connected)
1017 throw new Error(format(ERROR.INVALID_STATE, ['not connected']));
1018
1019 var wireMessage = new WireMessage(MESSAGE_TYPE.SUBSCRIBE);
1020 wireMessage.topics = filter.constructor === Array ? filter : [filter];
1021 if (subscribeOptions.qos === undefined) subscribeOptions.qos = 0;
1022 wireMessage.requestedQos = [];
1023 for (var i = 0; i < wireMessage.topics.length; i++)
1024 wireMessage.requestedQos[i] = subscribeOptions.qos;
1025
1026 if (subscribeOptions.onSuccess) {
1027 wireMessage.onSuccess = function (grantedQos) {
1028 subscribeOptions.onSuccess({
1029 invocationContext: subscribeOptions.invocationContext,
1030 grantedQos: grantedQos,
1031 });
1032 };
1033 }
1034
1035 if (subscribeOptions.onFailure) {
1036 wireMessage.onFailure = function (errorCode) {
1037 subscribeOptions.onFailure({
1038 invocationContext: subscribeOptions.invocationContext,
1039 errorCode: errorCode,
1040 errorMessage: format(errorCode),
1041 });
1042 };
1043 }
1044
1045 if (subscribeOptions.timeout) {
1046 wireMessage.timeOut = new Timeout(
1047 this,
1048 subscribeOptions.timeout,
1049 subscribeOptions.onFailure,
1050 [
1051 {
1052 invocationContext: subscribeOptions.invocationContext,
1053 errorCode: ERROR.SUBSCRIBE_TIMEOUT.code,
1054 errorMessage: format(ERROR.SUBSCRIBE_TIMEOUT),
1055 },
1056 ]
1057 );
1058 }
1059
1060 // All subscriptions return a SUBACK.
1061 this._requires_ack(wireMessage);
1062 this._schedule_message(wireMessage);
1063 };
1064
1065 /** @ignore */
1066 ClientImpl.prototype.unsubscribe = function (filter, unsubscribeOptions) {
1067 this._trace('Client.unsubscribe', filter, unsubscribeOptions);
1068
1069 if (!this.connected)
1070 throw new Error(format(ERROR.INVALID_STATE, ['not connected']));
1071
1072 var wireMessage = new WireMessage(MESSAGE_TYPE.UNSUBSCRIBE);
1073 wireMessage.topics = filter.constructor === Array ? filter : [filter];
1074
1075 if (unsubscribeOptions.onSuccess) {
1076 wireMessage.callback = function () {
1077 unsubscribeOptions.onSuccess({
1078 invocationContext: unsubscribeOptions.invocationContext,
1079 });
1080 };
1081 }
1082 if (unsubscribeOptions.timeout) {
1083 wireMessage.timeOut = new Timeout(
1084 this,
1085 unsubscribeOptions.timeout,
1086 unsubscribeOptions.onFailure,
1087 [
1088 {
1089 invocationContext: unsubscribeOptions.invocationContext,
1090 errorCode: ERROR.UNSUBSCRIBE_TIMEOUT.code,
1091 errorMessage: format(ERROR.UNSUBSCRIBE_TIMEOUT),
1092 },
1093 ]
1094 );
1095 }
1096
1097 // All unsubscribes return a SUBACK.
1098 this._requires_ack(wireMessage);
1099 this._schedule_message(wireMessage);
1100 };
1101
1102 ClientImpl.prototype.send = function (message) {
1103 this._trace('Client.send', message);
1104
1105 var wireMessage = new WireMessage(MESSAGE_TYPE.PUBLISH);
1106 wireMessage.payloadMessage = message;
1107
1108 if (this.connected) {
1109 // Mark qos 1 & 2 message as "ACK required"
1110 // For qos 0 message, invoke onMessageDelivered callback if there is one.
1111 // Then schedule the message.
1112 if (message.qos > 0) {
1113 this._requires_ack(wireMessage);
1114 } else if (this.onMessageDelivered) {
1115 this._notify_msg_sent[wireMessage] = this.onMessageDelivered(
1116 wireMessage.payloadMessage
1117 );
1118 }
1119 this._schedule_message(wireMessage);
1120 } else {
1121 // Currently disconnected, will not schedule this message
1122 // Check if reconnecting is in progress and disconnected publish is enabled.
1123 if (this._reconnecting && this.disconnectedPublishing) {
1124 // Check the limit which include the "required ACK" messages
1125 var messageCount =
1126 Object.keys(this._sentMessages).length +
1127 this._buffered_msg_queue.length;
1128 if (messageCount > this.disconnectedBufferSize) {
1129 throw new Error(
1130 format(ERROR.BUFFER_FULL, [this.disconnectedBufferSize])
1131 );
1132 } else {
1133 if (message.qos > 0) {
1134 // Mark this message as "ACK required"
1135 this._requires_ack(wireMessage);
1136 } else {
1137 wireMessage.sequence = ++this._sequence;
1138 // Add messages in fifo order to array, by adding to start
1139 this._buffered_msg_queue.unshift(wireMessage);
1140 }
1141 }
1142 } else {
1143 throw new Error(format(ERROR.INVALID_STATE, ['not connected']));
1144 }
1145 }
1146 };
1147
1148 ClientImpl.prototype.disconnect = function () {
1149 this._trace('Client.disconnect');
1150
1151 if (this._reconnecting) {
1152 // disconnect() function is called while reconnect is in progress.
1153 // Terminate the auto reconnect process.
1154 this._reconnectTimeout.cancel();
1155 this._reconnectTimeout = null;
1156 this._reconnecting = false;
1157 }
1158
1159 if (!this.socket)
1160 throw new Error(
1161 format(ERROR.INVALID_STATE, ['not connecting or connected'])
1162 );
1163
1164 var wireMessage = new WireMessage(MESSAGE_TYPE.DISCONNECT);
1165
1166 // Run the disconnected call back as soon as the message has been sent,
1167 // in case of a failure later on in the disconnect processing.
1168 // as a consequence, the _disconected call back may be run several times.
1169 this._notify_msg_sent[wireMessage] = scope(this._disconnected, this);
1170
1171 this._schedule_message(wireMessage);
1172 };
1173
1174 ClientImpl.prototype.getTraceLog = function () {
1175 if (this._traceBuffer !== null) {
1176 this._trace('Client.getTraceLog', new Date());
1177 this._trace(
1178 'Client.getTraceLog in flight messages',
1179 this._sentMessages.length
1180 );
1181 for (var key in this._sentMessages)
1182 this._trace('_sentMessages ', key, this._sentMessages[key]);
1183 for (var key in this._receivedMessages)
1184 this._trace('_receivedMessages ', key, this._receivedMessages[key]);
1185
1186 return this._traceBuffer;
1187 }
1188 };
1189
1190 ClientImpl.prototype.startTrace = function () {
1191 if (this._traceBuffer === null) {
1192 this._traceBuffer = [];
1193 }
1194 this._trace('Client.startTrace', new Date(), version);
1195 };
1196
1197 ClientImpl.prototype.stopTrace = function () {
1198 delete this._traceBuffer;
1199 };
1200
1201 ClientImpl.prototype._doConnect = function (wsurl) {
1202 // When the socket is open, this client will send the CONNECT WireMessage using the saved parameters.
1203 if (this.connectOptions.useSSL) {
1204 var uriParts = wsurl.split(':');
1205 uriParts[0] = 'wss';
1206 wsurl = uriParts.join(':');
1207 }
1208 this._wsuri = wsurl;
1209 this.connected = false;
1210
1211 if (this.connectOptions.mqttVersion < 4) {
1212 this.socket = new WebSocket(wsurl, ['mqttv3.1']);
1213 } else {
1214 this.socket = new WebSocket(wsurl, ['mqtt']);
1215 }
1216 this.socket.binaryType = 'arraybuffer';
1217 this.socket.onopen = scope(this._on_socket_open, this);
1218 this.socket.onmessage = scope(this._on_socket_message, this);
1219 this.socket.onerror = scope(this._on_socket_error, this);
1220 this.socket.onclose = scope(this._on_socket_close, this);
1221
1222 this.sendPinger = new Pinger(this, this.connectOptions.keepAliveInterval);
1223 this.receivePinger = new Pinger(
1224 this,
1225 this.connectOptions.keepAliveInterval
1226 );
1227 if (this._connectTimeout) {
1228 this._connectTimeout.cancel();
1229 this._connectTimeout = null;
1230 }
1231 this._connectTimeout = new Timeout(
1232 this,
1233 this.connectOptions.timeout,
1234 this._disconnected,
1235 [ERROR.CONNECT_TIMEOUT.code, format(ERROR.CONNECT_TIMEOUT)]
1236 );
1237 };
1238
1239 // Schedule a new message to be sent over the WebSockets
1240 // connection. CONNECT messages cause WebSocket connection
1241 // to be started. All other messages are queued internally
1242 // until this has happened. When WS connection starts, process
1243 // all outstanding messages.
1244 ClientImpl.prototype._schedule_message = function (message) {
1245 // Add messages in fifo order to array, by adding to start
1246 this._msg_queue.unshift(message);
1247 // Process outstanding messages in the queue if we have an open socket, and have received CONNACK.
1248 if (this.connected) {
1249 this._process_queue();
1250 }
1251 };
1252
1253 ClientImpl.prototype.store = function (prefix, wireMessage) {
1254 var storedMessage = {
1255 type: wireMessage.type,
1256 messageIdentifier: wireMessage.messageIdentifier,
1257 version: 1,
1258 };
1259
1260 switch (wireMessage.type) {
1261 case MESSAGE_TYPE.PUBLISH:
1262 if (wireMessage.pubRecReceived) storedMessage.pubRecReceived = true;
1263
1264 // Convert the payload to a hex string.
1265 storedMessage.payloadMessage = {};
1266 var hex = '';
1267 var messageBytes = wireMessage.payloadMessage.payloadBytes;
1268 for (var i = 0; i < messageBytes.length; i++) {
1269 if (messageBytes[i] <= 0xf)
1270 hex = hex + '0' + messageBytes[i].toString(16);
1271 else hex = hex + messageBytes[i].toString(16);
1272 }
1273 storedMessage.payloadMessage.payloadHex = hex;
1274
1275 storedMessage.payloadMessage.qos = wireMessage.payloadMessage.qos;
1276 storedMessage.payloadMessage.destinationName =
1277 wireMessage.payloadMessage.destinationName;
1278 if (wireMessage.payloadMessage.duplicate)
1279 storedMessage.payloadMessage.duplicate = true;
1280 if (wireMessage.payloadMessage.retained)
1281 storedMessage.payloadMessage.retained = true;
1282
1283 // Add a sequence number to sent messages.
1284 if (prefix.indexOf('Sent:') === 0) {
1285 if (wireMessage.sequence === undefined)
1286 wireMessage.sequence = ++this._sequence;
1287 storedMessage.sequence = wireMessage.sequence;
1288 }
1289 break;
1290
1291 default:
1292 throw Error(
1293 format(ERROR.INVALID_STORED_DATA, [
1294 prefix + this._localKey + wireMessage.messageIdentifier,
1295 storedMessage,
1296 ])
1297 );
1298 }
1299 localStorage.setItem(
1300 prefix + this._localKey + wireMessage.messageIdentifier,
1301 JSON.stringify(storedMessage)
1302 );
1303 };
1304
1305 ClientImpl.prototype.restore = function (key) {
1306 var value = localStorage.getItem(key);
1307 var storedMessage = JSON.parse(value);
1308
1309 var wireMessage = new WireMessage(storedMessage.type, storedMessage);
1310
1311 switch (storedMessage.type) {
1312 case MESSAGE_TYPE.PUBLISH:
1313 // Replace the payload message with a Message object.
1314 var hex = storedMessage.payloadMessage.payloadHex;
1315 var buffer = new ArrayBuffer(hex.length / 2);
1316 var byteStream = new Uint8Array(buffer);
1317 var i = 0;
1318 while (hex.length >= 2) {
1319 var x = parseInt(hex.substring(0, 2), 16);
1320 hex = hex.substring(2, hex.length);
1321 byteStream[i++] = x;
1322 }
1323 var payloadMessage = new Message(byteStream);
1324
1325 payloadMessage.qos = storedMessage.payloadMessage.qos;
1326 payloadMessage.destinationName =
1327 storedMessage.payloadMessage.destinationName;
1328 if (storedMessage.payloadMessage.duplicate)
1329 payloadMessage.duplicate = true;
1330 if (storedMessage.payloadMessage.retained)
1331 payloadMessage.retained = true;
1332 wireMessage.payloadMessage = payloadMessage;
1333
1334 break;
1335
1336 default:
1337 throw Error(format(ERROR.INVALID_STORED_DATA, [key, value]));
1338 }
1339
1340 if (key.indexOf('Sent:' + this._localKey) === 0) {
1341 wireMessage.payloadMessage.duplicate = true;
1342 this._sentMessages[wireMessage.messageIdentifier] = wireMessage;
1343 } else if (key.indexOf('Received:' + this._localKey) === 0) {
1344 this._receivedMessages[wireMessage.messageIdentifier] = wireMessage;
1345 }
1346 };
1347
1348 ClientImpl.prototype._process_queue = function () {
1349 var message = null;
1350
1351 // Send all queued messages down socket connection
1352 while ((message = this._msg_queue.pop())) {
1353 this._socket_send(message);
1354 // Notify listeners that message was successfully sent
1355 if (this._notify_msg_sent[message]) {
1356 this._notify_msg_sent[message]();
1357 delete this._notify_msg_sent[message];
1358 }
1359 }
1360 };
1361
1362 /**
1363 * Expect an ACK response for this message. Add message to the set of in progress
1364 * messages and set an unused identifier in this message.
1365 * @ignore
1366 */
1367 ClientImpl.prototype._requires_ack = function (wireMessage) {
1368 var messageCount = Object.keys(this._sentMessages).length;
1369 if (messageCount > this.maxMessageIdentifier)
1370 throw Error('Too many messages:' + messageCount);
1371
1372 while (this._sentMessages[this._message_identifier] !== undefined) {
1373 this._message_identifier++;
1374 }
1375 wireMessage.messageIdentifier = this._message_identifier;
1376 this._sentMessages[wireMessage.messageIdentifier] = wireMessage;
1377 if (wireMessage.type === MESSAGE_TYPE.PUBLISH) {
1378 this.store('Sent:', wireMessage);
1379 }
1380 if (this._message_identifier === this.maxMessageIdentifier) {
1381 this._message_identifier = 1;
1382 }
1383 };
1384
1385 /**
1386 * Called when the underlying websocket has been opened.
1387 * @ignore
1388 */
1389 ClientImpl.prototype._on_socket_open = function () {
1390 // Create the CONNECT message object.
1391 var wireMessage = new WireMessage(
1392 MESSAGE_TYPE.CONNECT,
1393 this.connectOptions
1394 );
1395 wireMessage.clientId = this.clientId;
1396 this._socket_send(wireMessage);
1397 };
1398
1399 /**
1400 * Called when the underlying websocket has received a complete packet.
1401 * @ignore
1402 */
1403 ClientImpl.prototype._on_socket_message = function (event) {
1404 this._trace('Client._on_socket_message', event.data);
1405 var messages = this._deframeMessages(event.data);
1406 for (var i = 0; i < messages.length; i += 1) {
1407 this._handleMessage(messages[i]);
1408 }
1409 };
1410
1411 ClientImpl.prototype._deframeMessages = function (data) {
1412 var byteArray = new Uint8Array(data);
1413 var messages = [];
1414 if (this.receiveBuffer) {
1415 var newData = new Uint8Array(
1416 this.receiveBuffer.length + byteArray.length
1417 );
1418 newData.set(this.receiveBuffer);
1419 newData.set(byteArray, this.receiveBuffer.length);
1420 byteArray = newData;
1421 delete this.receiveBuffer;
1422 }
1423 try {
1424 var offset = 0;
1425 while (offset < byteArray.length) {
1426 var result = decodeMessage(byteArray, offset);
1427 var wireMessage = result[0];
1428 offset = result[1];
1429 if (wireMessage !== null) {
1430 messages.push(wireMessage);
1431 } else {
1432 break;
1433 }
1434 }
1435 if (offset < byteArray.length) {
1436 this.receiveBuffer = byteArray.subarray(offset);
1437 }
1438 } catch (error) {
1439 var errorStack =
1440 error.hasOwnProperty('stack') == 'undefined'
1441 ? error.stack.toString()
1442 : 'No Error Stack Available';
1443 this._disconnected(
1444 ERROR.INTERNAL_ERROR.code,
1445 format(ERROR.INTERNAL_ERROR, [error.message, errorStack])
1446 );
1447 return;
1448 }
1449 return messages;
1450 };
1451
1452 ClientImpl.prototype._handleMessage = function (wireMessage) {
1453 this._trace('Client._handleMessage', wireMessage);
1454
1455 try {
1456 switch (wireMessage.type) {
1457 case MESSAGE_TYPE.CONNACK:
1458 this._connectTimeout.cancel();
1459 if (this._reconnectTimeout) this._reconnectTimeout.cancel();
1460
1461 // If we have started using clean session then clear up the local state.
1462 if (this.connectOptions.cleanSession) {
1463 for (var key in this._sentMessages) {
1464 var sentMessage = this._sentMessages[key];
1465 localStorage.removeItem(
1466 'Sent:' + this._localKey + sentMessage.messageIdentifier
1467 );
1468 }
1469 this._sentMessages = {};
1470
1471 for (var key in this._receivedMessages) {
1472 var receivedMessage = this._receivedMessages[key];
1473 localStorage.removeItem(
1474 'Received:' +
1475 this._localKey +
1476 receivedMessage.messageIdentifier
1477 );
1478 }
1479 this._receivedMessages = {};
1480 }
1481 // Client connected and ready for business.
1482 if (wireMessage.returnCode === 0) {
1483 this.connected = true;
1484 // Jump to the end of the list of uris and stop looking for a good host.
1485
1486 if (this.connectOptions.uris)
1487 this.hostIndex = this.connectOptions.uris.length;
1488 } else {
1489 this._disconnected(
1490 ERROR.CONNACK_RETURNCODE.code,
1491 format(ERROR.CONNACK_RETURNCODE, [
1492 wireMessage.returnCode,
1493 CONNACK_RC[wireMessage.returnCode],
1494 ])
1495 );
1496 break;
1497 }
1498
1499 // Resend messages.
1500 var sequencedMessages = [];
1501 for (var msgId in this._sentMessages) {
1502 if (this._sentMessages.hasOwnProperty(msgId))
1503 sequencedMessages.push(this._sentMessages[msgId]);
1504 }
1505
1506 // Also schedule qos 0 buffered messages if any
1507 if (this._buffered_msg_queue.length > 0) {
1508 var msg = null;
1509 while ((msg = this._buffered_msg_queue.pop())) {
1510 sequencedMessages.push(msg);
1511 if (this.onMessageDelivered)
1512 this._notify_msg_sent[msg] = this.onMessageDelivered(
1513 msg.payloadMessage
1514 );
1515 }
1516 }
1517
1518 // Sort sentMessages into the original sent order.
1519 var sequencedMessages = sequencedMessages.sort(function (a, b) {
1520 return a.sequence - b.sequence;
1521 });
1522 for (var i = 0, len = sequencedMessages.length; i < len; i++) {
1523 var sentMessage = sequencedMessages[i];
1524 if (
1525 sentMessage.type == MESSAGE_TYPE.PUBLISH &&
1526 sentMessage.pubRecReceived
1527 ) {
1528 var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {
1529 messageIdentifier: sentMessage.messageIdentifier,
1530 });
1531 this._schedule_message(pubRelMessage);
1532 } else {
1533 this._schedule_message(sentMessage);
1534 }
1535 }
1536
1537 // Execute the connectOptions.onSuccess callback if there is one.
1538 // Will also now return if this connection was the result of an automatic
1539 // reconnect and which URI was successfully connected to.
1540 if (this.connectOptions.onSuccess) {
1541 this.connectOptions.onSuccess({
1542 invocationContext: this.connectOptions.invocationContext,
1543 });
1544 }
1545
1546 var reconnected = false;
1547 if (this._reconnecting) {
1548 reconnected = true;
1549 this._reconnectInterval = 1;
1550 this._reconnecting = false;
1551 }
1552
1553 // Execute the onConnected callback if there is one.
1554 this._connected(reconnected, this._wsuri);
1555
1556 // Process all queued messages now that the connection is established.
1557 this._process_queue();
1558 break;
1559
1560 case MESSAGE_TYPE.PUBLISH:
1561 this._receivePublish(wireMessage);
1562 break;
1563
1564 case MESSAGE_TYPE.PUBACK:
1565 var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1566 // If this is a re flow of a PUBACK after we have restarted receivedMessage will not exist.
1567 if (sentMessage) {
1568 delete this._sentMessages[wireMessage.messageIdentifier];
1569 localStorage.removeItem(
1570 'Sent:' + this._localKey + wireMessage.messageIdentifier
1571 );
1572 if (this.onMessageDelivered)
1573 this.onMessageDelivered(sentMessage.payloadMessage);
1574 }
1575 break;
1576
1577 case MESSAGE_TYPE.PUBREC:
1578 var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1579 // If this is a re flow of a PUBREC after we have restarted receivedMessage will not exist.
1580 if (sentMessage) {
1581 sentMessage.pubRecReceived = true;
1582 var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {
1583 messageIdentifier: wireMessage.messageIdentifier,
1584 });
1585 this.store('Sent:', sentMessage);
1586 this._schedule_message(pubRelMessage);
1587 }
1588 break;
1589
1590 case MESSAGE_TYPE.PUBREL:
1591 var receivedMessage =
1592 this._receivedMessages[wireMessage.messageIdentifier];
1593 localStorage.removeItem(
1594 'Received:' + this._localKey + wireMessage.messageIdentifier
1595 );
1596 // If this is a re flow of a PUBREL after we have restarted receivedMessage will not exist.
1597 if (receivedMessage) {
1598 this._receiveMessage(receivedMessage);
1599 delete this._receivedMessages[wireMessage.messageIdentifier];
1600 }
1601 // Always flow PubComp, we may have previously flowed PubComp but the server lost it and restarted.
1602 var pubCompMessage = new WireMessage(MESSAGE_TYPE.PUBCOMP, {
1603 messageIdentifier: wireMessage.messageIdentifier,
1604 });
1605 this._schedule_message(pubCompMessage);
1606
1607 break;
1608
1609 case MESSAGE_TYPE.PUBCOMP:
1610 var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1611 delete this._sentMessages[wireMessage.messageIdentifier];
1612 localStorage.removeItem(
1613 'Sent:' + this._localKey + wireMessage.messageIdentifier
1614 );
1615 if (this.onMessageDelivered)
1616 this.onMessageDelivered(sentMessage.payloadMessage);
1617 break;
1618
1619 case MESSAGE_TYPE.SUBACK:
1620 var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1621 if (sentMessage) {
1622 if (sentMessage.timeOut) sentMessage.timeOut.cancel();
1623 // This will need to be fixed when we add multiple topic support
1624 if (wireMessage.returnCode[0] === 0x80) {
1625 if (sentMessage.onFailure) {
1626 sentMessage.onFailure(wireMessage.returnCode);
1627 }
1628 } else if (sentMessage.onSuccess) {
1629 sentMessage.onSuccess(wireMessage.returnCode);
1630 }
1631 delete this._sentMessages[wireMessage.messageIdentifier];
1632 }
1633 break;
1634
1635 case MESSAGE_TYPE.UNSUBACK:
1636 var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1637 if (sentMessage) {
1638 if (sentMessage.timeOut) sentMessage.timeOut.cancel();
1639 if (sentMessage.callback) {
1640 sentMessage.callback();
1641 }
1642 delete this._sentMessages[wireMessage.messageIdentifier];
1643 }
1644
1645 break;
1646
1647 case MESSAGE_TYPE.PINGRESP:
1648 /* The sendPinger or receivePinger may have sent a ping, the receivePinger has already been reset. */
1649 this.sendPinger.reset();
1650 break;
1651
1652 case MESSAGE_TYPE.DISCONNECT:
1653 // Clients do not expect to receive disconnect packets.
1654 this._disconnected(
1655 ERROR.INVALID_MQTT_MESSAGE_TYPE.code,
1656 format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type])
1657 );
1658 break;
1659
1660 default:
1661 this._disconnected(
1662 ERROR.INVALID_MQTT_MESSAGE_TYPE.code,
1663 format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type])
1664 );
1665 }
1666 } catch (error) {
1667 var errorStack =
1668 error.hasOwnProperty('stack') == 'undefined'
1669 ? error.stack.toString()
1670 : 'No Error Stack Available';
1671 this._disconnected(
1672 ERROR.INTERNAL_ERROR.code,
1673 format(ERROR.INTERNAL_ERROR, [error.message, errorStack])
1674 );
1675 return;
1676 }
1677 };
1678
1679 /** @ignore */
1680 ClientImpl.prototype._on_socket_error = function (error) {
1681 if (!this._reconnecting) {
1682 this._disconnected(
1683 ERROR.SOCKET_ERROR.code,
1684 format(ERROR.SOCKET_ERROR, [error.data])
1685 );
1686 }
1687 };
1688
1689 /** @ignore */
1690 ClientImpl.prototype._on_socket_close = function () {
1691 if (!this._reconnecting) {
1692 this._disconnected(ERROR.SOCKET_CLOSE.code, format(ERROR.SOCKET_CLOSE));
1693 }
1694 };
1695
1696 /** @ignore */
1697 ClientImpl.prototype._socket_send = function (wireMessage) {
1698 if (wireMessage.type == 1) {
1699 var wireMessageMasked = this._traceMask(wireMessage, 'password');
1700 this._trace('Client._socket_send', wireMessageMasked);
1701 } else this._trace('Client._socket_send', wireMessage);
1702
1703 this.socket.send(wireMessage.encode());
1704 /* We have proved to the server we are alive. */
1705 this.sendPinger.reset();
1706 };
1707
1708 /** @ignore */
1709 ClientImpl.prototype._receivePublish = function (wireMessage) {
1710 switch (wireMessage.payloadMessage.qos) {
1711 case 'undefined':
1712 case 0:
1713 this._receiveMessage(wireMessage);
1714 break;
1715
1716 case 1:
1717 var pubAckMessage = new WireMessage(MESSAGE_TYPE.PUBACK, {
1718 messageIdentifier: wireMessage.messageIdentifier,
1719 });
1720 this._schedule_message(pubAckMessage);
1721 this._receiveMessage(wireMessage);
1722 break;
1723
1724 case 2:
1725 this._receivedMessages[wireMessage.messageIdentifier] = wireMessage;
1726 this.store('Received:', wireMessage);
1727 var pubRecMessage = new WireMessage(MESSAGE_TYPE.PUBREC, {
1728 messageIdentifier: wireMessage.messageIdentifier,
1729 });
1730 this._schedule_message(pubRecMessage);
1731
1732 break;
1733
1734 default:
1735 throw Error('Invaild qos=' + wireMessage.payloadMessage.qos);
1736 }
1737 };
1738
1739 /** @ignore */
1740 ClientImpl.prototype._receiveMessage = function (wireMessage) {
1741 if (this.onMessageArrived) {
1742 this.onMessageArrived(wireMessage.payloadMessage);
1743 }
1744 };
1745
1746 /**
1747 * Client has connected.
1748 * @param {reconnect} [boolean] indicate if this was a result of reconnect operation.
1749 * @param {uri} [string] fully qualified WebSocket URI of the server.
1750 */
1751 ClientImpl.prototype._connected = function (reconnect, uri) {
1752 // Execute the onConnected callback if there is one.
1753 if (this.onConnected) this.onConnected(reconnect, uri);
1754 };
1755
1756 /**
1757 * Attempts to reconnect the client to the server.
1758 * For each reconnect attempt, will double the reconnect interval
1759 * up to 128 seconds.
1760 */
1761 ClientImpl.prototype._reconnect = function () {
1762 this._trace('Client._reconnect');
1763 if (!this.connected) {
1764 this._reconnecting = true;
1765 this.sendPinger.cancel();
1766 this.receivePinger.cancel();
1767 if (this._reconnectInterval < 128)
1768 this._reconnectInterval = this._reconnectInterval * 2;
1769 if (this.connectOptions.uris) {
1770 this.hostIndex = 0;
1771 this._doConnect(this.connectOptions.uris[0]);
1772 } else {
1773 this._doConnect(this.uri);
1774 }
1775 }
1776 };
1777
1778 /**
1779 * Client has disconnected either at its own request or because the server
1780 * or network disconnected it. Remove all non-durable state.
1781 * @param {errorCode} [number] the error number.
1782 * @param {errorText} [string] the error text.
1783 * @ignore
1784 */
1785 ClientImpl.prototype._disconnected = function (errorCode, errorText) {
1786 this._trace('Client._disconnected', errorCode, errorText);
1787
1788 if (errorCode !== undefined && this._reconnecting) {
1789 //Continue automatic reconnect process
1790 this._reconnectTimeout = new Timeout(
1791 this,
1792 this._reconnectInterval,
1793 this._reconnect
1794 );
1795 return;
1796 }
1797
1798 this.sendPinger.cancel();
1799 this.receivePinger.cancel();
1800 if (this._connectTimeout) {
1801 this._connectTimeout.cancel();
1802 this._connectTimeout = null;
1803 }
1804
1805 // Clear message buffers.
1806 this._msg_queue = [];
1807 this._buffered_msg_queue = [];
1808 this._notify_msg_sent = {};
1809
1810 if (this.socket) {
1811 // Cancel all socket callbacks so that they cannot be driven again by this socket.
1812 this.socket.onopen = null;
1813 this.socket.onmessage = null;
1814 this.socket.onerror = null;
1815 this.socket.onclose = null;
1816 if (this.socket.readyState === 1) this.socket.close();
1817 delete this.socket;
1818 }
1819
1820 if (
1821 this.connectOptions.uris &&
1822 this.hostIndex < this.connectOptions.uris.length - 1
1823 ) {
1824 // Try the next host.
1825 this.hostIndex++;
1826 this._doConnect(this.connectOptions.uris[this.hostIndex]);
1827 } else {
1828 if (errorCode === undefined) {
1829 errorCode = ERROR.OK.code;
1830 errorText = format(ERROR.OK);
1831 }
1832
1833 // Run any application callbacks last as they may attempt to reconnect and hence create a new socket.
1834 if (this.connected) {
1835 this.connected = false;
1836 // Execute the connectionLostCallback if there is one, and we were connected.
1837 if (this.onConnectionLost) {
1838 this.onConnectionLost({
1839 errorCode: errorCode,
1840 errorMessage: errorText,
1841 reconnect: this.connectOptions.reconnect,
1842 uri: this._wsuri,
1843 });
1844 }
1845 if (errorCode !== ERROR.OK.code && this.connectOptions.reconnect) {
1846 // Start automatic reconnect process for the very first time since last successful connect.
1847 this._reconnectInterval = 1;
1848 this._reconnect();
1849 return;
1850 }
1851 } else {
1852 // Otherwise we never had a connection, so indicate that the connect has failed.
1853 if (
1854 this.connectOptions.mqttVersion === 4 &&
1855 this.connectOptions.mqttVersionExplicit === false
1856 ) {
1857 this._trace('Failed to connect V4, dropping back to V3');
1858 this.connectOptions.mqttVersion = 3;
1859 if (this.connectOptions.uris) {
1860 this.hostIndex = 0;
1861 this._doConnect(this.connectOptions.uris[0]);
1862 } else {
1863 this._doConnect(this.uri);
1864 }
1865 } else if (this.connectOptions.onFailure) {
1866 this.connectOptions.onFailure({
1867 invocationContext: this.connectOptions.invocationContext,
1868 errorCode: errorCode,
1869 errorMessage: errorText,
1870 });
1871 }
1872 }
1873 }
1874 };
1875
1876 /** @ignore */
1877 ClientImpl.prototype._trace = function () {
1878 // Pass trace message back to client's callback function
1879 if (this.traceFunction) {
1880 var args = Array.prototype.slice.call(arguments);
1881 for (var i in args) {
1882 if (typeof args[i] !== 'undefined')
1883 args.splice(i, 1, JSON.stringify(args[i]));
1884 }
1885 var record = args.join('');
1886 this.traceFunction({ severity: 'Debug', message: record });
1887 }
1888
1889 //buffer style trace
1890 if (this._traceBuffer !== null) {
1891 for (var i = 0, max = arguments.length; i < max; i++) {
1892 if (this._traceBuffer.length == this._MAX_TRACE_ENTRIES) {
1893 this._traceBuffer.shift();
1894 }
1895 if (i === 0) this._traceBuffer.push(arguments[i]);
1896 else if (typeof arguments[i] === 'undefined')
1897 this._traceBuffer.push(arguments[i]);
1898 else this._traceBuffer.push(' ' + JSON.stringify(arguments[i]));
1899 }
1900 }
1901 };
1902
1903 /** @ignore */
1904 ClientImpl.prototype._traceMask = function (traceObject, masked) {
1905 var traceObjectMasked = {};
1906 for (var attr in traceObject) {
1907 if (traceObject.hasOwnProperty(attr)) {
1908 if (attr == masked) traceObjectMasked[attr] = '******';
1909 else traceObjectMasked[attr] = traceObject[attr];
1910 }
1911 }
1912 return traceObjectMasked;
1913 };
1914
1915 // ------------------------------------------------------------------------
1916 // Public Programming interface.
1917 // ------------------------------------------------------------------------
1918
1919 /**
1920 * The JavaScript application communicates to the server using a {@link Paho.Client} object.
1921 * <p>
1922 * Most applications will create just one Client object and then call its connect() method,
1923 * however applications can create more than one Client object if they wish.
1924 * In this case the combination of host, port and clientId attributes must be different for each Client object.
1925 * <p>
1926 * The send, subscribe and unsubscribe methods are implemented as asynchronous JavaScript methods
1927 * (even though the underlying protocol exchange might be synchronous in nature).
1928 * This means they signal their completion by calling back to the application,
1929 * via Success or Failure callback functions provided by the application on the method in question.
1930 * Such callbacks are called at most once per method invocation and do not persist beyond the lifetime
1931 * of the script that made the invocation.
1932 * <p>
1933 * In contrast there are some callback functions, most notably <i>onMessageArrived</i>,
1934 * that are defined on the {@link Paho.Client} object.
1935 * These may get called multiple times, and aren't directly related to specific method invocations made by the client.
1936 *
1937 * @name Paho.Client
1938 *
1939 * @constructor
1940 *
1941 * @param {string} host - the address of the messaging server, as a fully qualified WebSocket URI, as a DNS name or dotted decimal IP address.
1942 * @param {number} port - the port number to connect to - only required if host is not a URI
1943 * @param {string} path - the path on the host to connect to - only used if host is not a URI. Default: '/mqtt'.
1944 * @param {string} clientId - the Messaging client identifier, between 1 and 23 characters in length.
1945 *
1946 * @property {string} host - <i>read only</i> the server's DNS hostname or dotted decimal IP address.
1947 * @property {number} port - <i>read only</i> the server's port.
1948 * @property {string} path - <i>read only</i> the server's path.
1949 * @property {string} clientId - <i>read only</i> used when connecting to the server.
1950 * @property {function} onConnectionLost - called when a connection has been lost.
1951 * after a connect() method has succeeded.
1952 * Establish the call back used when a connection has been lost. The connection may be
1953 * lost because the client initiates a disconnect or because the server or network
1954 * cause the client to be disconnected. The disconnect call back may be called without
1955 * the connectionComplete call back being invoked if, for example the client fails to
1956 * connect.
1957 * A single response object parameter is passed to the onConnectionLost callback containing the following fields:
1958 * <ol>
1959 * <li>errorCode
1960 * <li>errorMessage
1961 * </ol>
1962 * @property {function} onMessageDelivered - called when a message has been delivered.
1963 * All processing that this Client will ever do has been completed. So, for example,
1964 * in the case of a Qos=2 message sent by this client, the PubComp flow has been received from the server
1965 * and the message has been removed from persistent storage before this callback is invoked.
1966 * Parameters passed to the onMessageDelivered callback are:
1967 * <ol>
1968 * <li>{@link Paho.Message} that was delivered.
1969 * </ol>
1970 * @property {function} onMessageArrived - called when a message has arrived in this Paho.client.
1971 * Parameters passed to the onMessageArrived callback are:
1972 * <ol>
1973 * <li>{@link Paho.Message} that has arrived.
1974 * </ol>
1975 * @property {function} onConnected - called when a connection is successfully made to the server.
1976 * after a connect() method.
1977 * Parameters passed to the onConnected callback are:
1978 * <ol>
1979 * <li>reconnect (boolean) - If true, the connection was the result of a reconnect.</li>
1980 * <li>URI (string) - The URI used to connect to the server.</li>
1981 * </ol>
1982 * @property {boolean} disconnectedPublishing - if set, will enable disconnected publishing in
1983 * in the event that the connection to the server is lost.
1984 * @property {number} disconnectedBufferSize - Used to set the maximum number of messages that the disconnected
1985 * buffer will hold before rejecting new messages. Default size: 5000 messages
1986 * @property {function} trace - called whenever trace is called. TODO
1987 */
1988 var Client = function (host, port, path, clientId) {
1989 var uri;
1990
1991 if (typeof host !== 'string')
1992 throw new Error(format(ERROR.INVALID_TYPE, [typeof host, 'host']));
1993
1994 if (arguments.length == 2) {
1995 // host: must be full ws:// uri
1996 // port: clientId
1997 clientId = port;
1998 uri = host;
1999 var match = uri.match(
2000 /^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/
2001 );
2002 if (match) {
2003 host = match[4] || match[2];
2004 port = parseInt(match[7]);
2005 path = match[8];
2006 } else {
2007 throw new Error(format(ERROR.INVALID_ARGUMENT, [host, 'host']));
2008 }
2009 } else {
2010 if (arguments.length == 3) {
2011 clientId = path;
2012 path = '/mqtt';
2013 }
2014 if (typeof port !== 'number' || port < 0)
2015 throw new Error(format(ERROR.INVALID_TYPE, [typeof port, 'port']));
2016 if (typeof path !== 'string')
2017 throw new Error(format(ERROR.INVALID_TYPE, [typeof path, 'path']));
2018
2019 var ipv6AddSBracket =
2020 host.indexOf(':') !== -1 &&
2021 host.slice(0, 1) !== '[' &&
2022 host.slice(-1) !== ']';
2023 uri =
2024 'ws://' +
2025 (ipv6AddSBracket ? '[' + host + ']' : host) +
2026 ':' +
2027 port +
2028 path;
2029 }
2030
2031 var clientIdLength = 0;
2032 for (var i = 0; i < clientId.length; i++) {
2033 var charCode = clientId.charCodeAt(i);
2034 if (0xd800 <= charCode && charCode <= 0xdbff) {
2035 i++; // Surrogate pair.
2036 }
2037 clientIdLength++;
2038 }
2039 if (typeof clientId !== 'string' || clientIdLength > 65535)
2040 throw new Error(format(ERROR.INVALID_ARGUMENT, [clientId, 'clientId']));
2041
2042 var client = new ClientImpl(uri, host, port, path, clientId);
2043
2044 //Public Properties
2045 Object.defineProperties(this, {
2046 host: {
2047 get: function () {
2048 return host;
2049 },
2050 set: function () {
2051 throw new Error(format(ERROR.UNSUPPORTED_OPERATION));
2052 },
2053 },
2054 port: {
2055 get: function () {
2056 return port;
2057 },
2058 set: function () {
2059 throw new Error(format(ERROR.UNSUPPORTED_OPERATION));
2060 },
2061 },
2062 path: {
2063 get: function () {
2064 return path;
2065 },
2066 set: function () {
2067 throw new Error(format(ERROR.UNSUPPORTED_OPERATION));
2068 },
2069 },
2070 uri: {
2071 get: function () {
2072 return uri;
2073 },
2074 set: function () {
2075 throw new Error(format(ERROR.UNSUPPORTED_OPERATION));
2076 },
2077 },
2078 clientId: {
2079 get: function () {
2080 return client.clientId;
2081 },
2082 set: function () {
2083 throw new Error(format(ERROR.UNSUPPORTED_OPERATION));
2084 },
2085 },
2086 onConnected: {
2087 get: function () {
2088 return client.onConnected;
2089 },
2090 set: function (newOnConnected) {
2091 if (typeof newOnConnected === 'function')
2092 client.onConnected = newOnConnected;
2093 else
2094 throw new Error(
2095 format(ERROR.INVALID_TYPE, [
2096 typeof newOnConnected,
2097 'onConnected',
2098 ])
2099 );
2100 },
2101 },
2102 disconnectedPublishing: {
2103 get: function () {
2104 return client.disconnectedPublishing;
2105 },
2106 set: function (newDisconnectedPublishing) {
2107 client.disconnectedPublishing = newDisconnectedPublishing;
2108 },
2109 },
2110 disconnectedBufferSize: {
2111 get: function () {
2112 return client.disconnectedBufferSize;
2113 },
2114 set: function (newDisconnectedBufferSize) {
2115 client.disconnectedBufferSize = newDisconnectedBufferSize;
2116 },
2117 },
2118 onConnectionLost: {
2119 get: function () {
2120 return client.onConnectionLost;
2121 },
2122 set: function (newOnConnectionLost) {
2123 if (typeof newOnConnectionLost === 'function')
2124 client.onConnectionLost = newOnConnectionLost;
2125 else
2126 throw new Error(
2127 format(ERROR.INVALID_TYPE, [
2128 typeof newOnConnectionLost,
2129 'onConnectionLost',
2130 ])
2131 );
2132 },
2133 },
2134 onMessageDelivered: {
2135 get: function () {
2136 return client.onMessageDelivered;
2137 },
2138 set: function (newOnMessageDelivered) {
2139 if (typeof newOnMessageDelivered === 'function')
2140 client.onMessageDelivered = newOnMessageDelivered;
2141 else
2142 throw new Error(
2143 format(ERROR.INVALID_TYPE, [
2144 typeof newOnMessageDelivered,
2145 'onMessageDelivered',
2146 ])
2147 );
2148 },
2149 },
2150 onMessageArrived: {
2151 get: function () {
2152 return client.onMessageArrived;
2153 },
2154 set: function (newOnMessageArrived) {
2155 if (typeof newOnMessageArrived === 'function')
2156 client.onMessageArrived = newOnMessageArrived;
2157 else
2158 throw new Error(
2159 format(ERROR.INVALID_TYPE, [
2160 typeof newOnMessageArrived,
2161 'onMessageArrived',
2162 ])
2163 );
2164 },
2165 },
2166 trace: {
2167 get: function () {
2168 return client.traceFunction;
2169 },
2170 set: function (trace) {
2171 if (typeof trace === 'function') {
2172 client.traceFunction = trace;
2173 } else {
2174 throw new Error(
2175 format(ERROR.INVALID_TYPE, [typeof trace, 'onTrace'])
2176 );
2177 }
2178 },
2179 },
2180 });
2181
2182 /**
2183 * Connect this Messaging client to its server.
2184 *
2185 * @name Paho.Client#connect
2186 * @function
2187 * @param {object} connectOptions - Attributes used with the connection.
2188 * @param {number} connectOptions.timeout - If the connect has not succeeded within this
2189 * number of seconds, it is deemed to have failed.
2190 * The default is 30 seconds.
2191 * @param {string} connectOptions.userName - Authentication username for this connection.
2192 * @param {string} connectOptions.password - Authentication password for this connection.
2193 * @param {Paho.Message} connectOptions.willMessage - sent by the server when the client
2194 * disconnects abnormally.
2195 * @param {number} connectOptions.keepAliveInterval - the server disconnects this client if
2196 * there is no activity for this number of seconds.
2197 * The default value of 60 seconds is assumed if not set.
2198 * @param {boolean} connectOptions.cleanSession - if true(default) the client and server
2199 * persistent state is deleted on successful connect.
2200 * @param {boolean} connectOptions.useSSL - if present and true, use an SSL Websocket connection.
2201 * @param {object} connectOptions.invocationContext - passed to the onSuccess callback or onFailure callback.
2202 * @param {function} connectOptions.onSuccess - called when the connect acknowledgement
2203 * has been received from the server.
2204 * A single response object parameter is passed to the onSuccess callback containing the following fields:
2205 * <ol>
2206 * <li>invocationContext as passed in to the onSuccess method in the connectOptions.
2207 * </ol>
2208 * @param {function} connectOptions.onFailure - called when the connect request has failed or timed out.
2209 * A single response object parameter is passed to the onFailure callback containing the following fields:
2210 * <ol>
2211 * <li>invocationContext as passed in to the onFailure method in the connectOptions.
2212 * <li>errorCode a number indicating the nature of the error.
2213 * <li>errorMessage text describing the error.
2214 * </ol>
2215 * @param {array} connectOptions.hosts - If present this contains either a set of hostnames or fully qualified
2216 * WebSocket URIs (ws://iot.eclipse.org:80/ws), that are tried in order in place
2217 * of the host and port paramater on the construtor. The hosts are tried one at at time in order until
2218 * one of then succeeds.
2219 * @param {array} connectOptions.ports - If present the set of ports matching the hosts. If hosts contains URIs, this property
2220 * is not used.
2221 * @param {boolean} connectOptions.reconnect - Sets whether the client will automatically attempt to reconnect
2222 * to the server if the connection is lost.
2223 *<ul>
2224 *<li>If set to false, the client will not attempt to automatically reconnect to the server in the event that the
2225 * connection is lost.</li>
2226 *<li>If set to true, in the event that the connection is lost, the client will attempt to reconnect to the server.
2227 * It will initially wait 1 second before it attempts to reconnect, for every failed reconnect attempt, the delay
2228 * will double until it is at 2 minutes at which point the delay will stay at 2 minutes.</li>
2229 *</ul>
2230 * @param {number} connectOptions.mqttVersion - The version of MQTT to use to connect to the MQTT Broker.
2231 *<ul>
2232 *<li>3 - MQTT V3.1</li>
2233 *<li>4 - MQTT V3.1.1</li>
2234 *</ul>
2235 * @param {boolean} connectOptions.mqttVersionExplicit - If set to true, will force the connection to use the
2236 * selected MQTT Version or will fail to connect.
2237 * @param {array} connectOptions.uris - If present, should contain a list of fully qualified WebSocket uris
2238 * (e.g. ws://iot.eclipse.org:80/ws), that are tried in order in place of the host and port parameter of the construtor.
2239 * The uris are tried one at a time in order until one of them succeeds. Do not use this in conjunction with hosts as
2240 * the hosts array will be converted to uris and will overwrite this property.
2241 * @throws {InvalidState} If the client is not in disconnected state. The client must have received connectionLost
2242 * or disconnected before calling connect for a second or subsequent time.
2243 */
2244 this.connect = function (connectOptions) {
2245 connectOptions = connectOptions || {};
2246 validate(connectOptions, {
2247 timeout: 'number',
2248 userName: 'string',
2249 password: 'string',
2250 willMessage: 'object',
2251 keepAliveInterval: 'number',
2252 cleanSession: 'boolean',
2253 useSSL: 'boolean',
2254 invocationContext: 'object',
2255 onSuccess: 'function',
2256 onFailure: 'function',
2257 hosts: 'object',
2258 ports: 'object',
2259 reconnect: 'boolean',
2260 mqttVersion: 'number',
2261 mqttVersionExplicit: 'boolean',
2262 uris: 'object',
2263 });
2264
2265 // If no keep alive interval is set, assume 60 seconds.
2266 if (connectOptions.keepAliveInterval === undefined)
2267 connectOptions.keepAliveInterval = 60;
2268
2269 if (connectOptions.mqttVersion > 4 || connectOptions.mqttVersion < 3) {
2270 throw new Error(
2271 format(ERROR.INVALID_ARGUMENT, [
2272 connectOptions.mqttVersion,
2273 'connectOptions.mqttVersion',
2274 ])
2275 );
2276 }
2277
2278 if (connectOptions.mqttVersion === undefined) {
2279 connectOptions.mqttVersionExplicit = false;
2280 connectOptions.mqttVersion = 4;
2281 } else {
2282 connectOptions.mqttVersionExplicit = true;
2283 }
2284
2285 //Check that if password is set, so is username
2286 if (
2287 connectOptions.password !== undefined &&
2288 connectOptions.userName === undefined
2289 )
2290 throw new Error(
2291 format(ERROR.INVALID_ARGUMENT, [
2292 connectOptions.password,
2293 'connectOptions.password',
2294 ])
2295 );
2296
2297 if (connectOptions.willMessage) {
2298 if (!(connectOptions.willMessage instanceof Message))
2299 throw new Error(
2300 format(ERROR.INVALID_TYPE, [
2301 connectOptions.willMessage,
2302 'connectOptions.willMessage',
2303 ])
2304 );
2305 // The will message must have a payload that can be represented as a string.
2306 // Cause the willMessage to throw an exception if this is not the case.
2307 connectOptions.willMessage.stringPayload = null;
2308
2309 if (typeof connectOptions.willMessage.destinationName === 'undefined')
2310 throw new Error(
2311 format(ERROR.INVALID_TYPE, [
2312 typeof connectOptions.willMessage.destinationName,
2313 'connectOptions.willMessage.destinationName',
2314 ])
2315 );
2316 }
2317 if (typeof connectOptions.cleanSession === 'undefined')
2318 connectOptions.cleanSession = true;
2319 if (connectOptions.hosts) {
2320 if (!(connectOptions.hosts instanceof Array))
2321 throw new Error(
2322 format(ERROR.INVALID_ARGUMENT, [
2323 connectOptions.hosts,
2324 'connectOptions.hosts',
2325 ])
2326 );
2327 if (connectOptions.hosts.length < 1)
2328 throw new Error(
2329 format(ERROR.INVALID_ARGUMENT, [
2330 connectOptions.hosts,
2331 'connectOptions.hosts',
2332 ])
2333 );
2334
2335 var usingURIs = false;
2336 for (var i = 0; i < connectOptions.hosts.length; i++) {
2337 if (typeof connectOptions.hosts[i] !== 'string')
2338 throw new Error(
2339 format(ERROR.INVALID_TYPE, [
2340 typeof connectOptions.hosts[i],
2341 'connectOptions.hosts[' + i + ']',
2342 ])
2343 );
2344 if (
2345 /^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/.test(
2346 connectOptions.hosts[i]
2347 )
2348 ) {
2349 if (i === 0) {
2350 usingURIs = true;
2351 } else if (!usingURIs) {
2352 throw new Error(
2353 format(ERROR.INVALID_ARGUMENT, [
2354 connectOptions.hosts[i],
2355 'connectOptions.hosts[' + i + ']',
2356 ])
2357 );
2358 }
2359 } else if (usingURIs) {
2360 throw new Error(
2361 format(ERROR.INVALID_ARGUMENT, [
2362 connectOptions.hosts[i],
2363 'connectOptions.hosts[' + i + ']',
2364 ])
2365 );
2366 }
2367 }
2368
2369 if (!usingURIs) {
2370 if (!connectOptions.ports)
2371 throw new Error(
2372 format(ERROR.INVALID_ARGUMENT, [
2373 connectOptions.ports,
2374 'connectOptions.ports',
2375 ])
2376 );
2377 if (!(connectOptions.ports instanceof Array))
2378 throw new Error(
2379 format(ERROR.INVALID_ARGUMENT, [
2380 connectOptions.ports,
2381 'connectOptions.ports',
2382 ])
2383 );
2384 if (connectOptions.hosts.length !== connectOptions.ports.length)
2385 throw new Error(
2386 format(ERROR.INVALID_ARGUMENT, [
2387 connectOptions.ports,
2388 'connectOptions.ports',
2389 ])
2390 );
2391
2392 connectOptions.uris = [];
2393
2394 for (var i = 0; i < connectOptions.hosts.length; i++) {
2395 if (
2396 typeof connectOptions.ports[i] !== 'number' ||
2397 connectOptions.ports[i] < 0
2398 )
2399 throw new Error(
2400 format(ERROR.INVALID_TYPE, [
2401 typeof connectOptions.ports[i],
2402 'connectOptions.ports[' + i + ']',
2403 ])
2404 );
2405 var host = connectOptions.hosts[i];
2406 var port = connectOptions.ports[i];
2407
2408 var ipv6 = host.indexOf(':') !== -1;
2409 uri =
2410 'ws://' + (ipv6 ? '[' + host + ']' : host) + ':' + port + path;
2411 connectOptions.uris.push(uri);
2412 }
2413 } else {
2414 connectOptions.uris = connectOptions.hosts;
2415 }
2416 }
2417
2418 client.connect(connectOptions);
2419 };
2420
2421 /**
2422 * Subscribe for messages, request receipt of a copy of messages sent to the destinations described by the filter.
2423 *
2424 * @name Paho.Client#subscribe
2425 * @function
2426 * @param {string} filter describing the destinations to receive messages from.
2427 * <br>
2428 * @param {object} subscribeOptions - used to control the subscription
2429 *
2430 * @param {number} subscribeOptions.qos - the maximum qos of any publications sent
2431 * as a result of making this subscription.
2432 * @param {object} subscribeOptions.invocationContext - passed to the onSuccess callback
2433 * or onFailure callback.
2434 * @param {function} subscribeOptions.onSuccess - called when the subscribe acknowledgement
2435 * has been received from the server.
2436 * A single response object parameter is passed to the onSuccess callback containing the following fields:
2437 * <ol>
2438 * <li>invocationContext if set in the subscribeOptions.
2439 * </ol>
2440 * @param {function} subscribeOptions.onFailure - called when the subscribe request has failed or timed out.
2441 * A single response object parameter is passed to the onFailure callback containing the following fields:
2442 * <ol>
2443 * <li>invocationContext - if set in the subscribeOptions.
2444 * <li>errorCode - a number indicating the nature of the error.
2445 * <li>errorMessage - text describing the error.
2446 * </ol>
2447 * @param {number} subscribeOptions.timeout - which, if present, determines the number of
2448 * seconds after which the onFailure calback is called.
2449 * The presence of a timeout does not prevent the onSuccess
2450 * callback from being called when the subscribe completes.
2451 * @throws {InvalidState} if the client is not in connected state.
2452 */
2453 this.subscribe = function (filter, subscribeOptions) {
2454 if (typeof filter !== 'string' && filter.constructor !== Array)
2455 throw new Error('Invalid argument:' + filter);
2456 subscribeOptions = subscribeOptions || {};
2457 validate(subscribeOptions, {
2458 qos: 'number',
2459 invocationContext: 'object',
2460 onSuccess: 'function',
2461 onFailure: 'function',
2462 timeout: 'number',
2463 });
2464 if (subscribeOptions.timeout && !subscribeOptions.onFailure)
2465 throw new Error(
2466 'subscribeOptions.timeout specified with no onFailure callback.'
2467 );
2468 if (
2469 typeof subscribeOptions.qos !== 'undefined' &&
2470 !(
2471 subscribeOptions.qos === 0 ||
2472 subscribeOptions.qos === 1 ||
2473 subscribeOptions.qos === 2
2474 )
2475 )
2476 throw new Error(
2477 format(ERROR.INVALID_ARGUMENT, [
2478 subscribeOptions.qos,
2479 'subscribeOptions.qos',
2480 ])
2481 );
2482 client.subscribe(filter, subscribeOptions);
2483 };
2484
2485 /**
2486 * Unsubscribe for messages, stop receiving messages sent to destinations described by the filter.
2487 *
2488 * @name Paho.Client#unsubscribe
2489 * @function
2490 * @param {string} filter - describing the destinations to receive messages from.
2491 * @param {object} unsubscribeOptions - used to control the subscription
2492 * @param {object} unsubscribeOptions.invocationContext - passed to the onSuccess callback
2493 or onFailure callback.
2494 * @param {function} unsubscribeOptions.onSuccess - called when the unsubscribe acknowledgement has been received from the server.
2495 * A single response object parameter is passed to the
2496 * onSuccess callback containing the following fields:
2497 * <ol>
2498 * <li>invocationContext - if set in the unsubscribeOptions.
2499 * </ol>
2500 * @param {function} unsubscribeOptions.onFailure called when the unsubscribe request has failed or timed out.
2501 * A single response object parameter is passed to the onFailure callback containing the following fields:
2502 * <ol>
2503 * <li>invocationContext - if set in the unsubscribeOptions.
2504 * <li>errorCode - a number indicating the nature of the error.
2505 * <li>errorMessage - text describing the error.
2506 * </ol>
2507 * @param {number} unsubscribeOptions.timeout - which, if present, determines the number of seconds
2508 * after which the onFailure callback is called. The presence of
2509 * a timeout does not prevent the onSuccess callback from being
2510 * called when the unsubscribe completes
2511 * @throws {InvalidState} if the client is not in connected state.
2512 */
2513 this.unsubscribe = function (filter, unsubscribeOptions) {
2514 if (typeof filter !== 'string' && filter.constructor !== Array)
2515 throw new Error('Invalid argument:' + filter);
2516 unsubscribeOptions = unsubscribeOptions || {};
2517 validate(unsubscribeOptions, {
2518 invocationContext: 'object',
2519 onSuccess: 'function',
2520 onFailure: 'function',
2521 timeout: 'number',
2522 });
2523 if (unsubscribeOptions.timeout && !unsubscribeOptions.onFailure)
2524 throw new Error(
2525 'unsubscribeOptions.timeout specified with no onFailure callback.'
2526 );
2527 client.unsubscribe(filter, unsubscribeOptions);
2528 };
2529
2530 /**
2531 * Send a message to the consumers of the destination in the Message.
2532 *
2533 * @name Paho.Client#send
2534 * @function
2535 * @param {string|Paho.Message} topic - <b>mandatory</b> The name of the destination to which the message is to be sent.
2536 * - If it is the only parameter, used as Paho.Message object.
2537 * @param {String|ArrayBuffer} payload - The message data to be sent.
2538 * @param {number} qos The Quality of Service used to deliver the message.
2539 * <dl>
2540 * <dt>0 Best effort (default).
2541 * <dt>1 At least once.
2542 * <dt>2 Exactly once.
2543 * </dl>
2544 * @param {Boolean} retained If true, the message is to be retained by the server and delivered
2545 * to both current and future subscriptions.
2546 * If false the server only delivers the message to current subscribers, this is the default for new Messages.
2547 * A received message has the retained boolean set to true if the message was published
2548 * with the retained boolean set to true
2549 * and the subscrption was made after the message has been published.
2550 * @throws {InvalidState} if the client is not connected.
2551 */
2552 this.send = function (topic, payload, qos, retained) {
2553 var message;
2554
2555 if (arguments.length === 0) {
2556 throw new Error('Invalid argument.' + 'length');
2557 } else if (arguments.length == 1) {
2558 if (!(topic instanceof Message) && typeof topic !== 'string')
2559 throw new Error('Invalid argument:' + typeof topic);
2560
2561 message = topic;
2562 if (typeof message.destinationName === 'undefined')
2563 throw new Error(
2564 format(ERROR.INVALID_ARGUMENT, [
2565 message.destinationName,
2566 'Message.destinationName',
2567 ])
2568 );
2569 client.send(message);
2570 } else {
2571 //parameter checking in Message object
2572 message = new Message(payload);
2573 message.destinationName = topic;
2574 if (arguments.length >= 3) message.qos = qos;
2575 if (arguments.length >= 4) message.retained = retained;
2576 client.send(message);
2577 }
2578 };
2579
2580 /**
2581 * Publish a message to the consumers of the destination in the Message.
2582 * Synonym for Paho.Mqtt.Client#send
2583 *
2584 * @name Paho.Client#publish
2585 * @function
2586 * @param {string|Paho.Message} topic - <b>mandatory</b> The name of the topic to which the message is to be published.
2587 * - If it is the only parameter, used as Paho.Message object.
2588 * @param {String|ArrayBuffer} payload - The message data to be published.
2589 * @param {number} qos The Quality of Service used to deliver the message.
2590 * <dl>
2591 * <dt>0 Best effort (default).
2592 * <dt>1 At least once.
2593 * <dt>2 Exactly once.
2594 * </dl>
2595 * @param {Boolean} retained If true, the message is to be retained by the server and delivered
2596 * to both current and future subscriptions.
2597 * If false the server only delivers the message to current subscribers, this is the default for new Messages.
2598 * A received message has the retained boolean set to true if the message was published
2599 * with the retained boolean set to true
2600 * and the subscrption was made after the message has been published.
2601 * @throws {InvalidState} if the client is not connected.
2602 */
2603 this.publish = function (topic, payload, qos, retained) {
2604 var message;
2605
2606 if (arguments.length === 0) {
2607 throw new Error('Invalid argument.' + 'length');
2608 } else if (arguments.length == 1) {
2609 if (!(topic instanceof Message) && typeof topic !== 'string')
2610 throw new Error('Invalid argument:' + typeof topic);
2611
2612 message = topic;
2613 if (typeof message.destinationName === 'undefined')
2614 throw new Error(
2615 format(ERROR.INVALID_ARGUMENT, [
2616 message.destinationName,
2617 'Message.destinationName',
2618 ])
2619 );
2620 client.send(message);
2621 } else {
2622 //parameter checking in Message object
2623 message = new Message(payload);
2624 message.destinationName = topic;
2625 if (arguments.length >= 3) message.qos = qos;
2626 if (arguments.length >= 4) message.retained = retained;
2627 client.send(message);
2628 }
2629 };
2630
2631 /**
2632 * Normal disconnect of this Messaging client from its server.
2633 *
2634 * @name Paho.Client#disconnect
2635 * @function
2636 * @throws {InvalidState} if the client is already disconnected.
2637 */
2638 this.disconnect = function () {
2639 client.disconnect();
2640 };
2641
2642 /**
2643 * Get the contents of the trace log.
2644 *
2645 * @name Paho.Client#getTraceLog
2646 * @function
2647 * @return {Object[]} tracebuffer containing the time ordered trace records.
2648 */
2649 this.getTraceLog = function () {
2650 return client.getTraceLog();
2651 };
2652
2653 /**
2654 * Start tracing.
2655 *
2656 * @name Paho.Client#startTrace
2657 * @function
2658 */
2659 this.startTrace = function () {
2660 client.startTrace();
2661 };
2662
2663 /**
2664 * Stop tracing.
2665 *
2666 * @name Paho.Client#stopTrace
2667 * @function
2668 */
2669 this.stopTrace = function () {
2670 client.stopTrace();
2671 };
2672
2673 this.isConnected = function () {
2674 return client.connected;
2675 };
2676 };
2677
2678 /**
2679 * An application message, sent or received.
2680 * <p>
2681 * All attributes may be null, which implies the default values.
2682 *
2683 * @name Paho.Message
2684 * @constructor
2685 * @param {String|ArrayBuffer} payload The message data to be sent.
2686 * <p>
2687 * @property {string} payloadString <i>read only</i> The payload as a string if the payload consists of valid UTF-8 characters.
2688 * @property {ArrayBuffer} payloadBytes <i>read only</i> The payload as an ArrayBuffer.
2689 * <p>
2690 * @property {string} destinationName <b>mandatory</b> The name of the destination to which the message is to be sent
2691 * (for messages about to be sent) or the name of the destination from which the message has been received.
2692 * (for messages received by the onMessage function).
2693 * <p>
2694 * @property {number} qos The Quality of Service used to deliver the message.
2695 * <dl>
2696 * <dt>0 Best effort (default).
2697 * <dt>1 At least once.
2698 * <dt>2 Exactly once.
2699 * </dl>
2700 * <p>
2701 * @property {Boolean} retained If true, the message is to be retained by the server and delivered
2702 * to both current and future subscriptions.
2703 * If false the server only delivers the message to current subscribers, this is the default for new Messages.
2704 * A received message has the retained boolean set to true if the message was published
2705 * with the retained boolean set to true
2706 * and the subscrption was made after the message has been published.
2707 * <p>
2708 * @property {Boolean} duplicate <i>read only</i> If true, this message might be a duplicate of one which has already been received.
2709 * This is only set on messages received from the server.
2710 *
2711 */
2712 var Message = function (newPayload) {
2713 var payload;
2714 if (
2715 typeof newPayload === 'string' ||
2716 newPayload instanceof ArrayBuffer ||
2717 (ArrayBuffer.isView(newPayload) && !(newPayload instanceof DataView))
2718 ) {
2719 payload = newPayload;
2720 } else {
2721 throw format(ERROR.INVALID_ARGUMENT, [newPayload, 'newPayload']);
2722 }
2723
2724 var destinationName;
2725 var qos = 0;
2726 var retained = false;
2727 var duplicate = false;
2728
2729 Object.defineProperties(this, {
2730 payloadString: {
2731 enumerable: true,
2732 get: function () {
2733 if (typeof payload === 'string') return payload;
2734 else return parseUTF8(payload, 0, payload.length);
2735 },
2736 },
2737 payloadBytes: {
2738 enumerable: true,
2739 get: function () {
2740 if (typeof payload === 'string') {
2741 var buffer = new ArrayBuffer(UTF8Length(payload));
2742 var byteStream = new Uint8Array(buffer);
2743 stringToUTF8(payload, byteStream, 0);
2744
2745 return byteStream;
2746 } else {
2747 return payload;
2748 }
2749 },
2750 },
2751 destinationName: {
2752 enumerable: true,
2753 get: function () {
2754 return destinationName;
2755 },
2756 set: function (newDestinationName) {
2757 if (typeof newDestinationName === 'string')
2758 destinationName = newDestinationName;
2759 else
2760 throw new Error(
2761 format(ERROR.INVALID_ARGUMENT, [
2762 newDestinationName,
2763 'newDestinationName',
2764 ])
2765 );
2766 },
2767 },
2768 qos: {
2769 enumerable: true,
2770 get: function () {
2771 return qos;
2772 },
2773 set: function (newQos) {
2774 if (newQos === 0 || newQos === 1 || newQos === 2) qos = newQos;
2775 else throw new Error('Invalid argument:' + newQos);
2776 },
2777 },
2778 retained: {
2779 enumerable: true,
2780 get: function () {
2781 return retained;
2782 },
2783 set: function (newRetained) {
2784 if (typeof newRetained === 'boolean') retained = newRetained;
2785 else
2786 throw new Error(
2787 format(ERROR.INVALID_ARGUMENT, [newRetained, 'newRetained'])
2788 );
2789 },
2790 },
2791 topic: {
2792 enumerable: true,
2793 get: function () {
2794 return destinationName;
2795 },
2796 set: function (newTopic) {
2797 destinationName = newTopic;
2798 },
2799 },
2800 duplicate: {
2801 enumerable: true,
2802 get: function () {
2803 return duplicate;
2804 },
2805 set: function (newDuplicate) {
2806 duplicate = newDuplicate;
2807 },
2808 },
2809 });
2810 };
2811
2812 // Module contents.
2813 return {
2814 Client: Client,
2815 Message: Message,
2816 };
2817 // eslint-disable-next-line no-nested-ternary
2818 })(
2819 typeof global !== 'undefined'
2820 ? global
2821 : typeof self !== 'undefined'
2822 ? self
2823 : typeof window !== 'undefined'
2824 ? window
2825 : {}
2826 );
2827 return PahoMQTT;
2828});