* The API consists of two main objects: *
-client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId");
+var client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId");
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
client.connect({onSuccess:onConnect});
@@ -64,7 +64,7 @@ function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe("/World");
- message = new Paho.MQTT.Message("Hello");
+ var message = new Paho.MQTT.Message("Hello");
message.destinationName = "/World";
client.send(message);
};
@@ -77,60 +77,71 @@ function onMessageArrived(message) {
client.disconnect();
};
*
- * @namespace Paho.MQTT
+ * @namespace Paho
*/
/* jshint shadow:true */
(function ExportLibrary(root, factory) {
- if(typeof exports === 'object' && typeof module === 'object'){
+ if(typeof exports === "object" && typeof module === "object"){
module.exports = factory();
- } else if (typeof define === 'function' && define.amd){
+ } else if (typeof define === "function" && define.amd){
define(factory);
- } else if (typeof exports === 'object'){
+ } else if (typeof exports === "object"){
exports = factory();
} else {
- if (typeof root.Paho === 'undefined'){
- root.Paho = {};
- }
- root.Paho.MQTT = factory();
+ //if (typeof root.Paho === "undefined"){
+ // root.Paho = {};
+ //}
+ root.Paho = factory();
}
})(this, function LibraryFactory(){
-var PahoMQTT = (function (global) {
+ var PahoMQTT = (function (global) {
// Private variables below, these are only visible inside the function closure
// which is used to define the module.
-
- var version = "@VERSION@";
- var buildLevel = "@BUILDLEVEL@";
+ var version = "@VERSION@-@BUILDLEVEL@";
/**
+ * @private
+ */
+ var localStorage = global.localStorage || (function () {
+ var data = {};
+
+ return {
+ setItem: function (key, item) { data[key] = item; },
+ getItem: function (key) { return data[key]; },
+ removeItem: function (key) { delete data[key]; },
+ };
+ })();
+
+ /**
* Unique message type identifiers, with associated
* associated integer values.
* @private
*/
- var MESSAGE_TYPE = {
- CONNECT: 1,
- CONNACK: 2,
- PUBLISH: 3,
- PUBACK: 4,
- PUBREC: 5,
- PUBREL: 6,
- PUBCOMP: 7,
- SUBSCRIBE: 8,
- SUBACK: 9,
- UNSUBSCRIBE: 10,
- UNSUBACK: 11,
- PINGREQ: 12,
- PINGRESP: 13,
- DISCONNECT: 14
- };
-
- // Collection of utility methods used to simplify module code
- // and promote the DRY pattern.
+ var MESSAGE_TYPE = {
+ CONNECT: 1,
+ CONNACK: 2,
+ PUBLISH: 3,
+ PUBACK: 4,
+ PUBREC: 5,
+ PUBREL: 6,
+ PUBCOMP: 7,
+ SUBSCRIBE: 8,
+ SUBACK: 9,
+ UNSUBSCRIBE: 10,
+ UNSUBACK: 11,
+ PINGREQ: 12,
+ PINGRESP: 13,
+ DISCONNECT: 14
+ };
- /**
+ // Collection of utility methods used to simplify module code
+ // and promote the DRY pattern.
+
+ /**
* Validate an object's parameter names to ensure they
* match a list of expected variables name for this option
* type. Used to ensure option object passed into the API don't
@@ -140,24 +151,24 @@ var PahoMQTT = (function (global) {
* @throws {Error} Invalid option parameter found.
* @private
*/
- var validate = function(obj, keys) {
- for (var key in obj) {
- if (obj.hasOwnProperty(key)) {
- if (keys.hasOwnProperty(key)) {
- if (typeof obj[key] !== keys[key])
- throw new Error(format(ERROR.INVALID_TYPE, [typeof obj[key], key]));
- } else {
- var errorStr = "Unknown property, " + key + ". Valid properties are:";
- for (var validKey in keys)
- if (keys.hasOwnProperty(validKey))
- errorStr = errorStr+" "+validKey;
- throw new Error(errorStr);
+ var validate = function(obj, keys) {
+ for (var key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ if (keys.hasOwnProperty(key)) {
+ if (typeof obj[key] !== keys[key])
+ throw new Error(format(ERROR.INVALID_TYPE, [typeof obj[key], key]));
+ } else {
+ var errorStr = "Unknown property, " + key + ". Valid properties are:";
+ for (var validKey in keys)
+ if (keys.hasOwnProperty(validKey))
+ errorStr = errorStr+" "+validKey;
+ throw new Error(errorStr);
+ }
}
}
- }
- };
+ };
- /**
+ /**
* Return a new function which runs the user function bound
* to a fixed scope.
* @param {function} User function
@@ -165,79 +176,79 @@ var PahoMQTT = (function (global) {
* @return {function} User function bound to another scope
* @private
*/
- var scope = function (f, scope) {
- return function () {
- return f.apply(scope, arguments);
+ var scope = function (f, scope) {
+ return function () {
+ return f.apply(scope, arguments);
+ };
};
- };
- /**
+ /**
* Unique message type identifiers, with associated
* associated integer values.
* @private
*/
- var ERROR = {
- OK: {code:0, text:"AMQJSC0000I OK."},
- CONNECT_TIMEOUT: {code:1, text:"AMQJSC0001E Connect timed out."},
- SUBSCRIBE_TIMEOUT: {code:2, text:"AMQJS0002E Subscribe timed out."},
- UNSUBSCRIBE_TIMEOUT: {code:3, text:"AMQJS0003E Unsubscribe timed out."},
- PING_TIMEOUT: {code:4, text:"AMQJS0004E Ping timed out."},
- INTERNAL_ERROR: {code:5, text:"AMQJS0005E Internal error. Error Message: {0}, Stack trace: {1}"},
- CONNACK_RETURNCODE: {code:6, text:"AMQJS0006E Bad Connack return code:{0} {1}."},
- SOCKET_ERROR: {code:7, text:"AMQJS0007E Socket error:{0}."},
- SOCKET_CLOSE: {code:8, text:"AMQJS0008I Socket closed."},
- MALFORMED_UTF: {code:9, text:"AMQJS0009E Malformed UTF data:{0} {1} {2}."},
- UNSUPPORTED: {code:10, text:"AMQJS0010E {0} is not supported by this browser."},
- INVALID_STATE: {code:11, text:"AMQJS0011E Invalid state {0}."},
- INVALID_TYPE: {code:12, text:"AMQJS0012E Invalid type {0} for {1}."},
- INVALID_ARGUMENT: {code:13, text:"AMQJS0013E Invalid argument {0} for {1}."},
- UNSUPPORTED_OPERATION: {code:14, text:"AMQJS0014E Unsupported operation."},
- INVALID_STORED_DATA: {code:15, text:"AMQJS0015E Invalid data in local storage key={0} value={1}."},
- INVALID_MQTT_MESSAGE_TYPE: {code:16, text:"AMQJS0016E Invalid MQTT message type {0}."},
- MALFORMED_UNICODE: {code:17, text:"AMQJS0017E Malformed Unicode string:{0} {1}."},
- BUFFER_FULL: {code:18, text:"AMQJS0018E Message buffer is full, maximum buffer size: {0}."},
- };
-
- /** CONNACK RC Meaning. */
- var CONNACK_RC = {
- 0:"Connection Accepted",
- 1:"Connection Refused: unacceptable protocol version",
- 2:"Connection Refused: identifier rejected",
- 3:"Connection Refused: server unavailable",
- 4:"Connection Refused: bad user name or password",
- 5:"Connection Refused: not authorized"
- };
+ var ERROR = {
+ OK: {code:0, text:"AMQJSC0000I OK."},
+ CONNECT_TIMEOUT: {code:1, text:"AMQJSC0001E Connect timed out."},
+ SUBSCRIBE_TIMEOUT: {code:2, text:"AMQJS0002E Subscribe timed out."},
+ UNSUBSCRIBE_TIMEOUT: {code:3, text:"AMQJS0003E Unsubscribe timed out."},
+ PING_TIMEOUT: {code:4, text:"AMQJS0004E Ping timed out."},
+ INTERNAL_ERROR: {code:5, text:"AMQJS0005E Internal error. Error Message: {0}, Stack trace: {1}"},
+ CONNACK_RETURNCODE: {code:6, text:"AMQJS0006E Bad Connack return code:{0} {1}."},
+ SOCKET_ERROR: {code:7, text:"AMQJS0007E Socket error:{0}."},
+ SOCKET_CLOSE: {code:8, text:"AMQJS0008I Socket closed."},
+ MALFORMED_UTF: {code:9, text:"AMQJS0009E Malformed UTF data:{0} {1} {2}."},
+ UNSUPPORTED: {code:10, text:"AMQJS0010E {0} is not supported by this browser."},
+ INVALID_STATE: {code:11, text:"AMQJS0011E Invalid state {0}."},
+ INVALID_TYPE: {code:12, text:"AMQJS0012E Invalid type {0} for {1}."},
+ INVALID_ARGUMENT: {code:13, text:"AMQJS0013E Invalid argument {0} for {1}."},
+ UNSUPPORTED_OPERATION: {code:14, text:"AMQJS0014E Unsupported operation."},
+ INVALID_STORED_DATA: {code:15, text:"AMQJS0015E Invalid data in local storage key={0} value={1}."},
+ INVALID_MQTT_MESSAGE_TYPE: {code:16, text:"AMQJS0016E Invalid MQTT message type {0}."},
+ MALFORMED_UNICODE: {code:17, text:"AMQJS0017E Malformed Unicode string:{0} {1}."},
+ BUFFER_FULL: {code:18, text:"AMQJS0018E Message buffer is full, maximum buffer size: {0}."},
+ };
+
+ /** CONNACK RC Meaning. */
+ var CONNACK_RC = {
+ 0:"Connection Accepted",
+ 1:"Connection Refused: unacceptable protocol version",
+ 2:"Connection Refused: identifier rejected",
+ 3:"Connection Refused: server unavailable",
+ 4:"Connection Refused: bad user name or password",
+ 5:"Connection Refused: not authorized"
+ };
/**
* Format an error message text.
* @private
- * @param {error} ERROR.KEY value above.
+ * @param {error} ERROR value above.
* @param {substitutions} [array] substituted into the text.
* @return the text with the substitutions made.
*/
- var format = function(error, substitutions) {
- var text = error.text;
- if (substitutions) {
- var field,start;
- for (var i=0; i* In contrast there are some callback functions, most notably onMessageArrived, - * that are defined on the {@link Paho.MQTT.Client} object. + * that are defined on the {@link Paho.Client} object. * These may get called multiple times, and aren't directly related to specific method invocations made by the client. * - * @name Paho.MQTT.Client + * @name Paho.Client * * @constructor * @@ -1710,12 +1717,12 @@ var PahoMQTT = (function (global) { * and the message has been removed from persistent storage before this callback is invoked. * Parameters passed to the onMessageDelivered callback are: *
* All attributes may be null, which implies the default values. * - * @name Paho.MQTT.Message + * @name Paho.Message * @constructor * @param {String|ArrayBuffer} payload The message data to be sent. *
@@ -2314,100 +2301,95 @@ var PahoMQTT = (function (global) {
* This is only set on messages received from the server.
*
*/
- var Message = function (newPayload) {
- var payload;
- if ( typeof newPayload === "string" ||
+ var Message = function (newPayload) {
+ var payload;
+ if ( typeof newPayload === "string" ||
newPayload instanceof ArrayBuffer ||
- newPayload instanceof Int8Array ||
- newPayload instanceof Uint8Array ||
- newPayload instanceof Int16Array ||
- newPayload instanceof Uint16Array ||
- newPayload instanceof Int32Array ||
- newPayload instanceof Uint32Array ||
- newPayload instanceof Float32Array ||
- newPayload instanceof Float64Array
- ) {
- payload = newPayload;
- } else {
- throw (format(ERROR.INVALID_ARGUMENT, [newPayload, "newPayload"]));
- }
-
- this._getPayloadString = function () {
- if (typeof payload === "string")
- return payload;
- else
- return parseUTF8(payload, 0, payload.length);
- };
-
- this._getPayloadBytes = function() {
- if (typeof payload === "string") {
- var buffer = new ArrayBuffer(UTF8Length(payload));
- var byteStream = new Uint8Array(buffer);
- stringToUTF8(payload, byteStream, 0);
-
- return byteStream;
+ (ArrayBuffer.isView(newPayload) && !(newPayload instanceof DataView))
+ ) {
+ payload = newPayload;
} else {
- return payload;
+ throw (format(ERROR.INVALID_ARGUMENT, [newPayload, "newPayload"]));
}
- };
-
- var destinationName;
- this._getDestinationName = function() { return destinationName; };
- this._setDestinationName = function(newDestinationName) {
- if (typeof newDestinationName === "string")
- destinationName = newDestinationName;
- else
- throw new Error(format(ERROR.INVALID_ARGUMENT, [newDestinationName, "newDestinationName"]));
- };
- var qos = 0;
- this._getQos = function() { return qos; };
- this._setQos = function(newQos) {
- if (newQos === 0 || newQos === 1 || newQos === 2 )
- qos = newQos;
- else
- throw new Error("Invalid argument:"+newQos);
+ var destinationName;
+ var qos = 0;
+ var retained = false;
+ var duplicate = false;
+
+ Object.defineProperties(this,{
+ "payloadString":{
+ enumerable : true,
+ get : function () {
+ if (typeof payload === "string")
+ return payload;
+ else
+ return parseUTF8(payload, 0, payload.length);
+ }
+ },
+ "payloadBytes":{
+ enumerable: true,
+ get: function() {
+ if (typeof payload === "string") {
+ var buffer = new ArrayBuffer(UTF8Length(payload));
+ var byteStream = new Uint8Array(buffer);
+ stringToUTF8(payload, byteStream, 0);
+
+ return byteStream;
+ } else {
+ return payload;
+ }
+ }
+ },
+ "destinationName":{
+ enumerable: true,
+ get: function() { return destinationName; },
+ set: function(newDestinationName) {
+ if (typeof newDestinationName === "string")
+ destinationName = newDestinationName;
+ else
+ throw new Error(format(ERROR.INVALID_ARGUMENT, [newDestinationName, "newDestinationName"]));
+ }
+ },
+ "qos":{
+ enumerable: true,
+ get: function() { return qos; },
+ set: function(newQos) {
+ if (newQos === 0 || newQos === 1 || newQos === 2 )
+ qos = newQos;
+ else
+ throw new Error("Invalid argument:"+newQos);
+ }
+ },
+ "retained":{
+ enumerable: true,
+ get: function() { return retained; },
+ set: function(newRetained) {
+ if (typeof newRetained === "boolean")
+ retained = newRetained;
+ else
+ throw new Error(format(ERROR.INVALID_ARGUMENT, [newRetained, "newRetained"]));
+ }
+ },
+ "topic":{
+ enumerable: true,
+ get: function() { return destinationName; },
+ set: function(newTopic) {destinationName=newTopic;}
+ },
+ "duplicate":{
+ enumerable: true,
+ get: function() { return duplicate; },
+ set: function(newDuplicate) {duplicate=newDuplicate;}
+ }
+ });
};
- var retained = false;
- this._getRetained = function() { return retained; };
- this._setRetained = function(newRetained) {
- if (typeof newRetained === "boolean")
- retained = newRetained;
- else
- throw new Error(format(ERROR.INVALID_ARGUMENT, [newRetained, "newRetained"]));
+ // Module contents.
+ return {
+ Client: Client,
+ Message: Message
};
-
- var duplicate = false;
- this._getDuplicate = function() { return duplicate; };
- this._setDuplicate = function(newDuplicate) { duplicate = newDuplicate; };
- };
-
- Message.prototype = {
- get payloadString() { return this._getPayloadString(); },
- get payloadBytes() { return this._getPayloadBytes(); },
-
- get destinationName() { return this._getDestinationName(); },
- set destinationName(newDestinationName) { this._setDestinationName(newDestinationName); },
-
- get topic() { return this._getDestinationName(); },
- set topic(newTopic) { this._setDestinationName(newTopic); },
-
- get qos() { return this._getQos(); },
- set qos(newQos) { this._setQos(newQos); },
-
- get retained() { return this._getRetained(); },
- set retained(newRetained) { this._setRetained(newRetained); },
-
- get duplicate() { return this._getDuplicate(); },
- set duplicate(newDuplicate) { this._setDuplicate(newDuplicate); }
- };
-
- // Module contents.
- return {
- Client: Client,
- Message: Message
- };
-})(window);
-return PahoMQTT;
+ // eslint-disable-next-line no-nested-ternary
+ })(typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
+ return PahoMQTT;
});
diff --git a/src/test/BasicTest-spec.js b/src/test/BasicTest-spec.js
index 44dd24c..e6845c4 100644
--- a/src/test/BasicTest-spec.js
+++ b/src/test/BasicTest-spec.js
@@ -6,371 +6,509 @@ var testPort = settings.port;
var testPath = settings.path;
var testMqttVersion = settings.mqttVersion;
var topicPrefix = settings.topicPrefix;
-
-var genStr = function(str){
- var time = new Date();
- return str + '.' + time.getTime();
+var testUseSSL = settings.useSSL;
+var genStr = function(str) {
+ var time = new Date();
+ return str + '.' + time.getTime();
};
describe('BasicTest', function() {
- //var client = null;
- var clientId = this.description;
- var connected = false;
- var failure = false;
- var disconnectError = null;
- var disconnectErrorMsg = null;
-
- var subscribed = false;
- var isMessageReceived = false;
- var isMessageDelivered = false;
- var strTopic = topicPrefix + '/' + makeid() + '/World';
- var strMessageReceived = '';
- var strMessageSend = 'Hello';
- var strTopicReceived = '';
-
-
- function makeid(){
+ //var client = null;
+ var clientId = this.description;
+ var connected = false;
+ var failure = false;
+ var disconnectError = null;
+ var disconnectErrorMsg = null;
+
+ var subscribed = false;
+ var isMessageReceived = false;
+ var isMessageDelivered = false;
+ var strTopic = topicPrefix + '/' + makeid() + '/World';
+ var strTopic2 = topicPrefix + '/' + makeid() + '/Mars';
+ var strMessageReceived = '';
+ var strMessageSend = 'Hello';
+ var strMessageSend2 = 'ä½ å¥½'; // Hello in Traditional Chinese and a good UTF-8 test
+ var strTopicReceived = '';
+
+ settings.printConfig(settings);
+
+
+ function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
- for( var i=0; i < 5; i++ )
- text += possible.charAt(Math.floor(Math.random() * possible.length));
+ for (var i = 0; i < 5; i++)
+ text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
- }
-
- function onConnectSuccess(responseObj) {
- //console.log("connected %s",responseObj);
- connected = true;
- };
-
- function onConnectionLost(err) {
- connected = false;
- if(err){
- disconnectError = err.errorCode;
- disconnectErrorMsg = err.errorMessage;
- }
- console.log("connection lost. ErrorCode: %s, ErrorMsg: %s",disconnectError,disconnectErrorMsg);
- };
-
- function onConnectFailure(err){
- connected = false;
- console.log('Connect fail. ErrorCode: %s, ErrorMsg: %s',err.errCode,err.errorMessage);
- };
-
- function onSubscribeSuccess() {
- subscribed = true;
- //console.log("subscribed",subscribed);
- };
-
- function onSubscribeFailure(err) {
- subscribed = false;
- console.log("subscribe fail. ErrorCode: %s, ErrorMsg: %s",err.errCode,err.errorMessage);
- };
- function onUnsubscribeSuccess() {
- subscribed = false;
- //console.log("unsubscribed",subscribed);
- };
-
- function messageDelivered(response) {
- console.log("messageDelivered. topic:%s, duplicate:%s, payloadString:%s,qos:%s,retained:%s",response.destinationName,response.duplicate,response.payloadString,response.qos,response.retained);
- isMessageDelivered = true;
- //reponse.invocationContext.onMessageArrived = null;
- };
-
- function messageArrived(message) {
- console.log("messageArrived.",'topic:',message.destinationName,' ;content:',message.payloadString);
- isMessageReceived = true;
- strMessageReceived = message.payloadString;
- strTopicReceived = message.destinationName;
-
- //reponse.invocationContext.onMessageArrived = null;
- };
-
- beforeEach(function(){
- connected = false;
- failure = false;
- disconnectError = null;
- disconnectErrorMsg = null;
- //if(!client){
- // client = new Paho.Client(testServer, testPort, clientId);
- //}
- });
-
- /*afterEach(function(){
- if(client){
- client.disconnect();
- }
- });
- */
- it('it should create and connect and disconnect to a server.', function() {
- var client = new Paho.Client(testServer, testPort, testPath, genStr(clientId));
- client.onConnectionLost = onConnectionLost;
- expect(client).not.toBe(null);
-
-
- console.log('Connecting...');
- runs(function() {
- client.connect({onSuccess:onConnectSuccess,onFailure:onConnectFailure,mqttVersion:testMqttVersion, useSSL: true});
- });
- waitsFor(function() {
- return connected;
- }, "the client should connect", 2000);
- runs(function() {
- expect(connected).toBe(true);
- });
-
- console.log('Disconnecting...');
- runs(function() {
- client.disconnect();
- });
- waitsFor(function() {
- return (connected==false);
- }, "the client should disconnect", 2000);
- runs(function() {
- expect(connected).not.toBe(true);
- });
-
- console.log('Re-Connecting...');
- runs(function() {
- client.connect({onSuccess:onConnectSuccess,mqttVersion:testMqttVersion, useSSL: true});
- });
-
- waitsFor(function() {
- return connected;
- }, "the client should re-connect", 2000);
-
- runs(function() {
- expect(connected).toBe(true);
- });
-
- });
-
- it('it should fallback from MQTTv3.1.1 to v3.1',function(){
- var client = new Paho.Client(testServer, testPort, testPath, genStr(clientId));
- client.onConnectionLost = onConnectionLost;
- expect(client).not.toBe(null);
-
- console.log('Connecting...');
- runs(function() {
- client.connect({onSuccess:onConnectSuccess,onFailure:onConnectFailure,timeout:1, useSSL: true});
- });
- waitsFor(function() {
- return connected;
- }, "the client should connect", 4000);
- runs(function() {
- expect(connected).toBe(true);
- });
-
- console.log('Disconnecting...');
- runs(function() {
- client.disconnect();
- });
- waitsFor(function() {
- return (connected==false);
- }, "the client should disconnect", 2000);
- runs(function() {
- expect(connected).not.toBe(true);
- });
- });
-
- it('it should connect to a list of server(HA connection).',function(){
- var defaultServer = testServer;
- var defaultPort = testPort;
- var arrHosts = ['localhost',testServer,];
- var arrPorts = [2000,testPort];
-
- var client = new Paho.Client(defaultServer, defaultPort, testPath, genStr(clientId) );
- client.onConnectionLost = onConnectionLost;
- expect(client).not.toBe(null);
-
- console.log('should connect to a available server from list');
- runs(function() {
- client.connect({
- onSuccess : onConnectSuccess,
- onFailure : onConnectFailure,
- hosts : arrHosts,
- ports : arrPorts,
- mqttVersion: testMqttVersion,
- useSSL : true
- });
- });
-
- waitsFor(function() {
- return connected;
- }, "the client should connect", 2000);
-
- runs(function() {
- expect(connected).toBe(true);
- //client.disconnect();
- });
-
- });
-
-
- it('it should publish and subscribe.',function(){
-
- var client = new Paho.Client(testServer, testPort, testPath, genStr(clientId));
- client.onMessageArrived = messageArrived;
- client.onMessageDelivered = messageDelivered;
-
- runs(function() {
- client.connect({onSuccess:onConnectSuccess,onFailure:onConnectFailure,mqttVersion:testMqttVersion, useSSL: true});
- });
- waitsFor(function() {
- return connected;
- }, "the client should connect", 5000);
- runs(function() {
- expect(connected).toBe(true);
- });
-
- console.log('Subscribe a topic...');
- runs(function() {
- client.subscribe(strTopic, {onSuccess:onSubscribeSuccess,onFailure:onSubscribeFailure});
- });
-
- waitsFor(function() {
- return subscribed;
- }, "the client should subscribe", 2000);
-
- runs(function() {
- expect(subscribed).toBe(true);
- });
-
- console.log('Send and receive message...');
- runs(function() {
- var message = new Paho.Message(strMessageSend);
- message.destinationName = strTopic;
- client.send(message);
- });
- waitsFor(function() {
- return isMessageReceived;
- }, "the client should send and receive a message", 2000);
- runs(function() {
- //to do Check message sent
- expect(isMessageDelivered).toBe(true);
- //Check msg received
- expect(isMessageReceived).toBe(true);
- //Check message
- expect(strMessageReceived).toEqual(strMessageSend);
- //Check topic
- expect(strTopicReceived).toEqual(strTopic);
-
- //disconnect
- //client.disconnect();
-
- });
-
- console.log('Unsubscribe a topic...');
- runs(function() {
- client.unsubscribe(strTopic, {onSuccess:onUnsubscribeSuccess});
- });
- waitsFor(function() {
- return !subscribed;
- }, "the client should subscribe", 2000);
- runs(function() {
- expect(subscribed).toBe(false);
- //disconnect
- //client.disconnect();
- });
-
- //should not receive a message after unsubscribe
- runs(function() {
- //console.log('isMessageReceived',isMessageReceived);
- isMessageDelivered = false;
- isMessageReceived = false;
- strMessageReceived = '';
- strTopicReceived = '';
-
- var message = new Paho.Message(genStr(strMessageSend));
- message.destinationName = strTopic;
- client.send(message);
- })
- waitsFor(function() {
- return isMessageDelivered;
- }, "the client should send and receive a message", 2000);
-
- runs(function() {
- //to do Check message sent
- expect(isMessageDelivered).toBe(true);
- //Check msg received
- expect(isMessageReceived).toBe(false);
- //Check message
- expect(strMessageReceived).toEqual('');
- //Check topic
- expect(strTopicReceived).toEqual('');
-
- //disconnect
- //client.disconnect();
-
- })
- });
-
- it('check message properties.',function(){
- var strMsg = 'test Msg';
- var strDes = topicPrefix + '/test';
- var message = new Paho.Message(strMsg);
- message.destinationName = strDes;
-
- console.log('Check default for message with payload.');
- expect(message.qos).toBe(0);
- expect(message.duplicate).toBe(false);
- expect(message.retained).toBe(false);
- expect(message.payloadString).toEqual(strMsg);
- expect(message.payloadBytes.length).toBeGreaterThan(0);
- expect(message.destinationName).toEqual(strDes);
-
- console.log('Check empty msg to throw error');
- expect(function(){
- var empMsg = new Paho.Message();
- }).toThrow();
-
- console.log('Check message qos');
- message.qos = 0;
- expect(message.qos).toBe(0);
- message.qos = 1;
- expect(message.qos).toBe(1);
- message.qos = 2;
- expect(message.qos).toBe(2);
-
- //illegal argument exception
- expect(function(){
- message.qos = -1;
- }).toThrow();
- expect(function(){
- message.qos = 1;
- }).not.toThrow();
-
- console.log('Check payload');
- var strPayload = 'payload is a string';
- message.payloadString = strPayload;
- console.log('not allowed to set payload');
- expect(message.payloadString).not.toEqual(strPayload);
-
- console.log('Check retained');
- message.retained = false;
- expect(message.retained).toBe(false);
- message.retained = true;
- expect(message.retained).toBe(true);
-
- console.log('Check duplicate');
- message.duplicate = false;
- expect(message.duplicate).toBe(false);
- message.duplicate = true;
- expect(message.duplicate).toBe(true);
-
- //to do , check payload
- /*
- var buffer = new ArrayBuffer(4);
- var uintArr = new Uint8Array(buffer);
- dataView = new DataView(buffer);
- dataView.setInt32(0,0x48656c6c);
- //dataView.setInt
- console.log(dataView.getInt32(0).toString(16));
- //var arrbufPayload = new ArrayBuffer
- var msg = new Paho.Message(buffer);
- console.log(msg.payloadBytes,msg.payloadString);
- */
- });
+ }
+
+ function onConnectSuccess(responseObj) {
+ //console.log("connected %s",responseObj);
+ connected = true;
+ };
+
+ function onConnectionLost(err) {
+ connected = false;
+ if (err) {
+ disconnectError = err.errorCode;
+ disconnectErrorMsg = err.errorMessage;
+ }
+ console.log("connection lost. ErrorCode: %s, ErrorMsg: %s", disconnectError, disconnectErrorMsg);
+ };
+
+ function onConnectFailure(err) {
+ connected = false;
+ console.log('Connect fail. ErrorCode: %s, ErrorMsg: %s', err.errCode, err.errorMessage);
+ };
+
+ function onSubscribeSuccess() {
+ subscribed = true;
+ //console.log("subscribed",subscribed);
+ };
+
+ function onSubscribeFailure(err) {
+ subscribed = false;
+ console.log("subscribe fail. ErrorCode: %s, ErrorMsg: %s", err.errCode, err.errorMessage);
+ };
+
+ function onUnsubscribeSuccess() {
+ subscribed = false;
+ //console.log("unsubscribed",subscribed);
+ };
+
+ function messageDelivered(response) {
+ console.log("messageDelivered. topic:%s, duplicate:%s, payloadString:%s,qos:%s,retained:%s", response.destinationName, response.duplicate, response.payloadString, response.qos, response.retained);
+ isMessageDelivered = true;
+ //reponse.invocationContext.onMessageArrived = null;
+ };
+
+ function messageArrived(message) {
+ console.log("messageArrived.", 'topic:', message.destinationName, ' ;content:', message.payloadString);
+ isMessageReceived = true;
+ strMessageReceived = message.payloadString;
+ strTopicReceived = message.destinationName;
+
+ //reponse.invocationContext.onMessageArrived = null;
+ };
+
+ beforeEach(function() {
+ connected = false;
+ failure = false;
+ disconnectError = null;
+ disconnectErrorMsg = null;
+ //if(!client){
+ // client = new Paho.Client(testServer, testPort, clientId);
+ //}
+ });
+
+ /*afterEach(function(){
+ if(client){
+ client.disconnect();
+ }
+ });
+ */
+ it('it should create and connect and disconnect to a server.', function() {
+ var client = new Paho.Client(testServer, testPort, testPath, genStr(clientId));
+ client.onConnectionLost = onConnectionLost;
+ expect(client).not.toBe(null);
+
+
+ console.log('Connecting...');
+ runs(function() {
+ client.connect({
+ onSuccess: onConnectSuccess,
+ onFailure: onConnectFailure,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+ });
+ waitsFor(function() {
+ return connected;
+ }, "the client should connect", 2000);
+ runs(function() {
+ expect(connected).toBe(true);
+ });
+
+ console.log('Disconnecting...');
+ runs(function() {
+ client.disconnect();
+ });
+ waitsFor(function() {
+ return (connected == false);
+ }, "the client should disconnect", 2000);
+ runs(function() {
+ expect(connected).not.toBe(true);
+ });
+
+ console.log('Re-Connecting...');
+ runs(function() {
+ client.connect({
+ onSuccess: onConnectSuccess,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+ });
+
+ waitsFor(function() {
+ return connected;
+ }, "the client should re-connect", 2000);
+
+ runs(function() {
+ expect(connected).toBe(true);
+ });
+
+ });
+
+ it('it should fallback from MQTTv3.1.1 to v3.1', function() {
+ var client = new Paho.Client(testServer, testPort, testPath, genStr(clientId));
+ client.onConnectionLost = onConnectionLost;
+ expect(client).not.toBe(null);
+
+ console.log('Connecting...');
+ runs(function() {
+ client.connect({
+ onSuccess: onConnectSuccess,
+ onFailure: onConnectFailure,
+ timeout: 1,
+ useSSL: testUseSSL
+ });
+ });
+ waitsFor(function() {
+ return connected;
+ }, "the client should connect", 4000);
+ runs(function() {
+ expect(connected).toBe(true);
+ });
+
+ console.log('Disconnecting...');
+ runs(function() {
+ client.disconnect();
+ });
+ waitsFor(function() {
+ return (connected == false);
+ }, "the client should disconnect", 2000);
+ runs(function() {
+ expect(connected).not.toBe(true);
+ });
+ });
+
+ it('it should connect to a list of server(HA connection).', function() {
+ var defaultServer = testServer;
+ var defaultPort = testPort;
+ var arrHosts = ['localhost', testServer, ];
+ var arrPorts = [2000, testPort];
+
+ var client = new Paho.Client(defaultServer, defaultPort, testPath, genStr(clientId));
+ client.onConnectionLost = onConnectionLost;
+ expect(client).not.toBe(null);
+
+ console.log('should connect to a available server from list');
+ runs(function() {
+ client.connect({
+ onSuccess: onConnectSuccess,
+ onFailure: onConnectFailure,
+ hosts: arrHosts,
+ ports: arrPorts,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+ });
+
+ waitsFor(function() {
+ return connected;
+ }, "the client should connect", 2000);
+
+ runs(function() {
+ expect(connected).toBe(true);
+ //client.disconnect();
+ });
+
+ });
+
+
+ it('it should publish and subscribe.', function() {
+
+ var client = new Paho.Client(testServer, testPort, testPath, genStr(clientId));
+ client.onMessageArrived = messageArrived;
+ client.onMessageDelivered = messageDelivered;
+
+ runs(function() {
+ client.connect({
+ onSuccess: onConnectSuccess,
+ onFailure: onConnectFailure,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+ });
+ waitsFor(function() {
+ return connected;
+ }, "the client should connect", 5000);
+ runs(function() {
+ expect(connected).toBe(true);
+ });
+
+ console.log('Subscribe a topic...');
+ runs(function() {
+ client.subscribe(strTopic, {
+ onSuccess: onSubscribeSuccess,
+ onFailure: onSubscribeFailure
+ });
+ });
+
+ waitsFor(function() {
+ return subscribed;
+ }, "the client should subscribe", 2000);
+
+ runs(function() {
+ expect(subscribed).toBe(true);
+ });
+
+ console.log('Send and receive message...');
+ runs(function() {
+ var message = new Paho.Message(strMessageSend);
+ message.destinationName = strTopic;
+ client.send(message);
+ });
+ waitsFor(function() {
+ return isMessageReceived;
+ }, "the client should send and receive a message", 2000);
+ runs(function() {
+ //to do Check message sent
+ expect(isMessageDelivered).toBe(true);
+ //Check msg received
+ expect(isMessageReceived).toBe(true);
+ //Check message
+ expect(strMessageReceived).toEqual(strMessageSend);
+ //Check topic
+ expect(strTopicReceived).toEqual(strTopic);
+
+ //disconnect
+ //client.disconnect();
+
+ });
+
+ console.log('Unsubscribe a topic...');
+ runs(function() {
+ client.unsubscribe(strTopic, {
+ onSuccess: onUnsubscribeSuccess
+ });
+ });
+ waitsFor(function() {
+ return !subscribed;
+ }, "the client should subscribe", 2000);
+ runs(function() {
+ expect(subscribed).toBe(false);
+ //disconnect
+ //client.disconnect();
+ });
+
+ //should not receive a message after unsubscribe
+ runs(function() {
+ //console.log('isMessageReceived',isMessageReceived);
+ isMessageDelivered = false;
+ isMessageReceived = false;
+ strMessageReceived = '';
+ strTopicReceived = '';
+
+ var message = new Paho.Message(genStr(strMessageSend));
+ message.destinationName = strTopic;
+ client.send(message);
+ })
+ waitsFor(function() {
+ return isMessageDelivered;
+ }, "the client should send and receive a message", 2000);
+
+ runs(function() {
+ //to do Check message sent
+ expect(isMessageDelivered).toBe(true);
+ //Check msg received
+ expect(isMessageReceived).toBe(false);
+ //Check message
+ expect(strMessageReceived).toEqual('');
+ //Check topic
+ expect(strTopicReceived).toEqual('');
+
+ //disconnect
+ //client.disconnect();
+
+ })
+ });
+
+ it('check message properties.', function() {
+ var strMsg = 'test Msg';
+ var strDes = topicPrefix + '/test';
+ var message = new Paho.Message(strMsg);
+ message.destinationName = strDes;
+
+ console.log('Check default for message with payload.');
+ expect(message.qos).toBe(0);
+ expect(message.duplicate).toBe(false);
+ expect(message.retained).toBe(false);
+ expect(message.payloadString).toEqual(strMsg);
+ expect(message.payloadBytes.length).toBeGreaterThan(0);
+ expect(message.destinationName).toEqual(strDes);
+
+ console.log('Check empty msg to throw error');
+ expect(function() {
+ var empMsg = new Paho.Message();
+ }).toThrow();
+
+ console.log('Check message qos');
+ message.qos = 0;
+ expect(message.qos).toBe(0);
+ message.qos = 1;
+ expect(message.qos).toBe(1);
+ message.qos = 2;
+ expect(message.qos).toBe(2);
+
+ //illegal argument exception
+ expect(function() {
+ message.qos = -1;
+ }).toThrow();
+ expect(function() {
+ message.qos = 1;
+ }).not.toThrow();
+
+ console.log('Check payload');
+ var strPayload = 'payload is a string';
+ message.payloadString = strPayload;
+ console.log('not allowed to set payload');
+ expect(message.payloadString).not.toEqual(strPayload);
+
+ console.log('Check retained');
+ message.retained = false;
+ expect(message.retained).toBe(false);
+ message.retained = true;
+ expect(message.retained).toBe(true);
+
+ console.log('Check duplicate');
+ message.duplicate = false;
+ expect(message.duplicate).toBe(false);
+ message.duplicate = true;
+ expect(message.duplicate).toBe(true);
+
+ //to do , check payload
+ /*
+ var buffer = new ArrayBuffer(4);
+ var uintArr = new Uint8Array(buffer);
+ dataView = new DataView(buffer);
+ dataView.setInt32(0,0x48656c6c);
+ //dataView.setInt
+ console.log(dataView.getInt32(0).toString(16));
+ //var arrbufPayload = new ArrayBuffer
+ var msg = new Paho.Message(buffer);
+ console.log(msg.payloadBytes,msg.payloadString);
+ */
+ });
+
+ it('it should subscribe to multiple topics.', function() {
+
+ var client = new Paho.Client(testServer, testPort, testPath, genStr(clientId));
+ client.onMessageArrived = messageArrived;
+ client.onMessageDelivered = messageDelivered;
+
+ runs(function() {
+ client.connect({
+ onSuccess: onConnectSuccess,
+ onFailure: onConnectFailure,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+ });
+ waitsFor(function() {
+ return connected;
+ }, "the client should connect", 5000);
+ runs(function() {
+ expect(connected).toBe(true);
+ });
+
+ console.log('Subscribe multiple topics...');
+ runs(function() {
+ client.subscribe([strTopic, strTopic2], {
+ onSuccess: onSubscribeSuccess,
+ onFailure: onSubscribeFailure
+ });
+ });
+
+ waitsFor(function() {
+ return subscribed;
+ }, "the client should subscribe to multiple topics.", 2000);
+
+ runs(function() {
+ expect(subscribed).toBe(true);
+ });
+
+ console.log('Send and receive message to the first topic...');
+ runs(function() {
+ var message= new Paho.Message(strMessageSend);
+ message.destinationName = strTopic;
+ client.send(message);
+ });
+
+ waitsFor(function() {
+ return isMessageReceived;
+ }, "the client should send and receive a message", 2000);
+ runs(function() {
+ //to do Check message sent
+ expect(isMessageDelivered).toBe(true);
+ //Check msg received
+ expect(isMessageReceived).toBe(true);
+ //Check message
+ expect(strMessageReceived).toEqual(strMessageSend);
+ //Check topic
+ expect(strTopicReceived).toEqual(strTopic);
+
+ //disconnect
+ //client.disconnect();
+
+ });
+
+ waitsFor(function() {
+ return isMessageReceived;
+ }, "Send and receive message to the second topic...", 2000);
+ runs(function() {
+ isMessageReceived = false;
+ var message= new Paho.Message(strMessageSend2);
+ message.destinationName = strTopic2;
+ client.send(message);
+
+ });
+
+
+
+ waitsFor(function() {
+ return isMessageReceived;
+ }, "the client should send and receive a message", 2000);
+ runs(function() {
+ //to do Check message sent
+ expect(isMessageDelivered).toBe(true);
+ //Check msg received
+ expect(isMessageReceived).toBe(true);
+ //Check message
+ expect(strMessageReceived).toEqual(strMessageSend2);
+ //Check topic
+ expect(strTopicReceived).toEqual(strTopic2);
+
+ //disconnect
+ //client.disconnect();
+
+ });
+
+ console.log('Unsubscribe from both topics...');
+ runs(function() {
+ client.unsubscribe([strTopic, strTopic2], {
+ onSuccess: onUnsubscribeSuccess
+ });
+ });
+ waitsFor(function() {
+ return !subscribed;
+ }, "the client should subscribe", 2000);
+ runs(function() {
+ expect(subscribed).toBe(false);
+ //disconnect
+ //client.disconnect();
+ });
+ });
});
diff --git a/src/test/base-spec.js b/src/test/base-spec.js
index da5e704..e332b14 100644
--- a/src/test/base-spec.js
+++ b/src/test/base-spec.js
@@ -1,82 +1,89 @@
-var settings = require('./client-harness');
+var settings = require('./client-harness')
-var testServer = settings.server;
-var testPort = settings.port;
-var testPath = settings.path;
-var testMqttVersion = settings.mqttVersion;
-var topicPrefix = settings.topicPrefix;
+var testServer = settings.server
+var testPort = settings.port
+var testPath = settings.path
+var testMqttVersion = settings.mqttVersion
+var topicPrefix = settings.topicPrefix
+var testUseSSL = settings.useSSL
describe('client', function() {
- var client = this;
- var connected = false;
- var subscribed = false;
- var messageReceived = false;
-
- function onConnect() {
- connected = true;
- };
-
- function onSubscribe() {
- subscribed = true;
- };
-
- function messageArrived(response) {
- messageReceived = true;
- //reponse.invocationContext.onMessageArrived = null;
- };
-
- it('should create a new client', function() {
- client = new settings.Paho.Client(testServer, testPort, testPath, "testclientid");
- client.onMessageArrived = messageArrived;
-
- expect(client).not.toBe(null);
- expect(client.host).toBe(testServer);
- expect(client.port).toBe(testPort);
- expect(client.path).toBe(testPath);
- });
-
- it('should connect to a server', function() {
- runs(function() {
- client.connect({onSuccess:onConnect, mqttVersion:testMqttVersion, useSSL: true});
- });
-
- waitsFor(function() {
- return connected;
- }, "the client should connect", 10000);
-
- runs(function() {
- expect(connected).toBe(true);
- });
- });
-
- it('should subscribe to a topic', function() {
- runs(function() {
- client.subscribe(topicPrefix + "/World", {onSuccess:onSubscribe});
- });
-
- waitsFor(function() {
- return subscribed;
- }, "the client should subscribe", 2000);
-
- runs(function() {
- expect(subscribed).toBe(true);
- });
- });
-
- it('should send and receive a message', function() {
- runs(function() {
- message = new settings.Paho.Message("Hello");
- message.destinationName = topicPrefix + "/World";
- client.send(message);
- })
-
- waitsFor(function() {
- return messageReceived;
- }, "the client should send and receive a message", 2000);
-
- runs(function() {
- expect(messageReceived).toBe(true);
- })
- });
+ var client = this;
+ var connected = false;
+ var subscribed = false;
+ var messageReceived = false;
+
+ function onConnect() {
+ connected = true;
+ };
+
+ function onSubscribe() {
+ subscribed = true;
+ };
+
+ function messageArrived(response) {
+ messageReceived = true;
+ //reponse.invocationContext.onMessageArrived = null;
+ };
+
+ it('should create a new client', function() {
+ client = new settings.Paho.Client(testServer, testPort, testPath, "testclientid");
+ client.onMessageArrived = messageArrived;
+
+ expect(client).not.toBe(null);
+ expect(client.host).toBe(testServer);
+ expect(client.port).toBe(testPort);
+ expect(client.path).toBe(testPath);
+ });
+
+ it('should connect to a server', function() {
+ runs(function() {
+ client.connect({
+ onSuccess: onConnect,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+ });
+
+ waitsFor(function() {
+ return connected;
+ }, "the client should connect", 10000);
+
+ runs(function() {
+ expect(connected).toBe(true);
+ });
+ });
+
+ it('should subscribe to a topic', function() {
+ runs(function() {
+ client.subscribe(topicPrefix + "/World", {
+ onSuccess: onSubscribe
+ });
+ });
+
+ waitsFor(function() {
+ return subscribed;
+ }, "the client should subscribe", 2000);
+
+ runs(function() {
+ expect(subscribed).toBe(true);
+ });
+ });
+
+ it('should send and receive a message', function() {
+ runs(function() {
+ message = new settings.Paho.Message("Hello");
+ message.destinationName = topicPrefix + "/World";
+ client.send(message);
+ })
+
+ waitsFor(function() {
+ return messageReceived;
+ }, "the client should send and receive a message", 2000);
+
+ runs(function() {
+ expect(messageReceived).toBe(true);
+ })
+ });
})
diff --git a/src/test/client-harness.js b/src/test/client-harness.js
index d259e12..943e8d4 100644
--- a/src/test/client-harness.js
+++ b/src/test/client-harness.js
@@ -1,126 +1,103 @@
-global.window = global;
+global.self = global
-var WebSocketClient = require('websocket').client;
+var WebSocketClient = require('websocket').client
var Paho = require('../paho-mqtt')
+require('dotenv').config()
+
+global.WebSocket = function(wsurl, protocol) {
+ var ws = new WebSocketClient()
+ var connection
+ var obj = {
+ send: function(msg) {
+ var nodeBuf = new Buffer(new Uint8Array(msg))
+ connection.send(nodeBuf)
+ },
+ get readyState() {
+ return ws.readyState;
+ }
+ };
+ ws.binaryType = 'arraybuffer';
-global.WebSocket = function(wsurl,protocol) {
- var ws = new WebSocketClient();
- var connection;
- var obj = {
- send: function(msg) {
- var nodeBuf = new Buffer(new Uint8Array(msg));
- connection.send(nodeBuf);
- },
- get readyState() { return ws.readyState; }
- };
-
- ws.binaryType = 'arraybuffer';
-
- ws.on("connect", function(conn) {
- connection = conn;
- conn.on("error", function (error) {
- console.log("socket error ",error);
- if (obj.onerror) {
- obj.onerror();
- }
- });
+ ws.on("connect", function(conn) {
+ connection = conn;
+ conn.on("error", function(error) {
+ console.log("socket error ", error);
+ if (obj.onerror) {
+ obj.onerror();
+ }
+ });
- conn.on("close", function(reasonCode, description) {
- console.log("socket closed ",description);
- })
+ conn.on("close", function(reasonCode, description) {
+ console.log("socket closed ", description);
+ })
- conn.on("message", function (message) {
- if (message.type === "binary") {
- if (obj.onmessage) {
- obj.onmessage({data:message.binaryData});
- }
- }
- });
- if (obj.onopen) {
- obj.onopen();
+ conn.on("message", function(message) {
+ if (message.type === "binary") {
+ if (obj.onmessage) {
+ obj.onmessage({
+ data: message.binaryData
+ });
}
+ }
});
- ws.on('connectFailed', function(error) {
- console.log('Connect Error: ' + error.toString());
- if (obj.onerror) {
- obj.onerror(error);
- }
- });
- ws.connect(wsurl, protocol);
- return obj;
+ if (obj.onopen) {
+ obj.onopen();
+ }
+ });
+ ws.on('connectFailed', function(error) {
+ console.log('Connect Error: ' + error.toString());
+ if (obj.onerror) {
+ obj.onerror(error);
+ }
+ });
+ ws.connect(wsurl, protocol);
+ return obj;
}
-var LocalStorage = require('node-localstorage').LocalStorage;
-global.localStorage = new LocalStorage('./persistence');
+var LocalStorage = require('node-localstorage').LocalStorage
+global.localStorage = new LocalStorage('./persistence')
var Paho = require('../paho-mqtt')
-global.Paho = Paho;
+global.Paho = Paho
-function ensureValue(prop,value) {
- if (prop == "" || prop[0] == "$") {
- return value;
- }
- return prop;
+function ensureValue(prop, value) {
+ if (prop === '' || prop[0] === '$') {
+ return value
+ }
+ return prop
}
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
- .substring(1);
+ .substring(1)
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
- s4() + '-' + s4() + s4() + s4();
+ s4() + '-' + s4() + s4() + s4()
}
-module.exports = {
- server: ensureValue("${test.server}","iot.eclipse.org"),
- port: parseInt(ensureValue("${test.server.port}","443")),
- path: ensureValue("${test.server.path}","/ws"),
- mqttVersion: parseInt(ensureValue("${test.server.mqttVersion}","3")),
- interopServer: ensureValue("${test.interopServer}","iot.eclipse.org"),
- interopPort: parseInt(ensureValue("${test.interopPort}","443")),
- interopPath: ensureValue("${test.interopPath}","/ws"),
- topicPrefix: "paho-mqtt-test-" + guid(),
- Paho: Paho
+function printConfig(settings) {
+ console.log(' - Eclipse Paho Javascript Client Test Harness Settings - ')
+ console.log('Server URI: ' + settings.server + ':' + settings.port + settings.path)
+ console.log('MQTT Version: ' + settings.mqttVersion)
+ console.log('Interop Server URI: ' + settings.interopServer + ':' + settings.interopPort + settings.interopPath)
}
-/*
-var connection = {
- "hostname" : "localhost",
- "port" : "1883"
-};
-
-var broker = new Paho.Client(connection.hostname, Number(connection.port), "clientId");
-broker.onConnectionLost = onConnectionLost;
-broker.onMessageArrived = onMessageArrived;
-broker.connect({onSuccess:onConnect,onFailure : onConnectFailure});
-function onConnect() {
- console.log("MQTT Broker Connected");
- console.log("broker = ");
- console.log(this);
- var topic = "/hello/world/#";
- broker.subscribe(topic);
-
- var staticTopic = "/hello/static";
- broker.subscribe(staticTopic);
-};
-function onConnectFailure() {
- console.log("connect failed");
+module.exports = {
+ server: ensureValue(process.env.TEST_SERVER, 'iot.eclipse.org'),
+ port: parseInt(ensureValue(process.env.TEST_SERVER_PORT, '443')),
+ path: ensureValue(process.env.TEST_SERVER_PATH, '/ws'),
+ mqttVersion: parseInt(ensureValue(process.env.TEST_SERVER_MQTTVER, '3')),
+ interopServer: ensureValue(process.env.TEST_INTEROPSERVER, 'iot.eclipse.org'),
+ interopPort: parseInt(ensureValue(process.env.TEST_INTEROPPORT, '443')),
+ interopPath: ensureValue(process.env.TEST_INTEROPPATH, '/ws'),
+ useSSL: ensureValue((process.env.TEST_USE_SSL === 'true'), true),
+ topicPrefix: 'paho-mqtt-test-' + guid(),
+ Paho: Paho,
+ printConfig: printConfig
}
-function onConnectionLost(responseObject) {
- console.log("onConnectionLost");
- if (responseObject.errorCode !== 0)
- console.log("onConnectionLost:"+responseObject.errorMessage);
-};
-
-function onMessageArrived(msg) {
- console.log("onMessageArrived: " + msg._getDestinationName());
- console.log("MSG : '" + msg._getPayloadString() + "'");
- console.log(msg);
-};
-*/
diff --git a/src/test/client-uris-spec.js b/src/test/client-uris-spec.js
index af9d1a9..326e901 100644
--- a/src/test/client-uris-spec.js
+++ b/src/test/client-uris-spec.js
@@ -5,76 +5,79 @@ var testServer = settings.server;
var testPort = settings.port;
var testPath = settings.path;
var testMqttVersion = settings.mqttVersion;
+var testUseSSL = settings.useSSL
describe('client-uris', function() {
- var client = this;
- var connected = false;
- var subscribed = false;
- var disconnectError = null;
- var messageReceived = false;
-
- function onConnect() {
- console.log("connected");
- disconnectError = null;
- connected = true;
- };
- function onDisconnect(err) {
- console.log("disconnected");
- disconnectError = err;
- connected = false;
- }
- function onSubscribe() {
- console.log("subscribed");
- subscribed = true;
- };
-
- function messageArrived(response) {
- console.log("messageArrived");
- messageReceived = true;
- //reponse.invocationContext.onMessageArrived = null;
- };
-
- it('should create a new client with a default path', function() {
- client = new Paho.Client(testServer, testPort, "testclientid");
-
- expect(client).not.toBe(null);
- expect(client.host).toBe(testServer);
- expect(client.port).toBe(testPort);
- expect(client.path).toBe("/mqtt");
-
- });
-
- it('should create a new client with a path', function() {
- client = new Paho.Client(testServer, testPort, testPath, "testclientid");
-
- expect(client).not.toBe(null);
- expect(client.host).toBe(testServer);
- expect(client.port).toBe(testPort);
- expect(client.path).toBe(testPath);
- });
-
- it('should create a new client with a uri', function() {
- client = new Paho.Client("ws://"+testServer+":"+testPort+testPath, "testclientid");
-
- expect(client).not.toBe(null);
- expect(client.host).toBe(testServer);
- expect(client.port).toBe(testPort);
- expect(client.path).toBe(testPath);
- });
-
- it('should fail to create a new client with an invalid ws uri', function() {
- client = null;
- var error;
- try {
- client = new Paho.Client("http://example.com", "testclientid");
- } catch(err) {
- error = err;
- }
- expect(client).toBe(null);
- expect(error).not.toBe(null);
- });
-
- /*
+ var client = this;
+ var connected = false;
+ var subscribed = false;
+ var disconnectError = null;
+ var messageReceived = false;
+
+ function onConnect() {
+ console.log("connected");
+ disconnectError = null;
+ connected = true;
+ };
+
+ function onDisconnect(err) {
+ console.log("disconnected");
+ disconnectError = err;
+ connected = false;
+ }
+
+ function onSubscribe() {
+ console.log("subscribed");
+ subscribed = true;
+ };
+
+ function messageArrived(response) {
+ console.log("messageArrived");
+ messageReceived = true;
+ //reponse.invocationContext.onMessageArrived = null;
+ };
+
+ it('should create a new client with a default path', function() {
+ client = new Paho.Client(testServer, testPort, "testclientid");
+
+ expect(client).not.toBe(null);
+ expect(client.host).toBe(testServer);
+ expect(client.port).toBe(testPort);
+ expect(client.path).toBe("/mqtt");
+
+ });
+
+ it('should create a new client with a path', function() {
+ client = new Paho.Client(testServer, testPort, testPath, "testclientid");
+
+ expect(client).not.toBe(null);
+ expect(client.host).toBe(testServer);
+ expect(client.port).toBe(testPort);
+ expect(client.path).toBe(testPath);
+ });
+
+ it('should create a new client with a uri', function() {
+ client = new Paho.Client("ws://" + testServer + ":" + testPort + testPath, "testclientid");
+
+ expect(client).not.toBe(null);
+ expect(client.host).toBe(testServer);
+ expect(client.port).toBe(testPort);
+ expect(client.path).toBe(testPath);
+ });
+
+ it('should fail to create a new client with an invalid ws uri', function() {
+ client = null;
+ var error;
+ try {
+ client = new Paho.Client("http://example.com", "testclientid");
+ } catch (err) {
+ error = err;
+ }
+ expect(client).toBe(null);
+ expect(error).not.toBe(null);
+ });
+
+ /*
// We don't yet expose setting the path element with the arrays of hosts/ports
// If you want a path other than /mqtt, you need to use the array of hosts-as-uris.
// Leaving this test here to remember this fact in case we add an array of paths to connopts
@@ -110,35 +113,40 @@ describe('client-uris', function() {
});
*/
- it('should connect and disconnect to a server using connectoptions hosts', function() {
- client = new Paho.Client(testServer, testPort, "testclientid");
- expect(client).not.toBe(null);
-
- client.onMessageArrived = messageArrived;
- client.onConnectionLost = onDisconnect;
-
- runs(function() {
- client.connect({onSuccess:onConnect,hosts:["ws://"+testServer+":"+testPort+testPath],mqttVersion:testMqttVersion, useSSL: true});
- });
-
- waitsFor(function() {
- return connected;
- }, "the client should connect", 10000);
-
- runs(function() {
- expect(connected).toBe(true);
- });
- runs(function() {
- client.disconnect();
- });
- waitsFor(function() {
- return !connected;
- }, "the client should disconnect",1000);
- runs(function() {
- expect(connected).toBe(false);
- expect(disconnectError).not.toBe(null);
- expect(disconnectError.errorCode).toBe(0);
- });
- });
+ it('should connect and disconnect to a server using connectoptions hosts', function() {
+ client = new Paho.Client(testServer, testPort, "testclientid");
+ expect(client).not.toBe(null);
+
+ client.onMessageArrived = messageArrived;
+ client.onConnectionLost = onDisconnect;
+
+ runs(function() {
+ client.connect({
+ onSuccess: onConnect,
+ hosts: ["ws://" + testServer + ":" + testPort + testPath],
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ })
+ });
+
+ waitsFor(function() {
+ return connected;
+ }, "the client should connect", 10000);
+
+ runs(function() {
+ expect(connected).toBe(true);
+ });
+ runs(function() {
+ client.disconnect();
+ });
+ waitsFor(function() {
+ return !connected;
+ }, "the client should disconnect", 1000);
+ runs(function() {
+ expect(connected).toBe(false);
+ expect(disconnectError).not.toBe(null);
+ expect(disconnectError.errorCode).toBe(0);
+ });
+ });
})
diff --git a/src/test/interops-spec.js b/src/test/interops-spec.js
index 724c51f..2bff66e 100644
--- a/src/test/interops-spec.js
+++ b/src/test/interops-spec.js
@@ -5,370 +5,402 @@ var testServer = settings.interopServer;
var testPort = settings.interopPort;
var testPath = settings.interopPath;
var topicPrefix = settings.topicPrefix;
-var testMqttVersion = 4;
+var testUseSSL = settings.useSSL
+var testMqttVersion = settings.mqttVersion;
-var genStr = function(str){
- var time = new Date();
- return str + '.' + time.getTime();
+var genStr = function(str) {
+ var time = new Date();
+ return str + '.' + time.getTime();
};
var topics = ["TopicA", "TopicA/B", "Topic/C", "TopicA/C", "/TopicA"];
var wildtopics = ["TopicA/+", "+/C", "#", "/#", "/+", "+/+", "TopicA/#"];
-var nosubscribetopics = ["test/nosubscribe",];
+var nosubscribetopics = ["test/nosubscribe", ];
describe('InteropsTests', function() {
- var clientId = this.description;
- var client = null;
- var failure = false;
- var subscribed = false;
- var disconnectError = null;
- var disconnectErrorMsg = null;
-
- var subscribed = false;
- var messageReceivedCount = 0;
- var messagePublishedCount = 0;
- var sendingComplete = false;
- var receivingComplete = false;
-
- beforeEach(function(){
- failure = false;
- subscribed = false;
- disconnectError = null;
- disconnectErrorMsg = null;
- messageReceivedCount = 0
- messagePublishedCount = 0;
- sendingComplete = false;
- receivingComplete = false;
- });
-
- afterEach(function(){
- if (client !== null && client.isConnected()) {
- client.disconnect();
- }
- client = null;
- });
-
- var callbacks = {
- onConnectionLost: function(err) {
- console.log("connectionLost " + err.errorMessage);
- },
- onMessageArrived: function(message) {
- console.log("messageArrived %s %s %s %s", message.destinationName, message.payloadString, message.qos, message.retained);
- messageReceivedCount++;
- if (messageReceivedCount == 3) {
- receivingComplete = true;
- }
- },
- onConnectSuccess: function(response) {
- connected = true;
- },
- onConnectFailure: function(err) {
- console.log('Connect failed %s %s',err.errCode,err.errorMessage);
- },
- onDisconnectSuccess: function(response) {
- connected = false;
- console.log("Disconnected from server")
- },
- onDisconnectFailure: function(err) {
- console.log('Disconnect failed %s %s',err.errCode,err.errorMessage);
- },
- onMessageDelivered: function(reponse) {
- messagePublishedCount++;
- if (messagePublishedCount == 3) {
- sendingComplete = true;
- }
- },
- onSubscribeSuccess: function() {
- subscribed = true;
- },
- };
-
- it('should connect, disconnect, subscribe, publish and receive messages', function() {
- client = new Paho.Client(testServer, testPort, testPath, "testclientid-js");
- client.onMessageArrived = callbacks.onMessageArrived;
- client.onMessageDelivered = callbacks.onMessageDelivered;
-
- expect(client).not.toBe(null);
-
- runs(function() {
- client.connect({onSuccess: callbacks.onConnectSuccess, mqttVersion:testMqttVersion, useSSL: true});
- });
- waitsFor(function() {
- return client.isConnected();
- }, "the client should connect", 5000);
- runs(function() {
- expect(client.isConnected()).toBe(true);
- });
-
- runs(function() {
- client.disconnect();
- });
- waitsFor(function() {
- return true;
- }, "the client should disconnect", 5000);
- runs(function() {
- expect(client.isConnected()).toBe(false);
- });
-
- runs(function() {
- client.connect({onSuccess: callbacks.onConnectSuccess, mqttVersion:testMqttVersion, useSSL: true});
- });
- waitsFor(function() {
- return client.isConnected();
- }, "the client should connect again", 5000);
- runs(function() {
- expect(client.isConnected()).toBe(true);
- });
-
- runs(function() {
- client.subscribe(topicPrefix + topics[0], {qos:2, onSuccess: callbacks.onSubscribeSuccess});
- });
- waitsFor(function() {
- return subscribed;
- }, "the client should subscribe", 2000);
- runs(function() {
- expect(subscribed).toBe(true);
- });
-
- runs(function (){
- for (var i = 0; i < 3; i++) {
- var message = new Paho.Message("qos " + i);
- message.destinationName = topicPrefix + topics[0];
- message.qos=i;
- client.send(message);
- }
- });
- waitsFor(function() {
- return sendingComplete;
- }, "the client should send 3 messages", 5000);
- waitsFor(function() {
- return receivingComplete;
- }, "the client should receive 3 messages", 5000);
- runs(function() {
- expect(messagePublishedCount).toBe(3);
- expect(messageReceivedCount).toBe(3)
- });
-
- runs(function() {
- client.disconnect({onSuccess: callbacks.onDisconnectSuccess});
- });
- waitsFor(function() {
- return connected;
- }, "the client should disconnect", 5000);
- runs(function() {
- expect(client.isConnected()).toBe(false);
- });
- });
-
- it('should connect, attempt to connect again and fail', function() {
- var exception = false;
- client = new Paho.Client(testServer, testPort, testPath, "testclientid-js");
- expect(client).not.toBe(null);
-
- runs(function() {
- client.connect({onSuccess: callbacks.onConnectSuccess, mqttVersion:testMqttVersion, useSSL: true});
- });
- waitsFor(function() {
- return client.isConnected();
- }, "the client should connect", 5000);
- runs(function() {
- expect(client.isConnected()).toBe(true);
- });
-
- runs(function() {
- try {
- client.connect({onSuccess: callbacks.onConnectSuccess, mqttVersion:testMqttVersion, useSSL: true});
- } catch (e) {
- console.log(e.message)
- if (e.message == "AMQJS0011E Invalid state already connected.") {
- exception = true
- }
- }
- });
- runs(function() {
- expect(exception).toBe(true);
- });
- });
-
- it('should connect successfully with a 0 length clientid with cleansession true', function() {
- client = new Paho.Client(testServer, testPort, testPath, "");
- expect(client).not.toBe(null);
-
- runs(function() {
- client.connect({cleanSession:true, onSuccess: callbacks.onConnectSuccess, mqttVersion:testMqttVersion, useSSL: true});
- });
- waitsFor(function() {
- return client.isConnected();
- }, "the client should connect", 5000);
- runs(function() {
- expect(client.isConnected()).toBe(true);
- });
-
- runs(function() {
- client.disconnect();
- });
- waitsFor(function() {
- return true;
- }, "the client should disconnect", 5000);
- runs(function() {
- expect(client.isConnected()).toBe(false);
- });
- });
-
- it('should fail to connect successfully with a 0 length clientid with cleansession false', function() {
- var connectFail = false;
- var failCallback = function(err) {
- connectFail = true;
- }
- client = new Paho.Client(testServer, testPort, testPath, "");
- expect(client).not.toBe(null);
-
- runs(function() {
- client.connect({cleanSession:false, onFailure:failCallback, mqttVersion:testMqttVersion, useSSL: true});
- });
- waitsFor(function() {
- return connectFail
- }, "the client should fail to connect", 5000);
- runs(function() {
- expect(client.isConnected()).toBe(false);
- });
- });
- /*
- it('should queue up messages on the server for offline clients', function() {
- client = new Paho.Client(testServer, testPort, testPath, "testclientid-js");
- client.onMessageArrived = callbacks.onMessageArrived;
-
- expect(client).not.toBe(null);
-
- runs(function() {
- client.connect({onSuccess: callbacks.onConnectSuccess, mqttVersion:testMqttVersion, cleanSession:false});
- });
- waitsFor(function() {
- return client.isConnected();
- }, "the client should connect", 5000);
- runs(function() {
- expect(client.isConnected()).toBe(true);
- });
-
- runs(function() {
- client.subscribe(wildtopics[5], {qos:2, onSuccess: callbacks.onSubscribeSuccess});
- });
- waitsFor(function() {
- return subscribed;
- }, "the client should subscribe", 2000);
- runs(function() {
- expect(subscribed).toBe(true);
- });
-
- runs(function() {
- client.disconnect();
- });
- waitsFor(function() {
- return true;
- }, "the client should disconnect", 5000);
- runs(function() {
- expect(client.isConnected()).toBe(false);
- });
-
- bClient = new Paho.Client(testServer, testPort, testPath, "testclientid-js-b");
- bClient.onMessageDelivered = callbacks.onMessageDelivered;
-
- runs(function() {
- bClient.connect({onSuccess: callbacks.onConnectSuccess, mqttVersion:testMqttVersion, cleanSession:true});
- });
- waitsFor(function() {
- return bClient.isConnected();
- }, "the client should connect again", 5000);
- runs(function() {
- expect(bClient.isConnected()).toBe(true);
- });
-
- runs(function (){
- for (var i = 0; i < 3; i++) {
- var message = new Paho.Message("qos " + i);
- message.destinationName = topics[i+1];
- message.qos=i;
- bClient.send(message);
- }
- });
- waitsFor(function() {
- return sendingComplete;
- }, "the client should send 3 messages", 5000);
- runs(function() {
- expect(messagePublishedCount).toBe(3);
- });
-
- runs(function() {
- bClient.disconnect({onSuccess: callbacks.onDisconnectSuccess});
- });
- waitsFor(function() {
- return connected;
- }, "the client should disconnect", 5000);
- runs(function() {
- expect(bClient.isConnected()).toBe(false);
- });
-
- runs(function() {
- client.connect({onSuccess: callbacks.onConnectSuccess, mqttVersion:testMqttVersion, cleanSession:false});
- });
- waitsFor(function() {
- return client.isConnected();
- }, "the client should connect", 5000);
- runs(function() {
- expect(client.isConnected()).toBe(true);
- });
- waitsFor(function() {
- return (messageReceivedCount > 1);
- }, "the client should receive 2/3 messages", 5000);
- runs(function() {
- expect(messageReceivedCount).toBeGreaterThan(1);
- });
- runs(function() {
- client.disconnect();
- });
- waitsFor(function() {
- return true;
- }, "the client should disconnect", 5000);
- runs(function() {
- expect(client.isConnected()).toBe(false);
- });
- });
-
-
- // This test has been commented out as it is only valid for a messagesight
- // server and behaviour differs between mqtt server implementations.
- it('should get a return code for failure to subscribe', function() {
- client = new Paho.Client(testServer, testPort, testPath, "testclientid-js");
- client.onMessageArrived = callbacks.onMessageArrived;
-
- var subFailed = false;
- var failSubscribe = function(response) {
- if (response.errorCode.get(0) == 0x80) {
- subFailed = true;
- }
- }
-
- expect(client).not.toBe(null);
-
- runs(function() {
- client.connect({onSuccess: callbacks.onConnectSuccess, mqttVersion:testMqttVersion, cleanSession:true});
- });
- waitsFor(function() {
- return client.isConnected();
- }, "the client should connect", 5000);
- runs(function() {
- expect(client.isConnected()).toBe(true);
- });
-
- runs(function() {
- client.subscribe(nosubscribetopics[0], {qos:2, onFailure: failSubscribe});
- });
- waitsFor(function() {
- return subFailed;
- }, "the client should fail to subscribe", 2000);
- runs(function() {
- expect(subFailed).toBe(true);
- });
- });
- */
+ var clientId = this.description;
+ var client = null;
+ var failure = false;
+ var subscribed = false;
+ var disconnectError = null;
+ var disconnectErrorMsg = null;
+
+ var subscribed = false;
+ var messageReceivedCount = 0;
+ var messagePublishedCount = 0;
+ var sendingComplete = false;
+ var receivingComplete = false;
+
+ beforeEach(function() {
+ failure = false;
+ subscribed = false;
+ disconnectError = null;
+ disconnectErrorMsg = null;
+ messageReceivedCount = 0
+ messagePublishedCount = 0;
+ sendingComplete = false;
+ receivingComplete = false;
+ });
+
+ afterEach(function() {
+ if (client !== null && client.isConnected()) {
+ client.disconnect();
+ }
+ client = null;
+ });
+
+ var callbacks = {
+ onConnectionLost: function(err) {
+ console.log("connectionLost " + err.errorMessage);
+ },
+ onMessageArrived: function(message) {
+ console.log("messageArrived %s %s %s %s", message.destinationName, message.payloadString, message.qos, message.retained);
+ messageReceivedCount++;
+ if (messageReceivedCount == 3) {
+ receivingComplete = true;
+ }
+ },
+ onConnectSuccess: function(response) {
+ connected = true;
+ },
+ onConnectFailure: function(err) {
+ console.log('Connect failed %s %s', err.errCode, err.errorMessage);
+ },
+ onDisconnectSuccess: function(response) {
+ connected = false;
+ console.log("Disconnected from server")
+ },
+ onDisconnectFailure: function(err) {
+ console.log('Disconnect failed %s %s', err.errCode, err.errorMessage);
+ },
+ onMessageDelivered: function(reponse) {
+ messagePublishedCount++;
+ if (messagePublishedCount == 3) {
+ sendingComplete = true;
+ }
+ },
+ onSubscribeSuccess: function() {
+ subscribed = true;
+ },
+ };
+
+ it('should connect, disconnect, subscribe, publish and receive messages', function() {
+ client = new Paho.Client(testServer, testPort, testPath, "testclientid-js");
+ client.onMessageArrived = callbacks.onMessageArrived;
+ client.onMessageDelivered = callbacks.onMessageDelivered;
+
+ expect(client).not.toBe(null);
+
+ runs(function() {
+ client.connect({
+ onSuccess: callbacks.onConnectSuccess,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+ });
+ waitsFor(function() {
+ return client.isConnected();
+ }, "the client should connect", 5000);
+ runs(function() {
+ expect(client.isConnected()).toBe(true);
+ });
+
+ runs(function() {
+ client.disconnect();
+ });
+ waitsFor(function() {
+ return true;
+ }, "the client should disconnect", 5000);
+ runs(function() {
+ expect(client.isConnected()).toBe(false);
+ });
+
+ runs(function() {
+ client.connect({
+ onSuccess: callbacks.onConnectSuccess,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+ });
+ waitsFor(function() {
+ return client.isConnected();
+ }, "the client should connect again", 5000);
+ runs(function() {
+ expect(client.isConnected()).toBe(true);
+ });
+
+ runs(function() {
+ client.subscribe(topicPrefix + topics[0], {
+ qos: 2,
+ onSuccess: callbacks.onSubscribeSuccess
+ });
+ });
+ waitsFor(function() {
+ return subscribed;
+ }, "the client should subscribe", 2000);
+ runs(function() {
+ expect(subscribed).toBe(true);
+ });
+
+ runs(function() {
+ for (var i = 0; i < 3; i++) {
+ var message = new Paho.Message("qos " + i);
+ message.destinationName = topicPrefix + topics[0];
+ message.qos = i;
+ client.send(message);
+ }
+ });
+ waitsFor(function() {
+ return sendingComplete;
+ }, "the client should send 3 messages", 5000);
+ waitsFor(function() {
+ return receivingComplete;
+ }, "the client should receive 3 messages", 5000);
+ runs(function() {
+ expect(messagePublishedCount).toBe(3);
+ expect(messageReceivedCount).toBe(3)
+ });
+
+ runs(function() {
+ client.disconnect({
+ onSuccess: callbacks.onDisconnectSuccess
+ });
+ });
+ waitsFor(function() {
+ return connected;
+ }, "the client should disconnect", 5000);
+ runs(function() {
+ expect(client.isConnected()).toBe(false);
+ });
+ });
+
+ it('should connect, attempt to connect again and fail', function() {
+ var exception = false;
+ client = new Paho.Client(testServer, testPort, testPath, "testclientid-js");
+ expect(client).not.toBe(null);
+
+ runs(function() {
+ client.connect({
+ onSuccess: callbacks.onConnectSuccess,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+ });
+ waitsFor(function() {
+ return client.isConnected();
+ }, "the client should connect", 5000);
+ runs(function() {
+ expect(client.isConnected()).toBe(true);
+ });
+
+ runs(function() {
+ try {
+ client.connect({
+ onSuccess: callbacks.onConnectSuccess,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+ } catch (e) {
+ console.log(e.message)
+ if (e.message == "AMQJS0011E Invalid state already connected.") {
+ exception = true
+ }
+ }
+ });
+ runs(function() {
+ expect(exception).toBe(true);
+ });
+ });
+
+ it('should connect successfully with a 0 length clientid with cleansession true', function() {
+ client = new Paho.Client(testServer, testPort, testPath, "");
+ expect(client).not.toBe(null);
+
+ runs(function() {
+ client.connect({
+ cleanSession: true,
+ onSuccess: callbacks.onConnectSuccess,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+ });
+ waitsFor(function() {
+ return client.isConnected();
+ }, "the client should connect", 5000);
+ runs(function() {
+ expect(client.isConnected()).toBe(true);
+ });
+
+ runs(function() {
+ client.disconnect();
+ });
+ waitsFor(function() {
+ return true;
+ }, "the client should disconnect", 5000);
+ runs(function() {
+ expect(client.isConnected()).toBe(false);
+ });
+ });
+
+ it('should fail to connect successfully with a 0 length clientid with cleansession false', function() {
+ var connectFail = false;
+ var failCallback = function(err) {
+ connectFail = true;
+ }
+ client = new Paho.Client(testServer, testPort, testPath, "");
+ expect(client).not.toBe(null);
+
+ runs(function() {
+ client.connect({
+ cleanSession: false,
+ onFailure: failCallback,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+ });
+ waitsFor(function() {
+ return connectFail
+ }, "the client should fail to connect", 5000);
+ runs(function() {
+ expect(client.isConnected()).toBe(false);
+ });
+ });
+ /*
+ it('should queue up messages on the server for offline clients', function() {
+ client = new Paho.Client(testServer, testPort, testPath, "testclientid-js");
+ client.onMessageArrived = callbacks.onMessageArrived;
+
+ expect(client).not.toBe(null);
+
+ runs(function() {
+ client.connect({onSuccess: callbacks.onConnectSuccess, mqttVersion:testMqttVersion, cleanSession:false});
+ });
+ waitsFor(function() {
+ return client.isConnected();
+ }, "the client should connect", 5000);
+ runs(function() {
+ expect(client.isConnected()).toBe(true);
+ });
+
+ runs(function() {
+ client.subscribe(wildtopics[5], {qos:2, onSuccess: callbacks.onSubscribeSuccess});
+ });
+ waitsFor(function() {
+ return subscribed;
+ }, "the client should subscribe", 2000);
+ runs(function() {
+ expect(subscribed).toBe(true);
+ });
+
+ runs(function() {
+ client.disconnect();
+ });
+ waitsFor(function() {
+ return true;
+ }, "the client should disconnect", 5000);
+ runs(function() {
+ expect(client.isConnected()).toBe(false);
+ });
+
+ bClient = new Paho.Client(testServer, testPort, testPath, "testclientid-js-b");
+ bClient.onMessageDelivered = callbacks.onMessageDelivered;
+
+ runs(function() {
+ bClient.connect({onSuccess: callbacks.onConnectSuccess, mqttVersion:testMqttVersion, cleanSession:true});
+ });
+ waitsFor(function() {
+ return bClient.isConnected();
+ }, "the client should connect again", 5000);
+ runs(function() {
+ expect(bClient.isConnected()).toBe(true);
+ });
+
+ runs(function (){
+ for (var i = 0; i < 3; i++) {
+ var message = new Paho.Message("qos " + i);
+ message.destinationName = topics[i+1];
+ message.qos=i;
+ bClient.send(message);
+ }
+ });
+ waitsFor(function() {
+ return sendingComplete;
+ }, "the client should send 3 messages", 5000);
+ runs(function() {
+ expect(messagePublishedCount).toBe(3);
+ });
+
+ runs(function() {
+ bClient.disconnect({onSuccess: callbacks.onDisconnectSuccess});
+ });
+ waitsFor(function() {
+ return connected;
+ }, "the client should disconnect", 5000);
+ runs(function() {
+ expect(bClient.isConnected()).toBe(false);
+ });
+
+ runs(function() {
+ client.connect({onSuccess: callbacks.onConnectSuccess, mqttVersion:testMqttVersion, cleanSession:false});
+ });
+ waitsFor(function() {
+ return client.isConnected();
+ }, "the client should connect", 5000);
+ runs(function() {
+ expect(client.isConnected()).toBe(true);
+ });
+ waitsFor(function() {
+ return (messageReceivedCount > 1);
+ }, "the client should receive 2/3 messages", 5000);
+ runs(function() {
+ expect(messageReceivedCount).toBeGreaterThan(1);
+ });
+ runs(function() {
+ client.disconnect();
+ });
+ waitsFor(function() {
+ return true;
+ }, "the client should disconnect", 5000);
+ runs(function() {
+ expect(client.isConnected()).toBe(false);
+ });
+ });
+
+
+ // This test has been commented out as it is only valid for a messagesight
+ // server and behaviour differs between mqtt server implementations.
+ it('should get a return code for failure to subscribe', function() {
+ client = new Paho.Client(testServer, testPort, testPath, "testclientid-js");
+ client.onMessageArrived = callbacks.onMessageArrived;
+
+ var subFailed = false;
+ var failSubscribe = function(response) {
+ if (response.errorCode.get(0) == 0x80) {
+ subFailed = true;
+ }
+ }
+
+ expect(client).not.toBe(null);
+
+ runs(function() {
+ client.connect({onSuccess: callbacks.onConnectSuccess, mqttVersion:testMqttVersion, cleanSession:true});
+ });
+ waitsFor(function() {
+ return client.isConnected();
+ }, "the client should connect", 5000);
+ runs(function() {
+ expect(client.isConnected()).toBe(true);
+ });
+
+ runs(function() {
+ client.subscribe(nosubscribetopics[0], {qos:2, onFailure: failSubscribe});
+ });
+ waitsFor(function() {
+ return subFailed;
+ }, "the client should fail to subscribe", 2000);
+ runs(function() {
+ expect(subFailed).toBe(true);
+ });
+ });
+ */
})
diff --git a/src/test/live-take-over-spec.js b/src/test/live-take-over-spec.js
index b9e6d9f..fe11d90 100644
--- a/src/test/live-take-over-spec.js
+++ b/src/test/live-take-over-spec.js
@@ -6,242 +6,260 @@ var testPort = settings.port;
var testPath = settings.path;
var testMqttVersion = settings.mqttVersion;
var topicPrefix = settings.topicPrefix;
+var testUseSSL = settings.useSSL
describe('LiveTakeOver', function() {
- //*************************************************************************
- // Client wrapper - define a client wrapper to ease testing
- //*************************************************************************
- var MqttClient= function(clientId){
- var client = new Paho.Client(testServer, testPort, testPath, clientId);
- //states
- var connected = false;
- var subscribed = false;
- var messageReceived = false;
- var messageDelivered = false;
- var receivedMessage = null;
-
- this.states={connected:connected};
-
- //reset all states
- this.resetStates=function(){
- connected = false;
- subscribed = false;
- messageReceived = false;
- messageDelivered = false;
- receivedMessage = null;
- };
-
- //callbacks
- var onConnect=function() {
- console.log("%s connected",clientId);
- connected = true;
- };
-
- var onDisconnect=function(response) {
- console.log("%s disconnected",clientId);
- connected = false;
- };
-
- var onSubscribe=function() {
- console.log("%s subscribed",clientId);
- subscribed = true;
- };
-
- var onUnsubscribe=function() {
- console.log("%s unsubscribed",clientId);
- subscribed = false;
- };
-
- var onMessageArrived=function(msg) {
- console.log("%s received msg: %s",clientId,msg.payloadString);
- messageReceived = true;
- receivedMessage = msg;
- };
-
- var onMessageDelivered=function(msg){
- console.log("%s delivered message: %s",clientId,msg.payloadString);
- messageDelivered=true;
- }
-
- //set callbacks
- client.onMessageArrived = onMessageArrived;
- client.onConnectionLost = onDisconnect;
- client.onMessageDelivered = onMessageDelivered;
-
- //functions
- //connect and verify
- this.connect=function(connectOptions){
- connectOptions = connectOptions || {};
- if(!connectOptions.hasOwnProperty("onSuccess")){
- connectOptions.onSuccess=onConnect;
- connectOptions.mqttVersion=testMqttVersion;
- connectOptions.useSSL = true;
- }
- runs(function() {
- client.connect(connectOptions);
- });
-
- waitsFor(function() {
- return connected;
- }, "the client should connect", 10000);
-
- runs(function() {
- expect(connected).toBe(true);
- //reset state
- connected=false;
- });
- };
-
- //disconnect and verify
- this.disconnect=function(){
- runs(function() {
- client.disconnect();
- });
-
- waitsFor(function() {
- return !connected;
- }, "the client should disconnect", 10000);
-
- runs(function() {
- expect(connected).not.toBe(true);
- });
- };
-
- //subscribe and verify
- this.subscribe=function(topic,qos){
- runs(function() {
- client.subscribe(topic, {qos:qos,onSuccess:onSubscribe});
- });
-
- waitsFor(function() {
- return subscribed;
- }, "the client should subscribe", 2000);
-
- runs(function() {
- expect(subscribed).toBe(true);
- //reset state
- subscribed=false;
- });
- };
-
- //unsubscribe and verify
- this.unsubscribe=function(topic){
- runs(function() {
- client.unsubscribe(topic, {onSuccess:onUnsubscribe});
- });
-
- waitsFor(function() {
- return !subscribed;
- }, "the client should subscribe", 2000);
-
- runs(function() {
- expect(subscribed).not.toBe(true);
- });
- };
-
- //publish and verify
- this.publish=function(topic,qos,payload){
- runs(function() {
- var message = new Paho.Message(payload);
- message.destinationName = topic;
- message.qos=qos;
- client.send(message);
- })
-
- waitsFor(function() {
- return messageDelivered;
- }, "the client should delivered a message",10000);
-
- runs(function() {
- //reset state
- messageDelivered=false;
- });
- };
-
-
- //verify no message received
- this.receiveNone=function(){
- waits(2000);
- runs(function() {
- expect(messageReceived).toBe(false);
- expect(receivedMessage).toBeNull();
- });
- };
-
- //verify the receive message
- this.receive=function(expectedTopic,publishedQoS,subscribedQoS,expectedPayload){
-
- waitsFor(function() {
- return messageReceived;
- }, "the client should send and receive a message",10000);
-
- runs(function() {
- expect(messageReceived).toBe(true);
- expect(receivedMessage).not.toBeNull();
- expect(receivedMessage.qos).toBe(Math.min(publishedQoS,subscribedQoS));
- expect(receivedMessage.destinationName).toBe(expectedTopic);
- if(typeof expectedPayload === "string"){
- expect(receivedMessage.payloadString).toEqual(expectedPayload);
- }else{
- expect(receivedMessage.payloadBytes).toEqual(expectedPayload);
- }
-
- //reset state after each publish
- messageReceived=false;
- receivedMessage=null;
- })
- };
- };
-
- //*************************************************************************
- // Tests
- //*************************************************************************
-
- it('should be taken over by another client for the actively doing work.', function() {
- var clientId="TakeOverClient1";
- var testTopic=topicPrefix + "FirstClient/Topic";
- var subscribedQoS=2;
- var publishQoS=1;
- var payload="TakeOverPayload";
-
- //will msg
- var willMessage= new Paho.Message("will-payload");
- willMessage.destinationName = topicPrefix + "willTopic";
- willMessage.qos = 2;
- willMessage.retained=true;
-
- var client1= new MqttClient(clientId);
- client1.connect({cleanSession:false,willMessage:willMessage,mqttVersion:testMqttVersion, useSSL: true});
-
- //subscribe
- client1.subscribe(testTopic, subscribedQoS);
-
- //publish some messwage
- for(var i=0;i<9;i++){
- client1.publish(testTopic,publishQoS,payload);
- client1.receive(testTopic,publishQoS,subscribedQoS,payload);
- }
-
- // Now lets take over the connection
- // Create a second MQTT client connection with the same clientid. The
- // server should spot this and kick the first client connection off.
- var client2= new MqttClient(clientId);
- client2.connect({cleanSession:false,willMessage:willMessage,mqttVersion:testMqttVersion, useSSL: true});
-
- waitsFor(function() {
- return !client1.states.connected;
- }, "the previous client should be disconnected",10000);
-
- // We should have taken over the first Client's subscription...
- //Now check we have grabbed his subscription by publishing.
- client2.publish(testTopic,publishQoS,payload);
- client2.receive(testTopic,publishQoS,subscribedQoS,payload);
-
- //disconnect
- client2.disconnect();
- });
+ //*************************************************************************
+ // Client wrapper - define a client wrapper to ease testing
+ //*************************************************************************
+ var MqttClient = function(clientId) {
+ var client = new Paho.Client(testServer, testPort, testPath, clientId);
+ //states
+ var connected = false;
+ var subscribed = false;
+ var messageReceived = false;
+ var messageDelivered = false;
+ var receivedMessage = null;
+
+ this.states = {
+ connected: connected
+ };
+
+ //reset all states
+ this.resetStates = function() {
+ connected = false;
+ subscribed = false;
+ messageReceived = false;
+ messageDelivered = false;
+ receivedMessage = null;
+ };
+
+ //callbacks
+ var onConnect = function() {
+ console.log("%s connected", clientId);
+ connected = true;
+ };
+
+ var onDisconnect = function(response) {
+ console.log("%s disconnected", clientId);
+ connected = false;
+ };
+
+ var onSubscribe = function() {
+ console.log("%s subscribed", clientId);
+ subscribed = true;
+ };
+
+ var onUnsubscribe = function() {
+ console.log("%s unsubscribed", clientId);
+ subscribed = false;
+ };
+
+ var onMessageArrived = function(msg) {
+ console.log("%s received msg: %s", clientId, msg.payloadString);
+ messageReceived = true;
+ receivedMessage = msg;
+ };
+
+ var onMessageDelivered = function(msg) {
+ console.log("%s delivered message: %s", clientId, msg.payloadString);
+ messageDelivered = true;
+ }
+
+ //set callbacks
+ client.onMessageArrived = onMessageArrived;
+ client.onConnectionLost = onDisconnect;
+ client.onMessageDelivered = onMessageDelivered;
+
+ //functions
+ //connect and verify
+ this.connect = function(connectOptions) {
+ connectOptions = connectOptions || {};
+ if (!connectOptions.hasOwnProperty("onSuccess")) {
+ connectOptions.onSuccess = onConnect;
+ connectOptions.mqttVersion = testMqttVersion;
+ connectOptions.useSSL = testUseSSL;
+ }
+ runs(function() {
+ client.connect(connectOptions);
+ });
+
+ waitsFor(function() {
+ return connected;
+ }, "the client should connect", 10000);
+
+ runs(function() {
+ expect(connected).toBe(true);
+ //reset state
+ connected = false;
+ });
+ };
+
+ //disconnect and verify
+ this.disconnect = function() {
+ runs(function() {
+ client.disconnect();
+ });
+
+ waitsFor(function() {
+ return !connected;
+ }, "the client should disconnect", 10000);
+
+ runs(function() {
+ expect(connected).not.toBe(true);
+ });
+ };
+
+ //subscribe and verify
+ this.subscribe = function(topic, qos) {
+ runs(function() {
+ client.subscribe(topic, {
+ qos: qos,
+ onSuccess: onSubscribe
+ });
+ });
+
+ waitsFor(function() {
+ return subscribed;
+ }, "the client should subscribe", 2000);
+
+ runs(function() {
+ expect(subscribed).toBe(true);
+ //reset state
+ subscribed = false;
+ });
+ };
+
+ //unsubscribe and verify
+ this.unsubscribe = function(topic) {
+ runs(function() {
+ client.unsubscribe(topic, {
+ onSuccess: onUnsubscribe
+ });
+ });
+
+ waitsFor(function() {
+ return !subscribed;
+ }, "the client should subscribe", 2000);
+
+ runs(function() {
+ expect(subscribed).not.toBe(true);
+ });
+ };
+
+ //publish and verify
+ this.publish = function(topic, qos, payload) {
+ runs(function() {
+ var message = new Paho.Message(payload);
+ message.destinationName = topic;
+ message.qos = qos;
+ client.send(message);
+ })
+
+ waitsFor(function() {
+ return messageDelivered;
+ }, "the client should delivered a message", 10000);
+
+ runs(function() {
+ //reset state
+ messageDelivered = false;
+ });
+ };
+
+
+ //verify no message received
+ this.receiveNone = function() {
+ waits(2000);
+ runs(function() {
+ expect(messageReceived).toBe(false);
+ expect(receivedMessage).toBeNull();
+ });
+ };
+
+ //verify the receive message
+ this.receive = function(expectedTopic, publishedQoS, subscribedQoS, expectedPayload) {
+
+ waitsFor(function() {
+ return messageReceived;
+ }, "the client should send and receive a message", 10000);
+
+ runs(function() {
+ expect(messageReceived).toBe(true);
+ expect(receivedMessage).not.toBeNull();
+ expect(receivedMessage.qos).toBe(Math.min(publishedQoS, subscribedQoS));
+ expect(receivedMessage.destinationName).toBe(expectedTopic);
+ if (typeof expectedPayload === "string") {
+ expect(receivedMessage.payloadString).toEqual(expectedPayload);
+ } else {
+ expect(receivedMessage.payloadBytes).toEqual(expectedPayload);
+ }
+
+ //reset state after each publish
+ messageReceived = false;
+ receivedMessage = null;
+ })
+ };
+ };
+
+ //*************************************************************************
+ // Tests
+ //*************************************************************************
+
+ it('should be taken over by another client for the actively doing work.', function() {
+ var clientId = "TakeOverClient1";
+ var testTopic = topicPrefix + "FirstClient/Topic";
+ var subscribedQoS = 2;
+ var publishQoS = 1;
+ var payload = "TakeOverPayload";
+
+ //will msg
+ var willMessage = new Paho.Message("will-payload");
+ willMessage.destinationName = topicPrefix + "willTopic";
+ willMessage.qos = 2;
+ willMessage.retained = true;
+
+ var client1 = new MqttClient(clientId);
+ client1.connect({
+ cleanSession: false,
+ willMessage: willMessage,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+
+ //subscribe
+ client1.subscribe(testTopic, subscribedQoS);
+
+ //publish some messwage
+ for (var i = 0; i < 9; i++) {
+ client1.publish(testTopic, publishQoS, payload);
+ client1.receive(testTopic, publishQoS, subscribedQoS, payload);
+ }
+
+ // Now lets take over the connection
+ // Create a second MQTT client connection with the same clientid. The
+ // server should spot this and kick the first client connection off.
+ var client2 = new MqttClient(clientId);
+ client2.connect({
+ cleanSession: false,
+ willMessage: willMessage,
+ mqttVersion: testMqttVersion,
+ useSSL: testUseSSL
+ });
+
+ waitsFor(function() {
+ return !client1.states.connected;
+ }, "the previous client should be disconnected", 10000);
+
+ // We should have taken over the first Client's subscription...
+ //Now check we have grabbed his subscription by publishing.
+ client2.publish(testTopic, publishQoS, payload);
+ client2.receive(testTopic, publishQoS, subscribedQoS, payload);
+
+ //disconnect
+ client2.disconnect();
+ });
})
diff --git a/src/test/send-receive-spec.js b/src/test/send-receive-spec.js
index 457d275..fdf9fa2 100644
--- a/src/test/send-receive-spec.js
+++ b/src/test/send-receive-spec.js
@@ -6,354 +6,387 @@ var testPort = settings.port;
var testPath = settings.path;
var testMqttVersion = settings.mqttVersion;
var topicPrefix = settings.topicPrefix;
+var testUseSSL = settings.useSSL
//define a default clientID
-var clientId="testClient1";
+var clientId = "testClient1";
describe('SendReceive', function() {
- //*************************************************************************
- // Client wrapper - define a client wrapper to ease testing
- //*************************************************************************
- var MqttClient= function(clientId){
- var client = new Paho.Client(testServer, testPort, testPath, clientId);
- //states
- var connected = false;
- var subscribed = false;
- var messageReceived = false;
- var messageDelivered = false;
- var receivedMessage = null;
-
- //reset all states
- this.resetStates=function(){
- connected = false;
- subscribed = false;
- messageReceived = false;
- messageDelivered = false;
- receivedMessage = null;
- };
-
- //callbacks
- var onConnect=function() {
- console.log("%s connected",clientId);
- connected = true;
- };
-
- var onDisconnect=function(response) {
- console.log("%s disconnected",clientId);
- connected = false;
- };
-
- var onSubscribe=function() {
- console.log("%s subscribed",clientId);
- subscribed = true;
- };
-
- var onUnsubscribe=function() {
- console.log("%s unsubscribed",clientId);
- subscribed = false;
- };
-
- var onMessageArrived=function(msg) {
- console.log("%s received msg: %s",clientId,msg.payloadString);
- messageReceived = true;
- receivedMessage = msg;
- };
-
- var onMessageDelivered=function(msg){
- console.log("%s delivered message: %s",clientId,msg.payloadString);
- messageDelivered=true;
- }
-
- //set callbacks
- client.onMessageArrived = onMessageArrived;
- client.onConnectionLost = onDisconnect;
- client.onMessageDelivered = onMessageDelivered;
-
- //functions
- //connect and verify
- this.connect=function(connectOptions){
- connectOptions = connectOptions || {};
- if(!connectOptions.hasOwnProperty("onSuccess")){
- connectOptions.onSuccess=onConnect;
- connectOptions.mqttVersion=testMqttVersion;
- connectOptions.useSSL = true;
- }
- runs(function() {
- client.connect(connectOptions);
- });
-
- waitsFor(function() {
- return connected;
- }, "the client should connect", 10000);
-
- runs(function() {
- expect(connected).toBe(true);
- //reset state
- connected=false;
- });
- };
-
- //disconnect and verify
- this.disconnect=function(){
- runs(function() {
- client.disconnect();
- });
-
- waitsFor(function() {
- return !connected;
- }, "the client should disconnect", 10000);
-
- runs(function() {
- expect(connected).not.toBe(true);
- });
- };
-
- //subscribe and verify
- this.subscribe=function(topic,qos){
- runs(function() {
- client.subscribe(topic, {qos:qos,onSuccess:onSubscribe});
- });
-
- waitsFor(function() {
- return subscribed;
- }, "the client should subscribe", 2000);
-
- runs(function() {
- expect(subscribed).toBe(true);
- //reset state
- subscribed=false;
- });
- };
-
- //unsubscribe and verify
- this.unsubscribe=function(topic){
- runs(function() {
- client.unsubscribe(topic, {onSuccess:onUnsubscribe});
- });
-
- waitsFor(function() {
- return !subscribed;
- }, "the client should subscribe", 2000);
-
- runs(function() {
- expect(subscribed).not.toBe(true);
- });
- };
-
- //publish and verify
- this.publish=function(topic,qos,payload){
- runs(function() {
- var message = new Paho.Message(payload);
- message.destinationName = topic;
- message.qos=qos;
- client.send(message);
- })
-
- waitsFor(function() {
- return messageDelivered;
- }, "the client should delivered a message",10000);
-
- runs(function() {
- //reset state
- messageDelivered=false;
- });
- };
-
-
- //verify no message received
- this.receiveNone=function(){
- waits(2000);
- runs(function() {
- expect(messageReceived).toBe(false);
- expect(receivedMessage).toBeNull();
- });
- };
-
- //verify the receive message
- this.receive=function(expectedTopic,publishedQoS,subscribedQoS,expectedPayload){
-
- waitsFor(function() {
- return messageReceived;
- }, "the client should send and receive a message",10000);
-
- runs(function() {
- expect(messageReceived).toBe(true);
- expect(receivedMessage).not.toBeNull();
- expect(receivedMessage.qos).toBe(Math.min(publishedQoS,subscribedQoS));
- expect(receivedMessage.destinationName).toBe(expectedTopic);
- if(typeof expectedPayload === "string"){
- expect(receivedMessage.payloadString).toEqual(expectedPayload);
- }else{
- expect(receivedMessage.payloadBytes).toEqual(expectedPayload);
- }
-
- //reset state after each publish
- messageReceived=false;
- receivedMessage=null;
- })
- };
- };
-
- //*************************************************************************
- // Tests
- //*************************************************************************
-
- it('should connect to a server and disconnect from a server', function() {
- var client= new MqttClient(clientId);
-
- //connect and verify
- client.connect({mqttVersion:testMqttVersion, useSSL: true});
-
- //disconnect and verify
- client.disconnect();
- });
-
-
- it('should pub/sub using largish messages', function() {
- var client= new MqttClient(clientId);
-
- //connect and verify
- client.connect({mqttVersion:testMqttVersion, useSSL: true});
-
- //subscribe and verify
- var testTopic=topicPrefix + "pubsub/topic";
- var subscribedQoS=0;
- client.subscribe(testTopic,subscribedQoS);
-
- //unsubscribe and verify
- client.unsubscribe(testTopic);
-
- //subscribe again
- client.subscribe(testTopic,subscribedQoS);
-
- //publish a large message to the topic and verify
- var publishQoS=0;
- var payload="";
- var largeSize=10000;
- for(var i=0;i This page uses your browsers Local Storage functionality
+ to store MQTT messages whilst they are "inflight". This allows the Paho javascript client to ensure that QoS 1 and QoS 2 messages are successfully delivered even
+ if the network connection or browser fails. If you do not wish for the Local Storage to be used, please do not use this client, or only use QoS 0 to send and
+ receive messages. If you wish to see the data being stored for yourself, open up your developer console and look for the Local Storage section,
+ as messages are sent and received, you will see entries appearing and disappearing as the messages complete their QoS 1 and QoS 2 flows.
+ Messages are deleted as soon as they have completed their QoS flow. More information about the Eclipse Privacy and cookie policy can be found Here.