paho-rails 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2012 @@
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
+
18
+ // Only expose a single object name in the global namespace.
19
+ // Everything must go through this module. Global Messaging module
20
+ // only has a single public function, client, which returns
21
+ // a Messaging client object given connection details.
22
+
23
+ /**
24
+ * Send and receive messages using web browsers.
25
+ * <p>
26
+ * This programming interface lets a JavaScript client application use the MQTT V3.1 protocol to
27
+ * connect to an MQTT-supporting messaging server.
28
+ *
29
+ * The function supported includes:
30
+ * <ol>
31
+ * <li>Connecting to and disconnecting from a server. The server is identified by its host name and port number.
32
+ * <li>Specifying options that relate to the communications link with the server,
33
+ * for example the frequency of keep-alive heartbeats, and whether SSL/TLS is required.
34
+ * <li>Subscribing to and receiving messages from MQTT Topics.
35
+ * <li>Publishing messages to MQTT Topics.
36
+ * </ol>
37
+ * <p>
38
+ * The API consists of two main objects:
39
+ * <dl>
40
+ * <dt><b>{@link Messaging.Client}</b></dt>
41
+ * <dd>This contains methods that provide the functionality of the API,
42
+ * including provision of callbacks that notify the application when a message
43
+ * arrives from or is delivered to the messaging server,
44
+ * or when the status of its connection to the messaging server changes.</dd>
45
+ * <dt><b>{@link Messaging.Message}</b></dt>
46
+ * <dd>This encapsulates the payload of the message along with various attributes
47
+ * associated with its delivery, in particular the destination to which it has
48
+ * been (or is about to be) sent.</dd>
49
+ * </dl>
50
+ * <p>
51
+ * The programming interface validates parameters passed to it, and will throw
52
+ * an Error containing an error message intended for developer use, if it detects
53
+ * an error with any parameter.
54
+ * <p>
55
+ * Example:
56
+ *
57
+ * <code><pre>
58
+ client = new Messaging.Client(location.hostname, Number(location.port), "clientId");
59
+ client.onConnectionLost = onConnectionLost;
60
+ client.onMessageArrived = onMessageArrived;
61
+ client.connect({onSuccess:onConnect});
62
+
63
+ function onConnect() {
64
+ // Once a connection has been made, make a subscription and send a message.
65
+ console.log("onConnect");
66
+ client.subscribe("/World");
67
+ message = new Messaging.Message("Hello");
68
+ message.destinationName = "/World";
69
+ client.send(message);
70
+ };
71
+ function onConnectionLost(responseObject) {
72
+ if (responseObject.errorCode !== 0)
73
+ console.log("onConnectionLost:"+responseObject.errorMessage);
74
+ };
75
+ function onMessageArrived(message) {
76
+ console.log("onMessageArrived:"+message.payloadString);
77
+ client.disconnect();
78
+ };
79
+ * </pre></code>
80
+ * @namespace Messaging
81
+ */
82
+
83
+ Messaging = (function (global) {
84
+
85
+ // Private variables below, these are only visible inside the function closure
86
+ // which is used to define the module.
87
+
88
+ var version = "@VERSION@";
89
+ var buildLevel = "@BUILDLEVEL@";
90
+
91
+ /**
92
+ * Unique message type identifiers, with associated
93
+ * associated integer values.
94
+ * @private
95
+ */
96
+ var MESSAGE_TYPE = {
97
+ CONNECT: 1,
98
+ CONNACK: 2,
99
+ PUBLISH: 3,
100
+ PUBACK: 4,
101
+ PUBREC: 5,
102
+ PUBREL: 6,
103
+ PUBCOMP: 7,
104
+ SUBSCRIBE: 8,
105
+ SUBACK: 9,
106
+ UNSUBSCRIBE: 10,
107
+ UNSUBACK: 11,
108
+ PINGREQ: 12,
109
+ PINGRESP: 13,
110
+ DISCONNECT: 14
111
+ };
112
+
113
+ // Collection of utility methods used to simplify module code
114
+ // and promote the DRY pattern.
115
+
116
+ /**
117
+ * Validate an object's parameter names to ensure they
118
+ * match a list of expected variables name for this option
119
+ * type. Used to ensure option object passed into the API don't
120
+ * contain erroneous parameters.
121
+ * @param {Object} obj - User options object
122
+ * @param {Object} keys - valid keys and types that may exist in obj.
123
+ * @throws {Error} Invalid option parameter found.
124
+ * @private
125
+ */
126
+ var validate = function(obj, keys) {
127
+ for(key in obj) {
128
+ if (obj.hasOwnProperty(key)) {
129
+ if (keys.hasOwnProperty(key)) {
130
+ if (typeof obj[key] !== keys[key])
131
+ throw new Error(format(ERROR.INVALID_TYPE, [typeof obj[key], key]));
132
+ } else {
133
+ var errorStr = "Unknown property, " + key + ". Valid properties are:";
134
+ for (key in keys)
135
+ if (keys.hasOwnProperty(key))
136
+ errorStr = errorStr+" "+key;
137
+ throw new Error(errorStr);
138
+ }
139
+ }
140
+ }
141
+ };
142
+
143
+ /**
144
+ * Return a new function which runs the user function bound
145
+ * to a fixed scope.
146
+ * @param {function} User function
147
+ * @param {object} Function scope
148
+ * @return {function} User function bound to another scope
149
+ * @private
150
+ */
151
+ var scope = function (f, scope) {
152
+ return function () {
153
+ return f.apply(scope, arguments);
154
+ };
155
+ };
156
+
157
+ /**
158
+ * Unique message type identifiers, with associated
159
+ * associated integer values.
160
+ * @private
161
+ */
162
+ var ERROR = {
163
+ OK: {code:0, text:"AMQJSC0000I OK."},
164
+ CONNECT_TIMEOUT: {code:1, text:"AMQJSC0001E Connect timed out."},
165
+ SUBSCRIBE_TIMEOUT: {code:2, text:"AMQJS0002E Subscribe timed out."},
166
+ UNSUBSCRIBE_TIMEOUT: {code:3, text:"AMQJS0003E Unsubscribe timed out."},
167
+ PING_TIMEOUT: {code:4, text:"AMQJS0004E Ping timed out."},
168
+ INTERNAL_ERROR: {code:5, text:"AMQJS0005E Internal error."},
169
+ CONNACK_RETURNCODE: {code:6, text:"AMQJS0006E Bad Connack return code:{0} {1}."},
170
+ SOCKET_ERROR: {code:7, text:"AMQJS0007E Socket error:{0}."},
171
+ SOCKET_CLOSE: {code:8, text:"AMQJS0008I Socket closed."},
172
+ MALFORMED_UTF: {code:9, text:"AMQJS0009E Malformed UTF data:{0} {1} {2}."},
173
+ UNSUPPORTED: {code:10, text:"AMQJS0010E {0} is not supported by this browser."},
174
+ INVALID_STATE: {code:11, text:"AMQJS0011E Invalid state {0}."},
175
+ INVALID_TYPE: {code:12, text:"AMQJS0012E Invalid type {0} for {1}."},
176
+ INVALID_ARGUMENT: {code:13, text:"AMQJS0013E Invalid argument {0} for {1}."},
177
+ UNSUPPORTED_OPERATION: {code:14, text:"AMQJS0014E Unsupported operation."},
178
+ INVALID_STORED_DATA: {code:15, text:"AMQJS0015E Invalid data in local storage key={0} value={1}."},
179
+ INVALID_MQTT_MESSAGE_TYPE: {code:16, text:"AMQJS0016E Invalid MQTT message type {0}."},
180
+ MALFORMED_UNICODE: {code:17, text:"AMQJS0017E Malformed Unicode string:{0} {1}."},
181
+ };
182
+
183
+ /** CONNACK RC Meaning. */
184
+ var CONNACK_RC = {
185
+ 0:"Connection Accepted",
186
+ 1:"Connection Refused: unacceptable protocol version",
187
+ 2:"Connection Refused: identifier rejected",
188
+ 3:"Connection Refused: server unavailable",
189
+ 4:"Connection Refused: bad user name or password",
190
+ 5:"Connection Refused: not authorized"
191
+ };
192
+
193
+ /**
194
+ * Format an error message text.
195
+ * @private
196
+ * @param {error} ERROR.KEY value above.
197
+ * @param {substitutions} [array] substituted into the text.
198
+ * @return the text with the substitutions made.
199
+ */
200
+ var format = function(error, substitutions) {
201
+ var text = error.text;
202
+ if (substitutions) {
203
+ for (var i=0; i<substitutions.length; i++) {
204
+ field = "{"+i+"}";
205
+ start = text.indexOf(field);
206
+ if(start > 0) {
207
+ var part1 = text.substring(0,start);
208
+ var part2 = text.substring(start+field.length);
209
+ text = part1+substitutions[i]+part2;
210
+ }
211
+ }
212
+ }
213
+ return text;
214
+ };
215
+
216
+ //MQTT protocol and version 6 M Q I s d p 3
217
+ var MqttProtoIdentifier = [0x00,0x06,0x4d,0x51,0x49,0x73,0x64,0x70,0x03];
218
+
219
+ /**
220
+ * Construct an MQTT wire protocol message.
221
+ * @param type MQTT packet type.
222
+ * @param options optional wire message attributes.
223
+ *
224
+ * Optional properties
225
+ *
226
+ * messageIdentifier: message ID in the range [0..65535]
227
+ * payloadMessage: Application Message - PUBLISH only
228
+ * connectStrings: array of 0 or more Strings to be put into the CONNECT payload
229
+ * topics: array of strings (SUBSCRIBE, UNSUBSCRIBE)
230
+ * requestQoS: array of QoS values [0..2]
231
+ *
232
+ * "Flag" properties
233
+ * cleanSession: true if present / false if absent (CONNECT)
234
+ * willMessage: true if present / false if absent (CONNECT)
235
+ * isRetained: true if present / false if absent (CONNECT)
236
+ * userName: true if present / false if absent (CONNECT)
237
+ * password: true if present / false if absent (CONNECT)
238
+ * keepAliveInterval: integer [0..65535] (CONNECT)
239
+ *
240
+ * @private
241
+ * @ignore
242
+ */
243
+ var WireMessage = function (type, options) {
244
+ this.type = type;
245
+ for(name in options) {
246
+ if (options.hasOwnProperty(name)) {
247
+ this[name] = options[name];
248
+ }
249
+ }
250
+ };
251
+
252
+ WireMessage.prototype.encode = function() {
253
+ // Compute the first byte of the fixed header
254
+ var first = ((this.type & 0x0f) << 4);
255
+
256
+ /*
257
+ * Now calculate the length of the variable header + payload by adding up the lengths
258
+ * of all the component parts
259
+ */
260
+
261
+ remLength = 0;
262
+ topicStrLength = new Array();
263
+
264
+ // if the message contains a messageIdentifier then we need two bytes for that
265
+ if (this.messageIdentifier != undefined)
266
+ remLength += 2;
267
+
268
+ switch(this.type) {
269
+ // If this a Connect then we need to include 12 bytes for its header
270
+ case MESSAGE_TYPE.CONNECT:
271
+ remLength += MqttProtoIdentifier.length + 3;
272
+ remLength += UTF8Length(this.clientId) + 2;
273
+ if (this.willMessage != undefined) {
274
+ remLength += UTF8Length(this.willMessage.destinationName) + 2;
275
+ // Will message is always a string, sent as UTF-8 characters with a preceding length.
276
+ var willMessagePayloadBytes = this.willMessage.payloadBytes;
277
+ if (!(willMessagePayloadBytes instanceof Uint8Array))
278
+ willMessagePayloadBytes = new Uint8Array(payloadBytes);
279
+ remLength += willMessagePayloadBytes.byteLength +2;
280
+ }
281
+ if (this.userName != undefined)
282
+ remLength += UTF8Length(this.userName) + 2;
283
+ if (this.password != undefined)
284
+ remLength += UTF8Length(this.password) + 2;
285
+ break;
286
+
287
+ // Subscribe, Unsubscribe can both contain topic strings
288
+ case MESSAGE_TYPE.SUBSCRIBE:
289
+ first |= 0x02; // Qos = 1;
290
+ for ( var i = 0; i < this.topics.length; i++) {
291
+ topicStrLength[i] = UTF8Length(this.topics[i]);
292
+ remLength += topicStrLength[i] + 2;
293
+ }
294
+ remLength += this.requestedQos.length; // 1 byte for each topic's Qos
295
+ // QoS on Subscribe only
296
+ break;
297
+
298
+ case MESSAGE_TYPE.UNSUBSCRIBE:
299
+ first |= 0x02; // Qos = 1;
300
+ for ( var i = 0; i < this.topics.length; i++) {
301
+ topicStrLength[i] = UTF8Length(this.topics[i]);
302
+ remLength += topicStrLength[i] + 2;
303
+ }
304
+ break;
305
+
306
+ case MESSAGE_TYPE.PUBLISH:
307
+ if (this.payloadMessage.duplicate) first |= 0x08;
308
+ first = first |= (this.payloadMessage.qos << 1);
309
+ if (this.payloadMessage.retained) first |= 0x01;
310
+ destinationNameLength = UTF8Length(this.payloadMessage.destinationName);
311
+ remLength += destinationNameLength + 2;
312
+ var payloadBytes = this.payloadMessage.payloadBytes;
313
+ remLength += payloadBytes.byteLength;
314
+ if (payloadBytes instanceof ArrayBuffer)
315
+ payloadBytes = new Uint8Array(payloadBytes);
316
+ else if (!(payloadBytes instanceof Uint8Array))
317
+ payloadBytes = new Uint8Array(payloadBytes.buffer);
318
+ break;
319
+
320
+ case MESSAGE_TYPE.DISCONNECT:
321
+ break;
322
+
323
+ default:
324
+ ;
325
+ }
326
+
327
+ // Now we can allocate a buffer for the message
328
+
329
+ var mbi = encodeMBI(remLength); // Convert the length to MQTT MBI format
330
+ var pos = mbi.length + 1; // Offset of start of variable header
331
+ var buffer = new ArrayBuffer(remLength + pos);
332
+ var byteStream = new Uint8Array(buffer); // view it as a sequence of bytes
333
+
334
+ //Write the fixed header into the buffer
335
+ byteStream[0] = first;
336
+ byteStream.set(mbi,1);
337
+
338
+ // If this is a PUBLISH then the variable header starts with a topic
339
+ if (this.type == MESSAGE_TYPE.PUBLISH)
340
+ pos = writeString(this.payloadMessage.destinationName, destinationNameLength, byteStream, pos);
341
+ // If this is a CONNECT then the variable header contains the protocol name/version, flags and keepalive time
342
+
343
+ else if (this.type == MESSAGE_TYPE.CONNECT) {
344
+ byteStream.set(MqttProtoIdentifier, pos);
345
+ pos += MqttProtoIdentifier.length;
346
+ var connectFlags = 0;
347
+ if (this.cleanSession)
348
+ connectFlags = 0x02;
349
+ if (this.willMessage != undefined ) {
350
+ connectFlags |= 0x04;
351
+ connectFlags |= (this.willMessage.qos<<3);
352
+ if (this.willMessage.retained) {
353
+ connectFlags |= 0x20;
354
+ }
355
+ }
356
+ if (this.userName != undefined)
357
+ connectFlags |= 0x80;
358
+ if (this.password != undefined)
359
+ connectFlags |= 0x40;
360
+ byteStream[pos++] = connectFlags;
361
+ pos = writeUint16 (this.keepAliveInterval, byteStream, pos);
362
+ }
363
+
364
+ // Output the messageIdentifier - if there is one
365
+ if (this.messageIdentifier != undefined)
366
+ pos = writeUint16 (this.messageIdentifier, byteStream, pos);
367
+
368
+ switch(this.type) {
369
+ case MESSAGE_TYPE.CONNECT:
370
+ pos = writeString(this.clientId, UTF8Length(this.clientId), byteStream, pos);
371
+ if (this.willMessage != undefined) {
372
+ pos = writeString(this.willMessage.destinationName, UTF8Length(this.willMessage.destinationName), byteStream, pos);
373
+ pos = writeUint16(willMessagePayloadBytes.byteLength, byteStream, pos);
374
+ byteStream.set(willMessagePayloadBytes, pos);
375
+ pos += willMessagePayloadBytes.byteLength;
376
+
377
+ }
378
+ if (this.userName != undefined)
379
+ pos = writeString(this.userName, UTF8Length(this.userName), byteStream, pos);
380
+ if (this.password != undefined)
381
+ pos = writeString(this.password, UTF8Length(this.password), byteStream, pos);
382
+ break;
383
+
384
+ case MESSAGE_TYPE.PUBLISH:
385
+ // PUBLISH has a text or binary payload, if text do not add a 2 byte length field, just the UTF characters.
386
+ byteStream.set(payloadBytes, pos);
387
+
388
+ break;
389
+
390
+ // case MESSAGE_TYPE.PUBREC:
391
+ // case MESSAGE_TYPE.PUBREL:
392
+ // case MESSAGE_TYPE.PUBCOMP:
393
+ // break;
394
+
395
+ case MESSAGE_TYPE.SUBSCRIBE:
396
+ // SUBSCRIBE has a list of topic strings and request QoS
397
+ for (var i=0; i<this.topics.length; i++) {
398
+ pos = writeString(this.topics[i], topicStrLength[i], byteStream, pos);
399
+ byteStream[pos++] = this.requestedQos[i];
400
+ }
401
+ break;
402
+
403
+ case MESSAGE_TYPE.UNSUBSCRIBE:
404
+ // UNSUBSCRIBE has a list of topic strings
405
+ for (var i=0; i<this.topics.length; i++)
406
+ pos = writeString(this.topics[i], topicStrLength[i], byteStream, pos);
407
+ break;
408
+
409
+ default:
410
+ // Do nothing.
411
+ }
412
+
413
+ return buffer;
414
+ }
415
+
416
+ function decodeMessage(input,pos) {
417
+ var startingPos = pos;
418
+ var first = input[pos];
419
+ var type = first >> 4;
420
+ var messageInfo = first &= 0x0f;
421
+ pos += 1;
422
+
423
+
424
+ // Decode the remaining length (MBI format)
425
+
426
+ var digit;
427
+ var remLength = 0;
428
+ var multiplier = 1;
429
+ do {
430
+ if (pos == input.length) {
431
+ return [null,startingPos];
432
+ }
433
+ digit = input[pos++];
434
+ remLength += ((digit & 0x7F) * multiplier);
435
+ multiplier *= 128;
436
+ } while ((digit & 0x80) != 0);
437
+
438
+ var endPos = pos+remLength;
439
+ if (endPos > input.length) {
440
+ return [null,startingPos];
441
+ }
442
+
443
+ var wireMessage = new WireMessage(type);
444
+ switch(type) {
445
+ case MESSAGE_TYPE.CONNACK:
446
+ wireMessage.topicNameCompressionResponse = input[pos++];
447
+ wireMessage.returnCode = input[pos++];
448
+ break;
449
+
450
+ case MESSAGE_TYPE.PUBLISH:
451
+ var qos = (messageInfo >> 1) & 0x03;
452
+
453
+ var len = readUint16(input, pos);
454
+ pos += 2;
455
+ var topicName = parseUTF8(input, pos, len);
456
+ pos += len;
457
+ // If QoS 1 or 2 there will be a messageIdentifier
458
+ if (qos > 0) {
459
+ wireMessage.messageIdentifier = readUint16(input, pos);
460
+ pos += 2;
461
+ }
462
+
463
+ var message = new Messaging.Message(input.subarray(pos));
464
+ if ((messageInfo & 0x01) == 0x01)
465
+ message.retained = true;
466
+ if ((messageInfo & 0x08) == 0x08)
467
+ message.duplicate = true;
468
+ message.qos = qos;
469
+ message.destinationName = topicName;
470
+ wireMessage.payloadMessage = message;
471
+ break;
472
+
473
+ case MESSAGE_TYPE.PUBACK:
474
+ case MESSAGE_TYPE.PUBREC:
475
+ case MESSAGE_TYPE.PUBREL:
476
+ case MESSAGE_TYPE.PUBCOMP:
477
+ case MESSAGE_TYPE.UNSUBACK:
478
+ wireMessage.messageIdentifier = readUint16(input, pos);
479
+ break;
480
+
481
+ case MESSAGE_TYPE.SUBACK:
482
+ wireMessage.messageIdentifier = readUint16(input, pos);
483
+ pos += 2;
484
+ wireMessage.grantedQos = input.subarray(pos);
485
+ break;
486
+
487
+ default:
488
+ ;
489
+ }
490
+
491
+ return [wireMessage,endPos];
492
+ }
493
+
494
+ function writeUint16(input, buffer, offset) {
495
+ buffer[offset++] = input >> 8; //MSB
496
+ buffer[offset++] = input % 256; //LSB
497
+ return offset;
498
+ }
499
+
500
+ function writeString(input, utf8Length, buffer, offset) {
501
+ offset = writeUint16(utf8Length, buffer, offset);
502
+ stringToUTF8(input, buffer, offset);
503
+ return offset + utf8Length;
504
+ }
505
+
506
+ function readUint16(buffer, offset) {
507
+ return 256*buffer[offset] + buffer[offset+1];
508
+ }
509
+
510
+ /**
511
+ * Encodes an MQTT Multi-Byte Integer
512
+ * @private
513
+ */
514
+ function encodeMBI(number) {
515
+ var output = new Array(1);
516
+ var numBytes = 0;
517
+
518
+ do {
519
+ var digit = number % 128;
520
+ number = number >> 7;
521
+ if (number > 0) {
522
+ digit |= 0x80;
523
+ }
524
+ output[numBytes++] = digit;
525
+ } while ( (number > 0) && (numBytes<4) );
526
+
527
+ return output;
528
+ }
529
+
530
+ /**
531
+ * Takes a String and calculates its length in bytes when encoded in UTF8.
532
+ * @private
533
+ */
534
+ function UTF8Length(input) {
535
+ var output = 0;
536
+ for (var i = 0; i<input.length; i++)
537
+ {
538
+ var charCode = input.charCodeAt(i);
539
+ if (charCode > 0x7FF)
540
+ {
541
+ // Surrogate pair means its a 4 byte character
542
+ if (0xD800 <= charCode && charCode <= 0xDBFF)
543
+ {
544
+ i++;
545
+ output++;
546
+ }
547
+ output +=3;
548
+ }
549
+ else if (charCode > 0x7F)
550
+ output +=2;
551
+ else
552
+ output++;
553
+ }
554
+ return output;
555
+ }
556
+
557
+ /**
558
+ * Takes a String and writes it into an array as UTF8 encoded bytes.
559
+ * @private
560
+ */
561
+ function stringToUTF8(input, output, start) {
562
+ var pos = start;
563
+ for (var i = 0; i<input.length; i++) {
564
+ var charCode = input.charCodeAt(i);
565
+
566
+ // Check for a surrogate pair.
567
+ if (0xD800 <= charCode && charCode <= 0xDBFF) {
568
+ lowCharCode = input.charCodeAt(++i);
569
+ if (isNaN(lowCharCode)) {
570
+ throw new Error(format(ERROR.MALFORMED_UNICODE, [charCode, lowCharCode]));
571
+ }
572
+ charCode = ((charCode - 0xD800)<<10) + (lowCharCode - 0xDC00) + 0x10000;
573
+
574
+ }
575
+
576
+ if (charCode <= 0x7F) {
577
+ output[pos++] = charCode;
578
+ } else if (charCode <= 0x7FF) {
579
+ output[pos++] = charCode>>6 & 0x1F | 0xC0;
580
+ output[pos++] = charCode & 0x3F | 0x80;
581
+ } else if (charCode <= 0xFFFF) {
582
+ output[pos++] = charCode>>12 & 0x0F | 0xE0;
583
+ output[pos++] = charCode>>6 & 0x3F | 0x80;
584
+ output[pos++] = charCode & 0x3F | 0x80;
585
+ } else {
586
+ output[pos++] = charCode>>18 & 0x07 | 0xF0;
587
+ output[pos++] = charCode>>12 & 0x3F | 0x80;
588
+ output[pos++] = charCode>>6 & 0x3F | 0x80;
589
+ output[pos++] = charCode & 0x3F | 0x80;
590
+ };
591
+ }
592
+ return output;
593
+ }
594
+
595
+ function parseUTF8(input, offset, length) {
596
+ var output = "";
597
+ var utf16;
598
+ var pos = offset;
599
+
600
+ while (pos < offset+length)
601
+ {
602
+ var byte1 = input[pos++];
603
+ if (byte1 < 128)
604
+ utf16 = byte1;
605
+ else
606
+ {
607
+ var byte2 = input[pos++]-128;
608
+ if (byte2 < 0)
609
+ throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16),""]));
610
+ if (byte1 < 0xE0) // 2 byte character
611
+ utf16 = 64*(byte1-0xC0) + byte2;
612
+ else
613
+ {
614
+ var byte3 = input[pos++]-128;
615
+ if (byte3 < 0)
616
+ throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16)]));
617
+ if (byte1 < 0xF0) // 3 byte character
618
+ utf16 = 4096*(byte1-0xE0) + 64*byte2 + byte3;
619
+ else
620
+ {
621
+ var byte4 = input[pos++]-128;
622
+ if (byte4 < 0)
623
+ throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16), byte4.toString(16)]));
624
+ if (byte1 < 0xF8) // 4 byte character
625
+ utf16 = 262144*(byte1-0xF0) + 4096*byte2 + 64*byte3 + byte4;
626
+ else // longer encodings are not supported
627
+ throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16), byte4.toString(16)]));
628
+ }
629
+ }
630
+ }
631
+
632
+ if (utf16 > 0xFFFF) // 4 byte character - express as a surrogate pair
633
+ {
634
+ utf16 -= 0x10000;
635
+ output += String.fromCharCode(0xD800 + (utf16 >> 10)); // lead character
636
+ utf16 = 0xDC00 + (utf16 & 0x3FF); // trail character
637
+ }
638
+ output += String.fromCharCode(utf16);
639
+ }
640
+ return output;
641
+ }
642
+
643
+ /**
644
+ * Repeat keepalive requests, monitor responses.
645
+ * @ignore
646
+ */
647
+ var Pinger = function(client, window, keepAliveInterval) {
648
+ this._client = client;
649
+ this._window = window;
650
+ this._keepAliveInterval = keepAliveInterval*1000;
651
+ this.isReset = false;
652
+
653
+ var pingReq = new WireMessage(MESSAGE_TYPE.PINGREQ).encode();
654
+
655
+ var doTimeout = function (pinger) {
656
+ return function () {
657
+ return doPing.apply(pinger);
658
+ };
659
+ };
660
+
661
+ /** @ignore */
662
+ var doPing = function() {
663
+ if (!this.isReset) {
664
+ this._client._trace("Pinger.doPing", "Timed out");
665
+ this._client._disconnected( ERROR.PING_TIMEOUT.code , format(ERROR.PING_TIMEOUT));
666
+ } else {
667
+ this.isReset = false;
668
+ this._client._trace("Pinger.doPing", "send PINGREQ");
669
+ this._client.socket.send(pingReq);
670
+ this.timeout = this._window.setTimeout(doTimeout(this), this._keepAliveInterval);
671
+ }
672
+ }
673
+
674
+ this.reset = function() {
675
+ this.isReset = true;
676
+ this._window.clearTimeout(this.timeout);
677
+ if (this._keepAliveInterval > 0)
678
+ this.timeout = setTimeout(doTimeout(this), this._keepAliveInterval);
679
+ }
680
+
681
+ this.cancel = function() {
682
+ this._window.clearTimeout(this.timeout);
683
+ }
684
+ };
685
+
686
+ /**
687
+ * Monitor request completion.
688
+ * @ignore
689
+ */
690
+ var Timeout = function(client, window, timeoutSeconds, action, args) {
691
+ this._window = window;
692
+ if (!timeoutSeconds)
693
+ timeoutSeconds = 30;
694
+
695
+ var doTimeout = function (action, client, args) {
696
+ return function () {
697
+ return action.apply(client, args);
698
+ };
699
+ };
700
+ this.timeout = setTimeout(doTimeout(action, client, args), timeoutSeconds * 1000);
701
+
702
+ this.cancel = function() {
703
+ this._window.clearTimeout(this.timeout);
704
+ }
705
+ };
706
+
707
+ /*
708
+ * Internal implementation of the Websockets MQTT V3.1 client.
709
+ *
710
+ * @name Messaging.ClientImpl @constructor
711
+ * @param {String} host the DNS nameof the webSocket host.
712
+ * @param {Number} port the port number for that host.
713
+ * @param {String} clientId the MQ client identifier.
714
+ */
715
+ var ClientImpl = function (uri, host, port, path, clientId) {
716
+ // Check dependencies are satisfied in this browser.
717
+ if (!("WebSocket" in global && global["WebSocket"] !== null)) {
718
+ throw new Error(format(ERROR.UNSUPPORTED, ["WebSocket"]));
719
+ }
720
+ if (!("localStorage" in global && global["localStorage"] !== null)) {
721
+ throw new Error(format(ERROR.UNSUPPORTED, ["localStorage"]));
722
+ }
723
+ if (!("ArrayBuffer" in global && global["ArrayBuffer"] !== null)) {
724
+ throw new Error(format(ERROR.UNSUPPORTED, ["ArrayBuffer"]));
725
+ }
726
+ this._trace("Messaging.Client", uri, host, port, path, clientId);
727
+
728
+ this.host = host;
729
+ this.port = port;
730
+ this.path = path;
731
+ this.uri = uri;
732
+ this.clientId = clientId;
733
+
734
+ // Local storagekeys are qualified with the following string.
735
+ // The conditional inclusion of path in the key is for backward
736
+ // compatibility to when the path was not configurable and assumed to
737
+ // be /mqtt
738
+ this._localKey=host+":"+port+(path!="/mqtt"?":"+path:"")+":"+clientId+":";
739
+
740
+ // Create private instance-only message queue
741
+ // Internal queue of messages to be sent, in sending order.
742
+ this._msg_queue = [];
743
+
744
+ // Messages we have sent and are expecting a response for, indexed by their respective message ids.
745
+ this._sentMessages = {};
746
+
747
+ // Messages we have received and acknowleged and are expecting a confirm message for
748
+ // indexed by their respective message ids.
749
+ this._receivedMessages = {};
750
+
751
+ // Internal list of callbacks to be executed when messages
752
+ // have been successfully sent over web socket, e.g. disconnect
753
+ // when it doesn't have to wait for ACK, just message is dispatched.
754
+ this._notify_msg_sent = {};
755
+
756
+ // Unique identifier for SEND messages, incrementing
757
+ // counter as messages are sent.
758
+ this._message_identifier = 1;
759
+
760
+ // Used to determine the transmission sequence of stored sent messages.
761
+ this._sequence = 0;
762
+
763
+
764
+ // Load the local state, if any, from the saved version, only restore state relevant to this client.
765
+ for(key in localStorage)
766
+ if ( key.indexOf("Sent:"+this._localKey) == 0
767
+ || key.indexOf("Received:"+this._localKey) == 0)
768
+ this.restore(key);
769
+ };
770
+
771
+ // Messaging Client public instance members.
772
+ ClientImpl.prototype.host;
773
+ ClientImpl.prototype.port;
774
+ ClientImpl.prototype.path;
775
+ ClientImpl.prototype.uri;
776
+ ClientImpl.prototype.clientId;
777
+
778
+ // Messaging Client private instance members.
779
+ ClientImpl.prototype.socket;
780
+ /* true once we have received an acknowledgement to a CONNECT packet. */
781
+ ClientImpl.prototype.connected = false;
782
+ /* The largest message identifier allowed, may not be larger than 2**16 but
783
+ * if set smaller reduces the maximum number of outbound messages allowed.
784
+ */
785
+ ClientImpl.prototype.maxMessageIdentifier = 65536;
786
+ ClientImpl.prototype.connectOptions;
787
+ ClientImpl.prototype.hostIndex;
788
+ ClientImpl.prototype.onConnectionLost;
789
+ ClientImpl.prototype.onMessageDelivered;
790
+ ClientImpl.prototype.onMessageArrived;
791
+ ClientImpl.prototype._msg_queue = null;
792
+ ClientImpl.prototype._connectTimeout;
793
+ /* The sendPinger monitors how long we allow before we send data to prove to the server that we are alive. */
794
+ ClientImpl.prototype.sendPinger = null;
795
+ /* The receivePinger monitors how long we allow before we require evidence that the server is alive. */
796
+ ClientImpl.prototype.receivePinger = null;
797
+
798
+ ClientImpl.prototype.receiveBuffer = null;
799
+
800
+ ClientImpl.prototype._traceBuffer = null;
801
+ ClientImpl.prototype._MAX_TRACE_ENTRIES = 100;
802
+
803
+ ClientImpl.prototype.connect = function (connectOptions) {
804
+ var connectOptionsMasked = this._traceMask(connectOptions, "password");
805
+ this._trace("Client.connect", connectOptionsMasked, this.socket, this.connected);
806
+
807
+ if (this.connected)
808
+ throw new Error(format(ERROR.INVALID_STATE, ["already connected"]));
809
+ if (this.socket)
810
+ throw new Error(format(ERROR.INVALID_STATE, ["already connected"]));
811
+
812
+ this.connectOptions = connectOptions;
813
+
814
+ if (connectOptions.uris) {
815
+ this.hostIndex = 0;
816
+ this._doConnect(connectOptions.uris[0]);
817
+ } else {
818
+ this._doConnect(this.uri);
819
+ }
820
+
821
+ };
822
+
823
+ ClientImpl.prototype.subscribe = function (filter, subscribeOptions) {
824
+ this._trace("Client.subscribe", filter, subscribeOptions);
825
+
826
+ if (!this.connected)
827
+ throw new Error(format(ERROR.INVALID_STATE, ["not connected"]));
828
+
829
+ var wireMessage = new WireMessage(MESSAGE_TYPE.SUBSCRIBE);
830
+ wireMessage.topics=[filter];
831
+ if (subscribeOptions.qos != undefined)
832
+ wireMessage.requestedQos = [subscribeOptions.qos];
833
+ else
834
+ wireMessage.requestedQos = [0];
835
+
836
+ if (subscribeOptions.onSuccess) {
837
+ wireMessage.callback = function() {subscribeOptions.onSuccess({invocationContext:subscribeOptions.invocationContext});};
838
+ }
839
+ if (subscribeOptions.timeout) {
840
+ wireMessage.timeOut = new Timeout(this, window, subscribeOptions.timeout, subscribeOptions.onFailure
841
+ , [{invocationContext:subscribeOptions.invocationContext,
842
+ errorCode:ERROR.SUBSCRIBE_TIMEOUT.code,
843
+ errorMessage:format(ERROR.SUBSCRIBE_TIMEOUT)}]);
844
+ }
845
+
846
+ // All subscriptions return a SUBACK.
847
+ this._requires_ack(wireMessage);
848
+ this._schedule_message(wireMessage);
849
+ };
850
+
851
+ /** @ignore */
852
+ ClientImpl.prototype.unsubscribe = function(filter, unsubscribeOptions) {
853
+ this._trace("Client.unsubscribe", filter, unsubscribeOptions);
854
+
855
+ if (!this.connected)
856
+ throw new Error(format(ERROR.INVALID_STATE, ["not connected"]));
857
+
858
+ var wireMessage = new WireMessage(MESSAGE_TYPE.UNSUBSCRIBE);
859
+ wireMessage.topics = [filter];
860
+
861
+ if (unsubscribeOptions.onSuccess) {
862
+ wireMessage.callback = function() {unsubscribeOptions.onSuccess({invocationContext:unsubscribeOptions.invocationContext});};
863
+ }
864
+ if (unsubscribeOptions.timeout) {
865
+ wireMessage.timeOut = new Timeout(this, window, unsubscribeOptions.timeout, unsubscribeOptions.onFailure
866
+ , [{invocationContext:unsubscribeOptions.invocationContext,
867
+ errorCode:ERROR.UNSUBSCRIBE_TIMEOUT.code,
868
+ errorMessage:format(ERROR.UNSUBSCRIBE_TIMEOUT)}]);
869
+ }
870
+
871
+ // All unsubscribes return a SUBACK.
872
+ this._requires_ack(wireMessage);
873
+ this._schedule_message(wireMessage);
874
+ };
875
+
876
+ ClientImpl.prototype.send = function (message) {
877
+ this._trace("Client.send", message);
878
+
879
+ if (!this.connected)
880
+ throw new Error(format(ERROR.INVALID_STATE, ["not connected"]));
881
+
882
+ wireMessage = new WireMessage(MESSAGE_TYPE.PUBLISH);
883
+ wireMessage.payloadMessage = message;
884
+
885
+ if (message.qos > 0)
886
+ this._requires_ack(wireMessage);
887
+ else if (this.onMessageDelivered)
888
+ this._notify_msg_sent[wireMessage] = this.onMessageDelivered(wireMessage.payloadMessage);
889
+ this._schedule_message(wireMessage);
890
+ };
891
+
892
+ ClientImpl.prototype.disconnect = function () {
893
+ this._trace("Client.disconnect");
894
+
895
+ if (!this.socket)
896
+ throw new Error(format(ERROR.INVALID_STATE, ["not connecting or connected"]));
897
+
898
+ wireMessage = new WireMessage(MESSAGE_TYPE.DISCONNECT);
899
+
900
+ // Run the disconnected call back as soon as the message has been sent,
901
+ // in case of a failure later on in the disconnect processing.
902
+ // as a consequence, the _disconected call back may be run several times.
903
+ this._notify_msg_sent[wireMessage] = scope(this._disconnected, this);
904
+
905
+ this._schedule_message(wireMessage);
906
+ };
907
+
908
+ ClientImpl.prototype.getTraceLog = function () {
909
+ if ( this._traceBuffer !== null ) {
910
+ this._trace("Client.getTraceLog", new Date());
911
+ this._trace("Client.getTraceLog in flight messages", this._sentMessages.length);
912
+ for (key in this._sentMessages)
913
+ this._trace("_sentMessages ",key, this._sentMessages[key]);
914
+ for (key in this._receivedMessages)
915
+ this._trace("_receivedMessages ",key, this._receivedMessages[key]);
916
+
917
+ return this._traceBuffer;
918
+ }
919
+ };
920
+
921
+ ClientImpl.prototype.startTrace = function () {
922
+ if ( this._traceBuffer === null ) {
923
+ this._traceBuffer = [];
924
+ }
925
+ this._trace("Client.startTrace", new Date(), version);
926
+ };
927
+
928
+ ClientImpl.prototype.stopTrace = function () {
929
+ delete this._traceBuffer;
930
+ };
931
+
932
+ ClientImpl.prototype._doConnect = function (wsurl) {
933
+ // When the socket is open, this client will send the CONNECT WireMessage using the saved parameters.
934
+ if (this.connectOptions.useSSL) {
935
+ var uriParts = wsurl.split(":");
936
+ uriParts[0] = "wss";
937
+ wsurl = uriParts.join(":");
938
+ }
939
+ this.connected = false;
940
+ this.socket = new WebSocket(wsurl, "mqttv3.1");
941
+ this.socket.binaryType = 'arraybuffer';
942
+
943
+ this.socket.onopen = scope(this._on_socket_open, this);
944
+ this.socket.onmessage = scope(this._on_socket_message, this);
945
+ this.socket.onerror = scope(this._on_socket_error, this);
946
+ this.socket.onclose = scope(this._on_socket_close, this);
947
+
948
+ this.sendPinger = new Pinger(this, window, this.connectOptions.keepAliveInterval);
949
+ this.receivePinger = new Pinger(this, window, this.connectOptions.keepAliveInterval);
950
+
951
+ this._connectTimeout = new Timeout(this, window, this.connectOptions.timeout, this._disconnected, [ERROR.CONNECT_TIMEOUT.code, format(ERROR.CONNECT_TIMEOUT)]);
952
+ };
953
+
954
+
955
+ // Schedule a new message to be sent over the WebSockets
956
+ // connection. CONNECT messages cause WebSocket connection
957
+ // to be started. All other messages are queued internally
958
+ // until this has happened. When WS connection starts, process
959
+ // all outstanding messages.
960
+ ClientImpl.prototype._schedule_message = function (message) {
961
+ this._msg_queue.push(message);
962
+ // Process outstanding messages in the queue if we have an open socket, and have received CONNACK.
963
+ if (this.connected) {
964
+ this._process_queue();
965
+ }
966
+ };
967
+
968
+ ClientImpl.prototype.store = function(prefix, wireMessage) {
969
+ storedMessage = {type:wireMessage.type, messageIdentifier:wireMessage.messageIdentifier, version:1};
970
+
971
+ switch(wireMessage.type) {
972
+ case MESSAGE_TYPE.PUBLISH:
973
+ if(wireMessage.pubRecReceived)
974
+ storedMessage.pubRecReceived = true;
975
+
976
+ // Convert the payload to a hex string.
977
+ storedMessage.payloadMessage = {};
978
+ var hex = "";
979
+ var messageBytes = wireMessage.payloadMessage.payloadBytes;
980
+ for (var i=0; i<messageBytes.length; i++) {
981
+ if (messageBytes[i] <= 0xF)
982
+ hex = hex+"0"+messageBytes[i].toString(16);
983
+ else
984
+ hex = hex+messageBytes[i].toString(16);
985
+ }
986
+ storedMessage.payloadMessage.payloadHex = hex;
987
+
988
+ storedMessage.payloadMessage.qos = wireMessage.payloadMessage.qos;
989
+ storedMessage.payloadMessage.destinationName = wireMessage.payloadMessage.destinationName;
990
+ if (wireMessage.payloadMessage.duplicate)
991
+ storedMessage.payloadMessage.duplicate = true;
992
+ if (wireMessage.payloadMessage.retained)
993
+ storedMessage.payloadMessage.retained = true;
994
+
995
+ // Add a sequence number to sent messages.
996
+ if ( prefix.indexOf("Sent:") == 0 ) {
997
+ if ( wireMessage.sequence === undefined )
998
+ wireMessage.sequence = ++this._sequence;
999
+ storedMessage.sequence = wireMessage.sequence;
1000
+ }
1001
+ break;
1002
+
1003
+ default:
1004
+ throw Error(format(ERROR.INVALID_STORED_DATA, [key, storedMessage]));
1005
+ }
1006
+ localStorage.setItem(prefix+this._localKey+wireMessage.messageIdentifier, JSON.stringify(storedMessage));
1007
+ };
1008
+
1009
+ ClientImpl.prototype.restore = function(key) {
1010
+ var value = localStorage.getItem(key);
1011
+ var storedMessage = JSON.parse(value);
1012
+
1013
+ var wireMessage = new WireMessage(storedMessage.type, storedMessage);
1014
+
1015
+ switch(storedMessage.type) {
1016
+ case MESSAGE_TYPE.PUBLISH:
1017
+ // Replace the payload message with a Message object.
1018
+ var hex = storedMessage.payloadMessage.payloadHex;
1019
+ var buffer = new ArrayBuffer((hex.length)/2);
1020
+ var byteStream = new Uint8Array(buffer);
1021
+ var i = 0;
1022
+ while (hex.length >= 2) {
1023
+ var x = parseInt(hex.substring(0, 2), 16);
1024
+ hex = hex.substring(2, hex.length);
1025
+ byteStream[i++] = x;
1026
+ }
1027
+ var payloadMessage = new Messaging.Message(byteStream);
1028
+
1029
+ payloadMessage.qos = storedMessage.payloadMessage.qos;
1030
+ payloadMessage.destinationName = storedMessage.payloadMessage.destinationName;
1031
+ if (storedMessage.payloadMessage.duplicate)
1032
+ payloadMessage.duplicate = true;
1033
+ if (storedMessage.payloadMessage.retained)
1034
+ payloadMessage.retained = true;
1035
+ wireMessage.payloadMessage = payloadMessage;
1036
+
1037
+ break;
1038
+
1039
+ default:
1040
+ throw Error(format(ERROR.INVALID_STORED_DATA, [key, value]));
1041
+ }
1042
+
1043
+ if (key.indexOf("Sent:"+this._localKey) == 0) {
1044
+ this._sentMessages[wireMessage.messageIdentifier] = wireMessage;
1045
+ } else if (key.indexOf("Received:"+this._localKey) == 0) {
1046
+ this._receivedMessages[wireMessage.messageIdentifier] = wireMessage;
1047
+ }
1048
+ };
1049
+
1050
+ ClientImpl.prototype._process_queue = function () {
1051
+ var message = null;
1052
+ // Process messages in order they were added
1053
+ var fifo = this._msg_queue.reverse();
1054
+
1055
+ // Send all queued messages down socket connection
1056
+ while ((message = fifo.pop())) {
1057
+ this._socket_send(message);
1058
+ // Notify listeners that message was successfully sent
1059
+ if (this._notify_msg_sent[message]) {
1060
+ this._notify_msg_sent[message]();
1061
+ delete this._notify_msg_sent[message];
1062
+ }
1063
+ }
1064
+ };
1065
+
1066
+ /**
1067
+ * Expect an ACK response for this message. Add message to the set of in progress
1068
+ * messages and set an unused identifier in this message.
1069
+ * @ignore
1070
+ */
1071
+ ClientImpl.prototype._requires_ack = function (wireMessage) {
1072
+ var messageCount = Object.keys(this._sentMessages).length;
1073
+ if (messageCount > this.maxMessageIdentifier)
1074
+ throw Error ("Too many messages:"+messageCount);
1075
+
1076
+ while(this._sentMessages[this._message_identifier] !== undefined) {
1077
+ this._message_identifier++;
1078
+ }
1079
+ wireMessage.messageIdentifier = this._message_identifier;
1080
+ this._sentMessages[wireMessage.messageIdentifier] = wireMessage;
1081
+ if (wireMessage.type === MESSAGE_TYPE.PUBLISH) {
1082
+ this.store("Sent:", wireMessage);
1083
+ }
1084
+ if (this._message_identifier === this.maxMessageIdentifier) {
1085
+ this._message_identifier = 1;
1086
+ }
1087
+ };
1088
+
1089
+ /**
1090
+ * Called when the underlying websocket has been opened.
1091
+ * @ignore
1092
+ */
1093
+ ClientImpl.prototype._on_socket_open = function () {
1094
+ // Create the CONNECT message object.
1095
+ var wireMessage = new WireMessage(MESSAGE_TYPE.CONNECT, this.connectOptions);
1096
+ wireMessage.clientId = this.clientId;
1097
+ this._socket_send(wireMessage);
1098
+ };
1099
+
1100
+ /**
1101
+ * Called when the underlying websocket has received a complete packet.
1102
+ * @ignore
1103
+ */
1104
+ ClientImpl.prototype._on_socket_message = function (event) {
1105
+ this._trace("Client._on_socket_message", event.data);
1106
+ // Reset the receive ping timer, we now have evidence the server is alive.
1107
+ this.receivePinger.reset();
1108
+ var messages = this._deframeMessages(event.data);
1109
+ for (var i = 0; i < messages.length; i+=1) {
1110
+ this._handleMessage(messages[i]);
1111
+ }
1112
+ }
1113
+
1114
+ ClientImpl.prototype._deframeMessages = function(data) {
1115
+ var byteArray = new Uint8Array(data);
1116
+ if (this.receiveBuffer) {
1117
+ var newData = new Uint8Array(this.receiveBuffer.length+byteArray.length);
1118
+ newData.set(this.receiveBuffer);
1119
+ newData.set(byteArray,this.receiveBuffer.length);
1120
+ byteArray = newData;
1121
+ delete this.receiveBuffer;
1122
+ }
1123
+ try {
1124
+ var offset = 0;
1125
+ var messages = [];
1126
+ while(offset < byteArray.length) {
1127
+ var result = decodeMessage(byteArray,offset);
1128
+ var wireMessage = result[0];
1129
+ offset = result[1];
1130
+ if (wireMessage !== null) {
1131
+ messages.push(wireMessage);
1132
+ } else {
1133
+ break;
1134
+ }
1135
+ }
1136
+ if (offset < byteArray.length) {
1137
+ this.receiveBuffer = byteArray.subarray(offset);
1138
+ }
1139
+ } catch (error) {
1140
+ this._disconnected(ERROR.INTERNAL_ERROR.code , format(ERROR.INTERNAL_ERROR, [error.message]));
1141
+ return;
1142
+ }
1143
+ return messages;
1144
+ }
1145
+
1146
+ ClientImpl.prototype._handleMessage = function(wireMessage) {
1147
+
1148
+ this._trace("Client._handleMessage", wireMessage);
1149
+
1150
+ try {
1151
+ switch(wireMessage.type) {
1152
+ case MESSAGE_TYPE.CONNACK:
1153
+ this._connectTimeout.cancel();
1154
+
1155
+ // If we have started using clean session then clear up the local state.
1156
+ if (this.connectOptions.cleanSession) {
1157
+ for (key in this._sentMessages) {
1158
+ var sentMessage = this._sentMessages[key];
1159
+ localStorage.removeItem("Sent:"+this._localKey+sentMessage.messageIdentifier);
1160
+ }
1161
+ this._sentMessages = {};
1162
+
1163
+ for (key in this._receivedMessages) {
1164
+ var receivedMessage = this._receivedMessages[key];
1165
+ localStorage.removeItem("Received:"+this._localKey+receivedMessage.messageIdentifier);
1166
+ }
1167
+ this._receivedMessages = {};
1168
+ }
1169
+ // Client connected and ready for business.
1170
+ if (wireMessage.returnCode === 0) {
1171
+ this.connected = true;
1172
+ // Jump to the end of the list of uris and stop looking for a good host.
1173
+ if (this.connectOptions.uris)
1174
+ this.hostIndex = this.connectOptions.uris.length;
1175
+ } else {
1176
+ this._disconnected(ERROR.CONNACK_RETURNCODE.code , format(ERROR.CONNACK_RETURNCODE, [wireMessage.returnCode, CONNACK_RC[wireMessage.returnCode]]));
1177
+ break;
1178
+ }
1179
+
1180
+ // Resend messages.
1181
+ var sequencedMessages = new Array();
1182
+ for (var msgId in this._sentMessages) {
1183
+ if (this._sentMessages.hasOwnProperty(msgId))
1184
+ sequencedMessages.push(this._sentMessages[msgId]);
1185
+ }
1186
+
1187
+ // Sort sentMessages into the original sent order.
1188
+ var sequencedMessages = sequencedMessages.sort(function(a,b) {return a.sequence - b.sequence;} );
1189
+ for (var i=0, len=sequencedMessages.length; i<len; i++) {
1190
+ var sentMessage = sequencedMessages[i];
1191
+ if (sentMessage.type == MESSAGE_TYPE.PUBLISH && sentMessage.pubRecReceived) {
1192
+ var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {messageIdentifier:sentMessage.messageIdentifier});
1193
+ this._schedule_message(pubRelMessage);
1194
+ } else {
1195
+ this._schedule_message(sentMessage);
1196
+ };
1197
+ }
1198
+
1199
+ // Execute the connectOptions.onSuccess callback if there is one.
1200
+ if (this.connectOptions.onSuccess) {
1201
+ this.connectOptions.onSuccess({invocationContext:this.connectOptions.invocationContext});
1202
+ }
1203
+
1204
+ // Process all queued messages now that the connection is established.
1205
+ this._process_queue();
1206
+ break;
1207
+
1208
+ case MESSAGE_TYPE.PUBLISH:
1209
+ this._receivePublish(wireMessage);
1210
+ break;
1211
+
1212
+ case MESSAGE_TYPE.PUBACK:
1213
+ var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1214
+ // If this is a re flow of a PUBACK after we have restarted receivedMessage will not exist.
1215
+ if (sentMessage) {
1216
+ delete this._sentMessages[wireMessage.messageIdentifier];
1217
+ localStorage.removeItem("Sent:"+this._localKey+wireMessage.messageIdentifier);
1218
+ if (this.onMessageDelivered)
1219
+ this.onMessageDelivered(sentMessage.payloadMessage);
1220
+ }
1221
+ break;
1222
+
1223
+ case MESSAGE_TYPE.PUBREC:
1224
+ var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1225
+ // If this is a re flow of a PUBREC after we have restarted receivedMessage will not exist.
1226
+ if (sentMessage) {
1227
+ sentMessage.pubRecReceived = true;
1228
+ var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {messageIdentifier:wireMessage.messageIdentifier});
1229
+ this.store("Sent:", sentMessage);
1230
+ this._schedule_message(pubRelMessage);
1231
+ }
1232
+ break;
1233
+
1234
+ case MESSAGE_TYPE.PUBREL:
1235
+ var receivedMessage = this._receivedMessages[wireMessage.messageIdentifier];
1236
+ localStorage.removeItem("Received:"+this._localKey+wireMessage.messageIdentifier);
1237
+ // If this is a re flow of a PUBREL after we have restarted receivedMessage will not exist.
1238
+ if (receivedMessage) {
1239
+ this._receiveMessage(receivedMessage);
1240
+ delete this._receivedMessages[wireMessage.messageIdentifier];
1241
+ }
1242
+ // Always flow PubComp, we may have previously flowed PubComp but the server lost it and restarted.
1243
+ pubCompMessage = new WireMessage(MESSAGE_TYPE.PUBCOMP, {messageIdentifier:wireMessage.messageIdentifier});
1244
+ this._schedule_message(pubCompMessage);
1245
+
1246
+
1247
+ break;
1248
+
1249
+ case MESSAGE_TYPE.PUBCOMP:
1250
+ var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1251
+ delete this._sentMessages[wireMessage.messageIdentifier];
1252
+ localStorage.removeItem("Sent:"+this._localKey+wireMessage.messageIdentifier);
1253
+ if (this.onMessageDelivered)
1254
+ this.onMessageDelivered(sentMessage.payloadMessage);
1255
+ break;
1256
+
1257
+ case MESSAGE_TYPE.SUBACK:
1258
+ var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1259
+ if (sentMessage) {
1260
+ if(sentMessage.timeOut)
1261
+ sentMessage.timeOut.cancel();
1262
+ if (sentMessage.callback) {
1263
+ sentMessage.callback();
1264
+ }
1265
+ delete this._sentMessages[wireMessage.messageIdentifier];
1266
+ }
1267
+ break;
1268
+
1269
+ case MESSAGE_TYPE.UNSUBACK:
1270
+ var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1271
+ if (sentMessage) {
1272
+ if (sentMessage.timeOut)
1273
+ sentMessage.timeOut.cancel();
1274
+ if (sentMessage.callback) {
1275
+ sentMessage.callback();
1276
+ }
1277
+ delete this._sentMessages[wireMessage.messageIdentifier];
1278
+ }
1279
+
1280
+ break;
1281
+
1282
+ case MESSAGE_TYPE.PINGRESP:
1283
+ /* The sendPinger or receivePinger may have sent a ping, the receivePinger has already been reset. */
1284
+ this.sendPinger.reset();
1285
+ break;
1286
+
1287
+ case MESSAGE_TYPE.DISCONNECT:
1288
+ // Clients do not expect to receive disconnect packets.
1289
+ this._disconnected(ERROR.INVALID_MQTT_MESSAGE_TYPE.code , format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type]));
1290
+ break;
1291
+
1292
+ default:
1293
+ this._disconnected(ERROR.INVALID_MQTT_MESSAGE_TYPE.code , format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type]));
1294
+ };
1295
+ } catch (error) {
1296
+ this._disconnected(ERROR.INTERNAL_ERROR.code , format(ERROR.INTERNAL_ERROR, [error.message]));
1297
+ return;
1298
+ }
1299
+ };
1300
+
1301
+ /** @ignore */
1302
+ ClientImpl.prototype._on_socket_error = function (error) {
1303
+ this._disconnected(ERROR.SOCKET_ERROR.code , format(ERROR.SOCKET_ERROR, [error.data]));
1304
+ };
1305
+
1306
+ /** @ignore */
1307
+ ClientImpl.prototype._on_socket_close = function () {
1308
+ this._disconnected(ERROR.SOCKET_CLOSE.code , format(ERROR.SOCKET_CLOSE));
1309
+ };
1310
+
1311
+ /** @ignore */
1312
+ ClientImpl.prototype._socket_send = function (wireMessage) {
1313
+
1314
+ if (wireMessage.type == 1) {
1315
+ var wireMessageMasked = this._traceMask(wireMessage, "password");
1316
+ this._trace("Client._socket_send", wireMessageMasked);
1317
+ }
1318
+ else this._trace("Client._socket_send", wireMessage);
1319
+
1320
+ this.socket.send(wireMessage.encode());
1321
+ /* We have proved to the server we are alive. */
1322
+ this.sendPinger.reset();
1323
+ };
1324
+
1325
+ /** @ignore */
1326
+ ClientImpl.prototype._receivePublish = function (wireMessage) {
1327
+ switch(wireMessage.payloadMessage.qos) {
1328
+ case "undefined":
1329
+ case 0:
1330
+ this._receiveMessage(wireMessage);
1331
+ break;
1332
+
1333
+ case 1:
1334
+ var pubAckMessage = new WireMessage(MESSAGE_TYPE.PUBACK, {messageIdentifier:wireMessage.messageIdentifier});
1335
+ this._schedule_message(pubAckMessage);
1336
+ this._receiveMessage(wireMessage);
1337
+ break;
1338
+
1339
+ case 2:
1340
+ this._receivedMessages[wireMessage.messageIdentifier] = wireMessage;
1341
+ this.store("Received:", wireMessage);
1342
+ var pubRecMessage = new WireMessage(MESSAGE_TYPE.PUBREC, {messageIdentifier:wireMessage.messageIdentifier});
1343
+ this._schedule_message(pubRecMessage);
1344
+
1345
+ break;
1346
+
1347
+ default:
1348
+ throw Error("Invaild qos="+wireMmessage.payloadMessage.qos);
1349
+ };
1350
+ };
1351
+
1352
+ /** @ignore */
1353
+ ClientImpl.prototype._receiveMessage = function (wireMessage) {
1354
+ if (this.onMessageArrived) {
1355
+ this.onMessageArrived(wireMessage.payloadMessage);
1356
+ }
1357
+ };
1358
+
1359
+ /**
1360
+ * Client has disconnected either at its own request or because the server
1361
+ * or network disconnected it. Remove all non-durable state.
1362
+ * @param {errorCode} [number] the error number.
1363
+ * @param {errorText} [string] the error text.
1364
+ * @ignore
1365
+ */
1366
+ ClientImpl.prototype._disconnected = function (errorCode, errorText) {
1367
+ this._trace("Client._disconnected", errorCode, errorText);
1368
+
1369
+ this.sendPinger.cancel();
1370
+ this.receivePinger.cancel();
1371
+ if (this._connectTimeout)
1372
+ this._connectTimeout.cancel();
1373
+ // Clear message buffers.
1374
+ this._msg_queue = [];
1375
+ this._notify_msg_sent = {};
1376
+
1377
+ if (this.socket) {
1378
+ // Cancel all socket callbacks so that they cannot be driven again by this socket.
1379
+ this.socket.onopen = null;
1380
+ this.socket.onmessage = null;
1381
+ this.socket.onerror = null;
1382
+ this.socket.onclose = null;
1383
+ if (this.socket.readyState === 1)
1384
+ this.socket.close();
1385
+ delete this.socket;
1386
+ }
1387
+
1388
+ if (this.connectOptions.uris && this.hostIndex < this.connectOptions.uris.length-1) {
1389
+ // Try the next host.
1390
+ this.hostIndex++;
1391
+ this._doConnect(this.connectOptions.uris[this.hostIndex]);
1392
+
1393
+ } else {
1394
+
1395
+ if (errorCode === undefined) {
1396
+ errorCode = ERROR.OK.code;
1397
+ errorText = format(ERROR.OK);
1398
+ }
1399
+
1400
+ // Run any application callbacks last as they may attempt to reconnect and hence create a new socket.
1401
+ if (this.connected) {
1402
+ this.connected = false;
1403
+ // Execute the connectionLostCallback if there is one, and we were connected.
1404
+ if (this.onConnectionLost)
1405
+ this.onConnectionLost({errorCode:errorCode, errorMessage:errorText});
1406
+ } else {
1407
+ // Otherwise we never had a connection, so indicate that the connect has failed.
1408
+ if(this.connectOptions.onFailure)
1409
+ this.connectOptions.onFailure({invocationContext:this.connectOptions.invocationContext, errorCode:errorCode, errorMessage:errorText});
1410
+ }
1411
+ }
1412
+ };
1413
+
1414
+ /** @ignore */
1415
+ ClientImpl.prototype._trace = function () {
1416
+ if ( this._traceBuffer !== null ) {
1417
+ for (var i = 0, max = arguments.length; i < max; i++) {
1418
+ if ( this._traceBuffer.length == this._MAX_TRACE_ENTRIES ) {
1419
+ this._traceBuffer.shift();
1420
+ }
1421
+ if (i === 0) this._traceBuffer.push(arguments[i]);
1422
+ else if (typeof arguments[i] === "undefined" ) this._traceBuffer.push(arguments[i]);
1423
+ else this._traceBuffer.push(" "+JSON.stringify(arguments[i]));
1424
+ };
1425
+ };
1426
+ };
1427
+
1428
+ /** @ignore */
1429
+ ClientImpl.prototype._traceMask = function (traceObject, masked) {
1430
+ var traceObjectMasked = {};
1431
+ for (var attr in traceObject) {
1432
+ if (traceObject.hasOwnProperty(attr)) {
1433
+ if (attr == masked)
1434
+ traceObjectMasked[attr] = "******";
1435
+ else
1436
+ traceObjectMasked[attr] = traceObject[attr];
1437
+ }
1438
+ }
1439
+ return traceObjectMasked;
1440
+ };
1441
+
1442
+ // ------------------------------------------------------------------------
1443
+ // Public Programming interface.
1444
+ // ------------------------------------------------------------------------
1445
+
1446
+ /**
1447
+ * The JavaScript application communicates to the server using a {@link Messaging.Client} object.
1448
+ * <p>
1449
+ * Most applications will create just one Client object and then call its connect() method,
1450
+ * however applications can create more than one Client object if they wish.
1451
+ * In this case the combination of host, port and clientId attributes must be different for each Client object.
1452
+ * <p>
1453
+ * The send, subscribe and unsubscribe methods are implemented as asynchronous JavaScript methods
1454
+ * (even though the underlying protocol exchange might be synchronous in nature).
1455
+ * This means they signal their completion by calling back to the application,
1456
+ * via Success or Failure callback functions provided by the application on the method in question.
1457
+ * Such callbacks are called at most once per method invocation and do not persist beyond the lifetime
1458
+ * of the script that made the invocation.
1459
+ * <p>
1460
+ * In contrast there are some callback functions, most notably <i>onMessageArrived</i>,
1461
+ * that are defined on the {@link Messaging.Client} object.
1462
+ * These may get called multiple times, and aren't directly related to specific method invocations made by the client.
1463
+ *
1464
+ * @name Messaging.Client
1465
+ *
1466
+ * @constructor
1467
+ *
1468
+ * @param {string} host - the address of the messaging server, as a fully qualified WebSocket URI, as a DNS name or dotted decimal IP address.
1469
+ * @param {number} port - the port number to connect to - only required if host is not a URI
1470
+ * @param {string} path - the path on the host to connect to - only used if host is not a URI. Default: '/mqtt'.
1471
+ * @param {string} clientId - the Messaging client identifier, between 1 and 23 characters in length.
1472
+ *
1473
+ * @property {string} host - <i>read only</i> the server's DNS hostname or dotted decimal IP address.
1474
+ * @property {number} port - <i>read only</i> the server's port.
1475
+ * @property {string} path - <i>read only</i> the server's path.
1476
+ * @property {string} clientId - <i>read only</i> used when connecting to the server.
1477
+ * @property {function} onConnectionLost - called when a connection has been lost.
1478
+ * after a connect() method has succeeded.
1479
+ * Establish the call back used when a connection has been lost. The connection may be
1480
+ * lost because the client initiates a disconnect or because the server or network
1481
+ * cause the client to be disconnected. The disconnect call back may be called without
1482
+ * the connectionComplete call back being invoked if, for example the client fails to
1483
+ * connect.
1484
+ * A single response object parameter is passed to the onConnectionLost callback containing the following fields:
1485
+ * <ol>
1486
+ * <li>errorCode
1487
+ * <li>errorMessage
1488
+ * </ol>
1489
+ * @property {function} onMessageDelivered called when a message has been delivered.
1490
+ * All processing that this Client will ever do has been completed. So, for example,
1491
+ * in the case of a Qos=2 message sent by this client, the PubComp flow has been received from the server
1492
+ * and the message has been removed from persistent storage before this callback is invoked.
1493
+ * Parameters passed to the onMessageDelivered callback are:
1494
+ * <ol>
1495
+ * <li>{@link Messaging.Message} that was delivered.
1496
+ * </ol>
1497
+ * @property {function} onMessageArrived called when a message has arrived in this Messaging.client.
1498
+ * Parameters passed to the onMessageArrived callback are:
1499
+ * <ol>
1500
+ * <li>{@link Messaging.Message} that has arrived.
1501
+ * </ol>
1502
+ */
1503
+ var Client = function (host, port, path, clientId) {
1504
+
1505
+ var uri;
1506
+
1507
+ if (typeof host !== "string")
1508
+ throw new Error(format(ERROR.INVALID_TYPE, [typeof host, "host"]));
1509
+
1510
+ if (arguments.length == 2) {
1511
+ // host: must be full ws:// uri
1512
+ // port: clientId
1513
+ clientId = port;
1514
+ uri = host;
1515
+ var match = uri.match(/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/);
1516
+ if (match) {
1517
+ host = match[4]||match[2];
1518
+ port = parseInt(match[7]);
1519
+ path = match[8];
1520
+ } else {
1521
+ throw new Error(format(ERROR.INVALID_ARGUMENT,[host,"host"]));
1522
+ }
1523
+ } else {
1524
+ if (arguments.length == 3) {
1525
+ clientId = path;
1526
+ path = "/mqtt";
1527
+ }
1528
+ if (typeof port !== "number" || port < 0)
1529
+ throw new Error(format(ERROR.INVALID_TYPE, [typeof port, "port"]));
1530
+ if (typeof path !== "string")
1531
+ throw new Error(format(ERROR.INVALID_TYPE, [typeof path, "path"]));
1532
+
1533
+ var ipv6 = (host.indexOf(":") != -1);
1534
+ uri = "ws://"+(ipv6?"["+host+"]":host)+":"+port+path;
1535
+ }
1536
+
1537
+ var clientIdLength = 0;
1538
+ for (var i = 0; i<clientId.length; i++) {
1539
+ var charCode = clientId.charCodeAt(i);
1540
+ if (0xD800 <= charCode && charCode <= 0xDBFF) {
1541
+ i++; // Surrogate pair.
1542
+ }
1543
+ clientIdLength++;
1544
+ }
1545
+ if (typeof clientId !== "string" || clientIdLength < 1 | clientIdLength > 23)
1546
+ throw new Error(format(ERROR.INVALID_ARGUMENT, [clientId, "clientId"]));
1547
+
1548
+ var client = new ClientImpl(uri, host, port, path, clientId);
1549
+ this._getHost = function() { return host; };
1550
+ this._setHost = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); };
1551
+
1552
+ this._getPort = function() { return port; };
1553
+ this._setPort = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); };
1554
+
1555
+ this._getPath = function() { return path; };
1556
+ this._setPath = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); };
1557
+
1558
+ this._getURI = function() { return uri; };
1559
+ this._setURI = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); };
1560
+
1561
+ this._getClientId = function() { return client.clientId; };
1562
+ this._setClientId = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); };
1563
+
1564
+ this._getOnConnectionLost = function() { return client.onConnectionLost; };
1565
+ this._setOnConnectionLost = function(newOnConnectionLost) {
1566
+ if (typeof newOnConnectionLost === "function")
1567
+ client.onConnectionLost = newOnConnectionLost;
1568
+ else
1569
+ throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnConnectionLost, "onConnectionLost"]));
1570
+ };
1571
+
1572
+ this._getOnMessageDelivered = function() { return client.onMessageDelivered; };
1573
+ this._setOnMessageDelivered = function(newOnMessageDelivered) {
1574
+ if (typeof newOnMessageDelivered === "function")
1575
+ client.onMessageDelivered = newOnMessageDelivered;
1576
+ else
1577
+ throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnMessageDelivered, "onMessageDelivered"]));
1578
+ };
1579
+
1580
+ this._getOnMessageArrived = function() { return client.onMessageArrived; };
1581
+ this._setOnMessageArrived = function(newOnMessageArrived) {
1582
+ if (typeof newOnMessageArrived === "function")
1583
+ client.onMessageArrived = newOnMessageArrived;
1584
+ else
1585
+ throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnMessageArrived, "onMessageArrived"]));
1586
+ };
1587
+
1588
+ /**
1589
+ * Connect this Messaging client to its server.
1590
+ *
1591
+ * @name Messaging.Client#connect
1592
+ * @function
1593
+ * @param {Object} connectOptions - attributes used with the connection.
1594
+ * @param {number} connectOptions.timeout - If the connect has not succeeded within this
1595
+ * number of seconds, it is deemed to have failed.
1596
+ * The default is 30 seconds.
1597
+ * @param {string} connectOptions.userName - Authentication username for this connection.
1598
+ * @param {string} connectOptions.password - Authentication password for this connection.
1599
+ * @param {Messaging.Message} connectOptions.willMessage - sent by the server when the client
1600
+ * disconnects abnormally.
1601
+ * @param {Number} connectOptions.keepAliveInterval - the server disconnects this client if
1602
+ * there is no activity for this number of seconds.
1603
+ * The default value of 60 seconds is assumed if not set.
1604
+ * @param {boolean} connectOptions.cleanSession - if true(default) the client and server
1605
+ * persistent state is deleted on successful connect.
1606
+ * @param {boolean} connectOptions.useSSL - if present and true, use an SSL Websocket connection.
1607
+ * @param {object} connectOptions.invocationContext - passed to the onSuccess callback or onFailure callback.
1608
+ * @param {function} connectOptions.onSuccess - called when the connect acknowledgement
1609
+ * has been received from the server.
1610
+ * A single response object parameter is passed to the onSuccess callback containing the following fields:
1611
+ * <ol>
1612
+ * <li>invocationContext as passed in to the onSuccess method in the connectOptions.
1613
+ * </ol>
1614
+ * @config {function} [onFailure] called when the connect request has failed or timed out.
1615
+ * A single response object parameter is passed to the onFailure callback containing the following fields:
1616
+ * <ol>
1617
+ * <li>invocationContext as passed in to the onFailure method in the connectOptions.
1618
+ * <li>errorCode a number indicating the nature of the error.
1619
+ * <li>errorMessage text describing the error.
1620
+ * </ol>
1621
+ * @config {Array} [hosts] If present this contains either a set of hostnames or fully qualified
1622
+ * WebSocket URIs (ws://example.com:1883/mqtt), that are tried in order in place
1623
+ * of the host and port paramater on the construtor. The hosts are tried one at at time in order until
1624
+ * one of then succeeds.
1625
+ * @config {Array} [ports] If present the set of ports matching the hosts. If hosts contains URIs, this property
1626
+ * is not used.
1627
+ * @throws {InvalidState} if the client is not in disconnected state. The client must have received connectionLost
1628
+ * or disconnected before calling connect for a second or subsequent time.
1629
+ */
1630
+ this.connect = function (connectOptions) {
1631
+ connectOptions = connectOptions || {} ;
1632
+ validate(connectOptions, {timeout:"number",
1633
+ userName:"string",
1634
+ password:"string",
1635
+ willMessage:"object",
1636
+ keepAliveInterval:"number",
1637
+ cleanSession:"boolean",
1638
+ useSSL:"boolean",
1639
+ invocationContext:"object",
1640
+ onSuccess:"function",
1641
+ onFailure:"function",
1642
+ hosts:"object",
1643
+ ports:"object"});
1644
+
1645
+ // If no keep alive interval is set, assume 60 seconds.
1646
+ if (connectOptions.keepAliveInterval === undefined)
1647
+ connectOptions.keepAliveInterval = 60;
1648
+
1649
+ if (connectOptions.willMessage) {
1650
+ if (!(connectOptions.willMessage instanceof Message))
1651
+ throw new Error(format(ERROR.INVALID_TYPE, [connectOptions.willMessage, "connectOptions.willMessage"]));
1652
+ // The will message must have a payload that can be represented as a string.
1653
+ // Cause the willMessage to throw an exception if this is not the case.
1654
+ connectOptions.willMessage.stringPayload;
1655
+
1656
+ if (typeof connectOptions.willMessage.destinationName === "undefined")
1657
+ throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.willMessage.destinationName, "connectOptions.willMessage.destinationName"]));
1658
+ }
1659
+ if (typeof connectOptions.cleanSession === "undefined")
1660
+ connectOptions.cleanSession = true;
1661
+ if (connectOptions.hosts) {
1662
+
1663
+ if (!(connectOptions.hosts instanceof Array) )
1664
+ throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts, "connectOptions.hosts"]));
1665
+ if (connectOptions.hosts.length <1 )
1666
+ throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts, "connectOptions.hosts"]));
1667
+
1668
+ var usingURIs = false;
1669
+ for (var i = 0; i<connectOptions.hosts.length; i++) {
1670
+ if (typeof connectOptions.hosts[i] !== "string")
1671
+ throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.hosts[i], "connectOptions.hosts["+i+"]"]));
1672
+ if (/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/.test(connectOptions.hosts[i])) {
1673
+ if (i == 0) {
1674
+ usingURIs = true;
1675
+ } else if (!usingURIs) {
1676
+ throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts[i], "connectOptions.hosts["+i+"]"]));
1677
+ }
1678
+ } else if (usingURIs) {
1679
+ throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts[i], "connectOptions.hosts["+i+"]"]));
1680
+ }
1681
+ }
1682
+
1683
+ if (!usingURIs) {
1684
+ if (!connectOptions.ports)
1685
+ throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"]));
1686
+ if (!(connectOptions.ports instanceof Array) )
1687
+ throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"]));
1688
+ if (connectOptions.hosts.length != connectOptions.ports.length)
1689
+ throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"]));
1690
+
1691
+ connectOptions.uris = [];
1692
+
1693
+ for (var i = 0; i<connectOptions.hosts.length; i++) {
1694
+ if (typeof connectOptions.ports[i] !== "number" || connectOptions.ports[i] < 0)
1695
+ throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.ports[i], "connectOptions.ports["+i+"]"]));
1696
+ var host = connectOptions.hosts[i];
1697
+ var port = connectOptions.ports[i];
1698
+
1699
+ var ipv6 = (host.indexOf(":") != -1);
1700
+ uri = "ws://"+(ipv6?"["+host+"]":host)+":"+port+path;
1701
+ connectOptions.uris.push(uri);
1702
+ }
1703
+ } else {
1704
+ connectOptions.uris = connectOptions.hosts;
1705
+ }
1706
+ }
1707
+
1708
+ client.connect(connectOptions);
1709
+ };
1710
+
1711
+ /**
1712
+ * Subscribe for messages, request receipt of a copy of messages sent to the destinations described by the filter.
1713
+ *
1714
+ * @name Messaging.Client#subscribe
1715
+ * @function
1716
+ * @param {string} filter describing the destinations to receive messages from.
1717
+ * <br>
1718
+ * @param {object} subscribeOptions - used to control the subscription
1719
+ *
1720
+ * @param {number} subscribeOptions.qos - the maiximum qos of any publications sent
1721
+ * as a result of making this subscription.
1722
+ * @param {object} subscribeOptions.invocationContext - passed to the onSuccess callback
1723
+ * or onFailure callback.
1724
+ * @param {function} subscribeOptions.onSuccess - called when the subscribe acknowledgement
1725
+ * has been received from the server.
1726
+ * A single response object parameter is passed to the onSuccess callback containing the following fields:
1727
+ * <ol>
1728
+ * <li>invocationContext if set in the subscribeOptions.
1729
+ * </ol>
1730
+ * @param {function} subscribeOptions.onFailure - called when the subscribe request has failed or timed out.
1731
+ * A single response object parameter is passed to the onFailure callback containing the following fields:
1732
+ * <ol>
1733
+ * <li>invocationContext - if set in the subscribeOptions.
1734
+ * <li>errorCode - a number indicating the nature of the error.
1735
+ * <li>errorMessage - text describing the error.
1736
+ * </ol>
1737
+ * @param {number} subscribeOptions.timeout - which, if present, determines the number of
1738
+ * seconds after which the onFailure calback is called.
1739
+ * The presence of a timeout does not prevent the onSuccess
1740
+ * callback from being called when the subscribe completes.
1741
+ * @throws {InvalidState} if the client is not in connected state.
1742
+ */
1743
+ this.subscribe = function (filter, subscribeOptions) {
1744
+ if (typeof filter !== "string")
1745
+ throw new Error("Invalid argument:"+filter);
1746
+ subscribeOptions = subscribeOptions || {} ;
1747
+ validate(subscribeOptions, {qos:"number",
1748
+ invocationContext:"object",
1749
+ onSuccess:"function",
1750
+ onFailure:"function",
1751
+ timeout:"number"
1752
+ });
1753
+ if (subscribeOptions.timeout && !subscribeOptions.onFailure)
1754
+ throw new Error("subscribeOptions.timeout specified with no onFailure callback.");
1755
+ if (typeof subscribeOptions.qos !== "undefined"
1756
+ && !(subscribeOptions.qos === 0 || subscribeOptions.qos === 1 || subscribeOptions.qos === 2 ))
1757
+ throw new Error(format(ERROR.INVALID_ARGUMENT, [subscribeOptions.qos, "subscribeOptions.qos"]));
1758
+ client.subscribe(filter, subscribeOptions);
1759
+ };
1760
+
1761
+ /**
1762
+ * Unsubscribe for messages, stop receiving messages sent to destinations described by the filter.
1763
+ *
1764
+ * @name Messaging.Client#unsubscribe
1765
+ * @function
1766
+ * @param {string} filter - describing the destinations to receive messages from.
1767
+ * @param {object} unsubscribeOptions - used to control the subscription
1768
+ * @param {object} unsubscribeOptions.invocationContext - passed to the onSuccess callback
1769
+ or onFailure callback.
1770
+ * @param {function} unsubscribeOptions.onSuccess - called when the unsubscribe acknowledgement has been received from the server.
1771
+ * A single response object parameter is passed to the
1772
+ * onSuccess callback containing the following fields:
1773
+ * <ol>
1774
+ * <li>invocationContext - if set in the unsubscribeOptions.
1775
+ * </ol>
1776
+ * @param {function} unsubscribeOptions.onFailure called when the unsubscribe request has failed or timed out.
1777
+ * A single response object parameter is passed to the onFailure callback containing the following fields:
1778
+ * <ol>
1779
+ * <li>invocationContext - if set in the unsubscribeOptions.
1780
+ * <li>errorCode - a number indicating the nature of the error.
1781
+ * <li>errorMessage - text describing the error.
1782
+ * </ol>
1783
+ * @param {number} unsubscribeOptions.timeout - which, if present, determines the number of seconds
1784
+ * after which the onFailure callback is called. The presence of
1785
+ * a timeout does not prevent the onSuccess callback from being
1786
+ * called when the unsubscribe completes
1787
+ * @throws {InvalidState} if the client is not in connected state.
1788
+ */
1789
+ this.unsubscribe = function (filter, unsubscribeOptions) {
1790
+ if (typeof filter !== "string")
1791
+ throw new Error("Invalid argument:"+filter);
1792
+ unsubscribeOptions = unsubscribeOptions || {} ;
1793
+ validate(unsubscribeOptions, {invocationContext:"object",
1794
+ onSuccess:"function",
1795
+ onFailure:"function",
1796
+ timeout:"number"
1797
+ });
1798
+ if (unsubscribeOptions.timeout && !unsubscribeOptions.onFailure)
1799
+ throw new Error("unsubscribeOptions.timeout specified with no onFailure callback.");
1800
+ client.unsubscribe(filter, unsubscribeOptions);
1801
+ };
1802
+
1803
+ /**
1804
+ * Send a message to the consumers of the destination in the Message.
1805
+ *
1806
+ * @name Messaging.Client#send
1807
+ * @function
1808
+ * @param {Messaging.Message} message to send.
1809
+
1810
+ * @throws {InvalidState} if the client is not connected.
1811
+ */
1812
+ this.send = function (message) {
1813
+ if (!(message instanceof Message))
1814
+ throw new Error("Invalid argument:"+typeof message);
1815
+ if (typeof message.destinationName === "undefined")
1816
+ throw new Error("Invalid parameter Message.destinationName:"+message.destinationName);
1817
+
1818
+ client.send(message);
1819
+ };
1820
+
1821
+ /**
1822
+ * Normal disconnect of this Messaging client from its server.
1823
+ *
1824
+ * @name Messaging.Client#disconnect
1825
+ * @function
1826
+ * @throws {InvalidState} if the client is already disconnected.
1827
+ */
1828
+ this.disconnect = function () {
1829
+ client.disconnect();
1830
+ };
1831
+
1832
+ /**
1833
+ * Get the contents of the trace log.
1834
+ *
1835
+ * @name Messaging.Client#getTraceLog
1836
+ * @function
1837
+ * @return {Object[]} tracebuffer containing the time ordered trace records.
1838
+ */
1839
+ this.getTraceLog = function () {
1840
+ return client.getTraceLog();
1841
+ }
1842
+
1843
+ /**
1844
+ * Start tracing.
1845
+ *
1846
+ * @name Messaging.Client#startTrace
1847
+ * @function
1848
+ */
1849
+ this.startTrace = function () {
1850
+ client.startTrace();
1851
+ };
1852
+
1853
+ /**
1854
+ * Stop tracing.
1855
+ *
1856
+ * @name Messaging.Client#stopTrace
1857
+ * @function
1858
+ */
1859
+ this.stopTrace = function () {
1860
+ client.stopTrace();
1861
+ };
1862
+ };
1863
+
1864
+ Client.prototype = {
1865
+ get host() { return this._getHost(); },
1866
+ set host(newHost) { this._setHost(newHost); },
1867
+
1868
+ get port() { return this._getPort(); },
1869
+ set port(newPort) { this._setPort(newPort); },
1870
+
1871
+ get path() { return this._getPath(); },
1872
+ set path(newPath) { this._setPath(newPath); },
1873
+
1874
+ get clientId() { return this._getClientId(); },
1875
+ set clientId(newClientId) { this._setClientId(newClientId); },
1876
+
1877
+ get onConnectionLost() { return this._getOnConnectionLost(); },
1878
+ set onConnectionLost(newOnConnectionLost) { this._setOnConnectionLost(newOnConnectionLost); },
1879
+
1880
+ get onMessageDelivered() { return this._getOnMessageDelivered(); },
1881
+ set onMessageDelivered(newOnMessageDelivered) { this._setOnMessageDelivered(newOnMessageDelivered); },
1882
+
1883
+ get onMessageArrived() { return this._getOnMessageArrived(); },
1884
+ set onMessageArrived(newOnMessageArrived) { this._setOnMessageArrived(newOnMessageArrived); }
1885
+ };
1886
+
1887
+ /**
1888
+ * An application message, sent or received.
1889
+ * <p>
1890
+ * All attributes may be null, which implies the default values.
1891
+ *
1892
+ * @name Messaging.Message
1893
+ * @constructor
1894
+ * @param {String|ArrayBuffer} payload The message data to be sent.
1895
+ * <p>
1896
+ * @property {string} payloadString <i>read only</i> The payload as a string if the payload consists of valid UTF-8 characters.
1897
+ * @property {ArrayBuffer} payloadBytes <i>read only</i> The payload as an ArrayBuffer.
1898
+ * <p>
1899
+ * @property {string} destinationName <b>mandatory</b> The name of the destination to which the message is to be sent
1900
+ * (for messages about to be sent) or the name of the destination from which the message has been received.
1901
+ * (for messages received by the onMessage function).
1902
+ * <p>
1903
+ * @property {number} qos The Quality of Service used to deliver the message.
1904
+ * <dl>
1905
+ * <dt>0 Best effort (default).
1906
+ * <dt>1 At least once.
1907
+ * <dt>2 Exactly once.
1908
+ * </dl>
1909
+ * <p>
1910
+ * @property {Boolean} retained If true, the message is to be retained by the server and delivered
1911
+ * to both current and future subscriptions.
1912
+ * If false the server only delivers the message to current subscribers, this is the default for new Messages.
1913
+ * A received message has the retained boolean set to true if the message was published
1914
+ * with the retained boolean set to true
1915
+ * and the subscrption was made after the message has been published.
1916
+ * <p>
1917
+ * @property {Boolean} duplicate <i>read only</i> If true, this message might be a duplicate of one which has already been received.
1918
+ * This is only set on messages received from the server.
1919
+ *
1920
+ */
1921
+ var Message = function (newPayload) {
1922
+ var payload;
1923
+ if ( typeof newPayload === "string"
1924
+ || newPayload instanceof ArrayBuffer
1925
+ || newPayload instanceof Int8Array
1926
+ || newPayload instanceof Uint8Array
1927
+ || newPayload instanceof Int16Array
1928
+ || newPayload instanceof Uint16Array
1929
+ || newPayload instanceof Int32Array
1930
+ || newPayload instanceof Uint32Array
1931
+ || newPayload instanceof Float32Array
1932
+ || newPayload instanceof Float64Array
1933
+ ) {
1934
+ payload = newPayload;
1935
+ } else {
1936
+ throw (format(ERROR.INVALID_ARGUMENT, [newPayload, "newPayload"]));
1937
+ }
1938
+
1939
+ this._getPayloadString = function () {
1940
+ if (typeof payload === "string")
1941
+ return payload;
1942
+ else
1943
+ return parseUTF8(payload, 0, payload.length);
1944
+ };
1945
+
1946
+ this._getPayloadBytes = function() {
1947
+ if (typeof payload === "string") {
1948
+ var buffer = new ArrayBuffer(UTF8Length(payload));
1949
+ var byteStream = new Uint8Array(buffer);
1950
+ stringToUTF8(payload, byteStream, 0);
1951
+
1952
+ return byteStream;
1953
+ } else {
1954
+ return payload;
1955
+ };
1956
+ };
1957
+
1958
+ var destinationName = undefined;
1959
+ this._getDestinationName = function() { return destinationName; };
1960
+ this._setDestinationName = function(newDestinationName) {
1961
+ if (typeof newDestinationName === "string")
1962
+ destinationName = newDestinationName;
1963
+ else
1964
+ throw new Error(format(ERROR.INVALID_ARGUMENT, [newDestinationName, "newDestinationName"]));
1965
+ };
1966
+
1967
+ var qos = 0;
1968
+ this._getQos = function() { return qos; };
1969
+ this._setQos = function(newQos) {
1970
+ if (newQos === 0 || newQos === 1 || newQos === 2 )
1971
+ qos = newQos;
1972
+ else
1973
+ throw new Error("Invalid argument:"+newQos);
1974
+ };
1975
+
1976
+ var retained = false;
1977
+ this._getRetained = function() { return retained; };
1978
+ this._setRetained = function(newRetained) {
1979
+ if (typeof newRetained === "boolean")
1980
+ retained = newRetained;
1981
+ else
1982
+ throw new Error(format(ERROR.INVALID_ARGUMENT, [newRetained, "newRetained"]));
1983
+ };
1984
+
1985
+ var duplicate = false;
1986
+ this._getDuplicate = function() { return duplicate; };
1987
+ this._setDuplicate = function(newDuplicate) { duplicate = newDuplicate; };
1988
+ };
1989
+
1990
+ Message.prototype = {
1991
+ get payloadString() { return this._getPayloadString(); },
1992
+ get payloadBytes() { return this._getPayloadBytes(); },
1993
+
1994
+ get destinationName() { return this._getDestinationName(); },
1995
+ set destinationName(newDestinationName) { this._setDestinationName(newDestinationName); },
1996
+
1997
+ get qos() { return this._getQos(); },
1998
+ set qos(newQos) { this._setQos(newQos); },
1999
+
2000
+ get retained() { return this._getRetained(); },
2001
+ set retained(newRetained) { this._setRetained(newRetained); },
2002
+
2003
+ get duplicate() { return this._getDuplicate(); },
2004
+ set duplicate(newDuplicate) { this._setDuplicate(newDuplicate); }
2005
+ };
2006
+
2007
+ // Module contents.
2008
+ return {
2009
+ Client: Client,
2010
+ Message: Message
2011
+ };
2012
+ })(window);