diff options
-rw-r--r-- | index.html | 166 | ||||
-rw-r--r-- | js/minified.js | 1 | ||||
-rw-r--r-- | js/mqttws31.js | 2143 | ||||
-rw-r--r-- | js/sortable.js | 319 |
4 files changed, 2629 insertions, 0 deletions
diff --git a/index.html b/index.html new file mode 100644 index 0000000..6d5fc04 --- /dev/null +++ b/index.html @@ -0,0 +1,166 @@ +<!DOCTYPE html> +<html> +<head> + <meta charset="utf-8" /> + <title>Alpine Linux builds</title> + <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css"> + <style> + body { padding: 15px; } + .host, .msgs, .prgr_built, .prgr_total, .progress-value { white-space: nowrap; } + .msgs { width: 400px; font-size: 0.9em; } + .progress-value { font-size: 0.8em; position: relative; bottom: 3px;} + .sortable a { color: black; text-decoration: none; } + .sortable th span { display: none; } + #mqtt_connect_status { font-size: 0.8em; } + </style> + <script src="js/mqttws31.js" type="text/javascript"></script> + <script src="js/minified.js" type="text/javascript"></script> + <script src="js/sortable.js" type="text/javascript"></script> + <script language="javascript" type="text/javascript"> + var MINI = require('minified'); + var _=MINI._, $=MINI.$, $$=MINI.$$, EE=MINI.EE, HTML=MINI.HTML; + + var wsHost = "msg.alpinelinux.org"; + var wsPort = "8083"; + var wsSub = "build/#"; + var max_mqtt_msgs_count = 3; + + function connect(){ + // !!!!!!!! temporary + if (window.location.search.match(/localhost/g)){ wsHost = "localhost"; } + + // Create a client instance + var clientId = Math.random().toString(36).substr(2, 22); // length - 20 symb + var client = new Paho.MQTT.Client(wsHost, Number(wsPort), clientId); + + // set callback handlers + client.onConnectionLost = onConnectionLost; + client.onMessageArrived = onMessageArrived; + + // connect the client + client.connect({onSuccess:onConnect,onFailure:onFailure}); + + // called when the client connects + function onConnect() { + // Once a connection has been made, make a subscription + client.subscribe(wsSub); + echo('CONNECTED to websocket. SUBSCRIBED to ' + wsSub, false, 'green'); + + // send a message + // message = new Paho.MQTT.Message("Hello"); + // message.destinationName = "World"; + // client.send(message); + } + + function onFailure() { + echo('Sorry, the websocket at "' + wsName + '" is unavailable.', false, 'red'); + setTimeout('connect();', 2000); + } + + // called when the client looses its connection + function onConnectionLost(responseObject) { + if (responseObject.errorCode !== 0) { + echo('CONNECTION LOST<br>' + responseObject.errorMessage, false, 'red'); + setTimeout('connect();', 2000); + } + } + + // called when a message arrives + function onMessageArrived(message) { + var host = message.destinationName || null; + host = host ? host.split("build/build-").pop() : null; + mqtt_msg(host,message.payloadString); + } + + setTimeout('sort_table();', 1500); + } + + function echo(msg,mqtt_msg,color){ + var pre = document.createElement("p"); + pre.style.wordWrap = "break-word"; + if (color) pre.style.color = color; + pre.innerHTML = msg; + + var output = (mqtt_msg ? document.getElementById("mqtt_msgs") : document.getElementById("mqtt_connect_status")); + if (output) output.appendChild(pre); + + var max_msg_count = ( mqtt_msg ? max_mqtt_msgs_count : 1 ); + if (output && output.childNodes.length > max_msg_count) { + output.removeChild(output.firstChild); + } + } + + function mqtt_msg(host, msg){ + id = "bs_"+host; + if (!$('#servers #'+id).length) { + $('#servers').add(EE('tr', {'@id':id}, [ + EE('td', {'className': 'nr'}, $('#servers tr').length+1), + EE('td', {'className': 'host'}, host), + EE('td', {'className': 'msgs_container'}), + EE('td', {'className': 'prgr_built'}), + EE('td', {'className': 'prgr_total'}), + ])); + $('#'+id+' .msgs_container').add(EE('div', {'className': 'msgs'})); + } + + if (msg == "idle") { + $('#'+id+' .msgs').ht(''); // clear previous messages + }else if ($('#'+id+' .msgs span').length >= max_mqtt_msgs_count) { + $('#'+id+' .msgs span')[0].remove(); + $('#'+id+' .msgs br')[0].remove(); + } + + + var pat = /^(\d+)\/(\d+)\s+(\d+)\/(\d+)\s+(.*)/i + if (msg.match(pat)) { + var msg_arr = msg.match(pat); + var built_curr = msg_arr[1]; + var built_last = msg_arr[2]; + var repo_curr = msg_arr[3]; + var repo_last = msg_arr[4]; + var built_pr = Math.round(built_curr*100/built_last); + var repo_pr = Math.round(repo_curr*100/repo_last); + msg = msg_arr[5]; + + $('#'+id+' .prgr_built').ht('<progress value="'+built_curr+'" max="'+built_last+'"></progress> <span class="progress-value">'+built_pr+'%</span>'); + $('#'+id+' .prgr_total').ht('<progress value="'+repo_curr+'" max="'+repo_last+'"></progress> <span class="progress-value">'+repo_pr+'%</span>'); + }else{ + $('#'+id+' .prgr_built').ht('<progress value="0" max="100"></progress> <span class="progress-value"> </span>'); + $('#'+id+' .prgr_total').ht('<progress value="0" max="100"></progress> <span class="progress-value"> </span>'); + } + + $('#'+id+' .msgs').add([EE('span', msg), EE('br')]); + } + + function sort_table(){ + var host_header = document.getElementById( 'host' ).getElementsByTagName( 'a' )[0]; + if (host_header) host_header.click(); // this will sort table by host column + + // update order nr's after sorting + $('#servers tr').each(function(obj, index) { + $('#'+obj.id+' .nr').ht(index+1); + }); + } + + window.addEventListener("load", connect, false); + </script> +</head> + +<body> + <h3>Alpine Linux Builds:</h3> + <table id="builds" class="pure-table pure-table-striped sortable"> + <thead> + <tr> + <th>#</th> + <th id="host">host</th> + <th>activity</th> + <th>aport built</th> + <th>aport total</th> + </tr> + </thead> + <tbody id="servers"> + </tbody> + </table> + <div id="mqtt_connect_status"></div> +</body> +</html> diff --git a/js/minified.js b/js/minified.js new file mode 100644 index 0000000..b6e27a2 --- /dev/null +++ b/js/minified.js @@ -0,0 +1 @@ +/^u/.test(typeof define)&&function(a){var b=this.require=function(b){return a[b]};this.define=function(c,d){a[c]=a[c]||d(b)}}({}),define("minified",function(){function a(a){return a.substr(0,3)}function b(a){return a!=Db?""+a:""}function c(a){return"string"==typeof a}function d(a){return!!a&&"object"==typeof a}function e(a){return a&&a.nodeType}function f(a){return"number"==typeof a}function g(a){return d(a)&&!!a.getDay}function h(a){return!0===a||!1===a}function i(a){var b=typeof a;return"object"==b?!(!a||!a.getDay):"string"==b||"number"==b||h(a)}function j(a){return a}function k(a){return a+1}function l(a,c,d){return b(a).replace(c,d!=Db?d:"")}function m(a){return l(a,/[\\\[\]\/{}()*+?.$|^-]/g,"\\$&")}function n(a){return l(a,/^\s+|\s+$/g)}function o(a,b,c){for(var d in a)a.hasOwnProperty(d)&&b.call(c||a,d,a[d]);return a}function p(a,b,c){if(a)for(var d=0;d<a.length;d++)b.call(c||a,a[d],d);return a}function q(a,b,c){var d=[],e=db(b)?b:function(a){return b!=a};return p(a,function(b,f){e.call(c||a,b,f)&&d.push(b)}),d}function r(a,b,c,d){var e=[];return a(b,function(a,f){eb(a=c.call(d||b,a,f))?p(a,function(a){e.push(a)}):a!=Db&&e.push(a)}),e}function s(a,b,c){return r(p,a,b,c)}function t(a){var b=0;return o(a,function(){b++}),b}function u(a){var b=[];return o(a,function(a){b.push(a)}),b}function v(a,b,c){var d=[];return p(a,function(e,f){d.push(b.call(c||a,e,f))}),d}function w(a,b){if(eb(a)){var c=ub(b);return M(G(a,0,c.length),c)}return b!=Db&&a.substr(0,b.length)==b}function x(a,b){if(eb(a)){var c=ub(b);return M(G(a,-c.length),c)||!c.length}return b!=Db&&a.substr(a.length-b.length)==b}function y(a){var b=a.length;return eb(a)?new tb(v(a,function(){return a[--b]})):l(a,/[\s\S]/g,function(){return a.charAt(--b)})}function z(a,b){var c={};return p(a,function(a){c[a]=b}),c}function A(a,b){var c,d=b||{};for(c in a)d[c]=a[c];return d}function B(a,b){for(var c=b,d=0;d<a.length;d++)c=A(a[d],c);return c}function C(a){return db(a)?a:function(b,c){return a===b?c:void 0}}function D(a,b,c){return b==Db?c:0>b?Math.max(a.length+b,0):Math.min(a.length,b)}function E(a,b,c,d){b=C(b),d=D(a,d,a.length);for(var e=D(a,c,0);d>e;e++)if((c=b.call(a,a[e],e))!=Db)return c}function F(a,b,c,d){b=C(b),d=D(a,d,-1);for(var e=D(a,c,a.length-1);e>d;e--)if((c=b.call(a,a[e],e))!=Db)return c}function G(a,b,c){var d=[];if(a)for(c=D(a,c,a.length),b=D(a,b,0);c>b;b++)d.push(a[b]);return d}function H(a){return v(a,j)}function I(a){return function(){return new tb(O(a,arguments))}}function J(a){var b={};return q(a,function(a){return b[a]?!1:b[a]=1})}function K(a,b){var c=z(b,1);return q(a,function(a){var b=c[a];return c[a]=0,b})}function L(a,b){for(var c=0;c<a.length;c++)if(a[c]==b)return!0;return!1}function M(a,b){var c,d=db(a)?a():a,e=db(b)?b():b;return d==e?!0:d==Db||e==Db?!1:i(d)||i(e)?g(d)&&g(e)&&+d==+e:eb(d)?d.length==e.length&&!E(d,function(a,b){return M(a,e[b])?void 0:!0}):!eb(e)&&(c=u(d)).length==t(e)&&!E(c,function(a){return M(d[a],e[a])?void 0:!0})}function N(a,b,c){return db(a)?a.apply(c&&b,v(c||b,j)):void 0}function O(a,b,c){return v(a,function(a){return N(a,b,c)})}function P(a,b,c,d){return function(){return N(a,b,s([c,arguments,d],j))}}function Q(a,b){for(var c=0>b?"-":"",d=(c?-b:b).toFixed(0);d.length<a;)d="0"+d;return c+d}function R(a,b,c){var d,e=0,f=c?b:y(b);return a=(c?a:y(a)).replace(/./g,function(a){return"0"==a?(d=!1,f.charAt(e++)||"0"):"#"==a?(d=!0,f.charAt(e++)||""):d&&!f.charAt(e)?"":a}),c?a:b.substr(0,b.length-e)+y(a)}function S(a,b,c){return b!=Db&&a?60*parseFloat(a[b])+parseFloat(a[b+1])+c.getTimezoneOffset():0}function T(a){return new Date(+a)}function U(a,b,c){return a["set"+b](a["get"+b]()+c),a}function V(a,b,c){return c==Db?V(new Date,a,b):U(T(a),b.charAt(0).toUpperCase()+b.substr(1),c)}function W(a,b,c){var d=+b,e=+c,f=e-d;if(0>f)return-W(a,c,b);if(b={milliseconds:1,seconds:1e3,minutes:6e4,hours:36e5}[a])return f/b;for(b=a.charAt(0).toUpperCase()+a.substr(1),a=Math.floor(f/{fullYear:31536e6,month:2628e6,date:864e5}[a]-2),d=U(new Date(d),b,a),f=a;1.2*a+4>f;f++)if(+U(d,b,1)>e)return f}function X(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)}function Y(a){return l(a,/[\x00-\x1f'"\u2028\u2029]/g,X)}function Z(a,b){function c(a,c){var d=[];return e.call(c||a,a,function(a,b){eb(a)?p(a,function(a,c){b.call(a,a,c)}):o(a,function(a,c){b.call(c,a,c)})},b||j,function(){N(d.push,d,arguments)},ub),d.join("")}if(Kb[a])return Kb[a];var d="with(_.isObject(obj)?obj:{}){"+v(a.split(/{{|}}}?/g),function(a,b){var c,d=n(a),e=l(d,/^{/),d=d==e?"esc(":"";return b%2?(c=/^each\b(\s+([\w_]+(\s*,\s*[\w_]+)?)\s*:)?(.*)/.exec(e))?"each("+(n(c[4])?c[4]:"this")+", function("+c[2]+"){":(c=/^if\b(.*)/.exec(e))?"if("+c[1]+"){":(c=/^else\b\s*(if\b(.*))?/.exec(e))?"}else "+(c[1]?"if("+c[2]+")":"")+"{":(c=/^\/(if)?/.exec(e))?c[1]?"}\n":"});\n":(c=/^(var\s.*)/.exec(e))?c[1]+";":(c=/^#(.*)/.exec(e))?c[1]:(c=/(.*)::\s*(.*)/.exec(e))?"print("+d+'_.formatValue("'+Y(c[2])+'",'+(n(c[1])?c[1]:"this")+(d&&")")+"));\n":"print("+d+(n(e)?e:"this")+(d&&")")+");\n":a?'print("'+Y(a)+'");\n':void 0}).join("")+"}",e=Function("obj","each","esc","print","_",d);return 99<Lb.push(c)&&delete Kb[Lb.shift()],Kb[a]=c}function $(a){return l(a,/[<>'"&]/g,function(a){return"&#"+a.charCodeAt(0)+";"})}function _(a,b){return Z(a,$)(b)}function ab(a){return function(b,c){return new tb(a(this,b,c))}}function bb(a){return function(b,c,d){return a(this,b,c,d)}}function cb(a){return function(b,c,d){return new tb(a(b,c,d))}}function db(a){return"function"==typeof a&&!a.item}function eb(a){return a&&a.length!=Db&&!c(a)&&!e(a)&&!db(a)&&a!==wb}function fb(a){return parseFloat(l(a,/^[^\d-]+/))}function gb(a){return a.Nia=a.Nia||++zb}function hb(a,b){var c,d=[],e={};return rb(a,function(a){rb(b(a),function(a){e[c=gb(a)]||(d.push(a),e[c]=!0)})}),d}function ib(a,b){var c={$position:"absolute",$visibility:"hidden",$display:"block",$height:Db},d=a.get(c),c=a.set(c).get("clientHeight");return a.set(d),c*b+"px"}function jb(a){Ab?Ab.push(a):setTimeout(a,0)}function kb(a,b,c){return ob(a,b,c)[0]}function lb(a,b,c){return a=nb(document.createElement(a)),eb(b)||b!=Db&&!d(b)?a.add(b):a.set(b).add(c)}function mb(a){return r(rb,a,function(a){return eb(a)?mb(a):(e(a)&&(a=a.cloneNode(!0),a.removeAttribute&&a.removeAttribute("id")),a)})}function nb(a,b,c){return db(a)?jb(a):new tb(ob(a,b,c))}function ob(a,b,d){function f(a){return eb(a)?r(rb,a,f):a}function g(a){return q(r(rb,a,f),function(a){for(;a=a.parentNode;)if(a==b[0]||d)return a==b[0]})}return b?1!=(b=ob(b)).length?hb(b,function(b){return ob(a,b,d)}):c(a)?1!=e(b[0])?[]:d?g(b[0].querySelectorAll(a)):b[0].querySelectorAll(a):g(a):c(a)?document.querySelectorAll(a):r(rb,a,f)}function pb(a,b){function d(a,b){var c=RegExp("(^|\\s+)"+a+"(?=$|\\s)","i");return function(d){return a?c.test(d[b]):!0}}var g,h,i={},j=i;return db(a)?a:f(a)?function(b,c){return c==a}:!a||"*"==a||c(a)&&(j=/^([\w-]*)\.?([\w-]*)$/.exec(a))?(g=d(j[1],"tagName"),h=d(j[2],"className"),function(a){return 1==e(a)&&g(a)&&h(a)}):b?function(c){return nb(a,b).find(c)!=Db}:(nb(a).each(function(a){i[gb(a)]=!0}),function(a){return i[gb(a)]})}function qb(a){var b=pb(a);return function(a){return b(a)?Db:!0}}function rb(a,b){return eb(a)?p(a,b):a!=Db&&b(a,0),a}function sb(){function a(a,c){return b==Db&&a!=Db&&(b=a,i=eb(c)?c:[c],setTimeout(function(){p(e,function(a){a()})},0)),b}var b,c,e=[],f=arguments,g=f.length,h=0,i=[];return p(f,function k(b,c){try{b.then?b.then(function(b){var e;(d(b)||db(b))&&db(e=b.then)?k(e,c):(i[c]=v(arguments,j),++h==g&&a(!0,2>g?i[c]:i))},function(){i[c]=v(arguments,j),a(!1,2>g?i[c]:[i[c][0],i,c])}):b(function(){a(!0,arguments)},function(){a(!1,arguments)})}catch(e){a(!1,[e,i,c])}}),a.stop=function(){return p(f,function(a){a.stop&&a.stop()}),N(a.stop0)},c=a.then=function(c,f){function g(){try{var a=b?c:f;db(a)?function g(a){try{var b,c=0;if((d(a)||db(a))&&db(b=a.then)){if(a===h)throw new TypeError;b.call(a,function(a){c++||g(a)},function(a){c++||h(!1,[a])}),h.stop0=a.stop}else h(!0,[a])}catch(e){c++||h(!1,[e])}}(N(a,vb,i)):h(b,i)}catch(e){h(!1,[e])}}var h=sb();return h.stop0=a.stop,b!=Db?setTimeout(g,0):e.push(g),h},a.always=function(a){return c(a,a)},a.error=function(a){return c(0,a)},a}function tb(a,b){var c,d,e,f,g,h=0;if(a)for(c=0,d=a.length;d>c;c++)if(e=a[c],b&&eb(e))for(f=0,g=e.length;g>f;f++)this[h++]=e[f];else this[h++]=e;else this[h++]=b;this.length=h,this._=!0}function ub(){return new tb(arguments,!0)}var vb,wb=this,xb={},yb={},zb=1,Ab=/^[ic]/.test(document.readyState)?Db:[],Bb={},Cb=0,Db=null,Eb="January,February,March,April,May,June,July,August,September,October,November,December".split(/,/g),Fb=v(Eb,a),Gb="Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(/,/g),Hb=v(Gb,a),Ib={y:["FullYear",j],Y:["FullYear",function(a){return a%100}],M:["Month",k],n:["Month",Fb],N:["Month",Eb],d:["Date",j],m:["Minutes",j],H:["Hours",j],h:["Hours",function(a){return a%12||12}],k:["Hours",k],K:["Hours",function(a){return a%12}],s:["Seconds",j],S:["Milliseconds",j],a:["Hours","am,am,am,am,am,am,am,am,am,am,am,am,pm,pm,pm,pm,pm,pm,pm,pm,pm,pm,pm,pm".split(/,/g)],w:["Day",Hb],W:["Day",Gb],z:["TimezoneOffset",function(a,b,c){return c?c:(b=a>0?a:-a,(0>a?"+":"-")+Q(2,Math.floor(b/60))+Q(2,b%60))}]},Jb={y:0,Y:[0,-2e3],M:[1,1],n:[1,Fb],N:[1,Eb],d:2,m:4,H:3,h:3,K:[3,1],k:[3,1],s:5,S:6,a:[3,"am,pm".split(/,/g)]},Kb={},Lb=[];return A({each:bb(p),filter:ab(q),collect:ab(s),map:ab(v),toObject:bb(z),equals:bb(M),sub:ab(G),reverse:bb(y),find:bb(E),findLast:bb(F),startsWith:bb(w),endsWith:bb(x),contains:bb(L),call:ab(O),array:bb(H),unite:bb(I),merge:bb(B),uniq:ab(J),intersection:ab(K),join:function(a){return v(this,j).join(a)},reduce:function(a,b){return p(this,function(c,d){b=a.call(this,b,c,d)}),b},sort:function(a){return new tb(v(this,j).sort(a))},remove:function(){rb(this,function(a){a.parentNode.removeChild(a)})},text:function(){return r(rb,this,function(a){return a.textContent}).join("")},trav:function(a,b,c){var d=f(b),e=pb(d?Db:b),g=d?b:c;return new tb(hb(this,function(b){for(var c=[];(b=b[a])&&c.length!=g;)e(b)&&c.push(b);return c}))},next:function(a,b){return this.trav("nextSibling",a,b||1)},up:function(a,b){return this.trav("parentNode",a,b||1)},select:function(a,b){return nb(a,this,b)},is:function(a){return!this.find(qb(a))},only:function(a){return new tb(q(this,pb(a)))},not:function(a){return new tb(q(this,qb(a)))},get:function(a,b){var d,e,f,g=this,h=g[0];return h?c(a)?(d=/^(\W*)(.*)/.exec(l(a,/^%/,"@data-")),e=d[1],h=yb[e]?yb[e](this,d[2]):"$"==a?g.get("className"):"$$"==a?g.get("@style"):"$$slide"==a?g.get("$height"):"$$fade"==a||"$$show"==a?"hidden"==g.get("$visibility")||"none"==g.get("$display")?0:"$$fade"==a?isNaN(g.get("$opacity",!0))?1:g.get("$opacity",!0):1:"$"==e?wb.getComputedStyle(h,Db).getPropertyValue(l(d[2],/[A-Z]/g,function(a){return"-"+a.toLowerCase()})):"@"==e?h.getAttribute(d[2]):h[d[2]],b?fb(h):h):(f={},(eb(a)?rb:o)(a,function(a){f[a]=g.get(a,b)}),f):void 0},set:function(a,b){var d,e,f=this;return b!==vb?(d=/^(\W*)(.*)/.exec(l(l(a,/^\$float$/,"cssFloat"),/^%/,"@data-")),e=d[1],xb[e]?xb[e](this,d[2],b):"$$fade"==a?this.set({$visibility:b?"visible":"hidden",$opacity:b}):"$$slide"==a?f.set({$visibility:b?"visible":"hidden",$overflow:"hidden",$height:/px/.test(b)?b:function(a,c,d){return ib(nb(d),b)}}):"$$show"==a?b?f.set({$visibility:b?"visible":"hidden",$display:""}).set({$display:function(a){return"none"==a?"block":a}}):f.set({$display:"none"}):"$$"==a?f.set("@style",b):rb(this,function(c,f){var g=db(b)?b(nb(c).get(a),f,c):b;"$"==e?d[2]?c.style[d[2]]=g:rb(g&&g.split(/\s+/),function(a){var b=l(a,/^[+-]/),d=c.className||"",e=l(d,RegExp("(^|\\s+)"+b+"(?=$|\\s)"));(/^\+/.test(a)||b==a&&d==e)&&(e+=" "+b),c.className=n(e)}):"$$scrollX"==a?c.scroll(g,nb(c).get("$$scrollY")):"$$scrollY"==a?c.scroll(nb(c).get("$$scrollX"),g):"@"==e?g==Db?c.removeAttribute(d[2]):c.setAttribute(d[2],g):c[d[2]]=g})):c(a)||db(a)?f.set("$",a):o(a,function(a,b){f.set(a,b)}),f},show:function(){return this.set("$$show",1)},hide:function(){return this.set("$$show",0)},add:function(a,b){return this.each(function(c,d){function f(a){eb(a)?rb(a,f):db(a)?f(a(c,d)):a!=Db&&(a=e(a)?a:document.createTextNode(a),g?g.parentNode.insertBefore(a,g.nextSibling):b?b(a,c,c.parentNode):c.appendChild(a),g=a)}var g;f(d&&!db(a)?mb(a):a)})},fill:function(a){return this.each(function(a){nb(a.childNodes).remove()}).add(a)},addAfter:function(a){return this.add(a,function(a,b,c){c.insertBefore(a,b.nextSibling)})},addBefore:function(a){return this.add(a,function(a,b,c){c.insertBefore(a,b)})},addFront:function(a){return this.add(a,function(a,b){b.insertBefore(a,b.firstChild)})},replace:function(a){return this.add(a,function(a,b,c){c.replaceChild(a,b)})},clone:ab(mb),animate:function(a,b,c){var d,e=sb(),f=this,g=r(rb,this,function(b,d){var e,f=nb(b),g={};return o(e=f.get(a),function(c,e){var h=a[c];g[c]=db(h)?h(e,d,b):"$$slide"==c?ib(f,h):h}),f.dial(e,g,c)}),h=b||500;return e.stop0=function(){return e(!1),d()},d=nb.loop(function(a){O(g,[a/h]),a>=h&&(d(),e(!0,[f]))}),e},dial:function(a,c,d){function e(a,b){return/^#/.test(a)?parseInt(6<a.length?a.substr(2*b+1,2):(a=a.charAt(b+1))+a,16):fb(a.split(",")[b])}var f=this,g=d||0,h=db(g)?g:function(a,b,c){return c*(b-a)*(g+(1-g)*c*(3-2*c))+a};return function(d){o(a,function(a,g){var i=c[a],j=0;f.set(a,0>=d?g:d>=1?i:/^#|rgb\(/.test(i)?"rgb("+Math.round(h(e(g,j),e(i,j++),d))+","+Math.round(h(e(g,j),e(i,j++),d))+","+Math.round(h(e(g,j),e(i,j++),d))+")":l(i,/-?[\d.]+/,b(h(fb(g),fb(i),d))))})}},toggle:function(a,b,c,d){var e,f,g=this,h=!1;return b?(g.set(a),function(i){i!==h&&(f=(h=!0===i||!1===i?i:!h)?b:a,c?(e=g.animate(f,e?e.stop():c,d)).then(function(){e=Db}):g.set(f))}):g.toggle(l(a,/\b(?=\w)/g,"-"),l(a,/\b(?=\w)/g,"+"))},values:function(a){var c=a||{};return this.each(function(a){var d=a.name||a.id,e=b(a.value);if(/form/i.test(a.tagName))for(d=0;d<a.elements.length;d++)nb(a.elements[d]).values(c);else!d||/ox|io/i.test(a.type)&&!a.checked||(c[d]=c[d]==Db?e:r(rb,[c[d],e],j))}),c},offset:function(){for(var a=this[0],b={x:0,y:0};a;)b.x+=a.offsetLeft,b.y+=a.offsetTop,a=a.offsetParent;return b},on:function(a,d,e,f,g){return db(d)?this.on(Db,a,d,e,f):c(f)?this.on(a,d,e,Db,f):this.each(function(c,h){rb(a?ob(a,c):c,function(a){rb(b(d).split(/\s/),function(b){function c(b,c,d){var j,l=!g;if(d=g?d:a,g)for(j=pb(g,a);d&&d!=a&&!(l=j(d));)d=d.parentNode;return!l||i!=b||e.apply(nb(d),f||[c,h])&&"?"==k||"|"==k}function d(a){c(i,a,a.target)||(a.preventDefault(),a.stopPropagation())}var i=l(b,/[?|]/g),k=l(b,/[^?|]/g),m=("blur"==i||"focus"==i)&&!!g,n=zb++;a.addEventListener(i,d,m),a.M||(a.M={}),a.M[n]=c,e.M=r(rb,[e.M,function(){a.removeEventListener(i,d,m),delete a.M[n]}],j)})})})},onOver:function(a,b){var c=this,d=[];return db(b)?this.on(a,"|mouseover |mouseout",function(a,e){var f=a.relatedTarget||a.toElement,g="mouseout"!=a.type;d[e]===g||!g&&f&&(f==c[e]||nb(f).up(c[e]).length)||(d[e]=g,b.call(this,g,a))}):this.onOver(Db,a)},onFocus:function(a,b,c){return db(b)?this.on(a,"|blur",b,[!1],c).on(a,"|focus",b,[!0],c):this.onFocus(Db,a,b)},onChange:function(a,b,c){return db(b)?this.on(a,"|input |change |click",function(a,c){var d=this[0],e=/ox|io/i.test(d.type)?d.checked:d.value;d.NiaP!=e&&b.call(this,d.NiaP=e,c)},c):this.onChange(Db,a,b)},onClick:function(a,b,c,d){return db(b)?this.on(a,"click",b,c,d):this.onClick(Db,a,b,c)},trigger:function(a,b){return this.each(function(c){for(var d=!0,e=c;e&&d;)o(e.M,function(e,f){d=d&&f(a,b,c)}),e=e.parentNode})},per:function(a,b){if(db(a))for(var c=this.length,d=0;c>d;d++)a.call(this,new tb(Db,this[d]),d);else nb(a,this).per(b);return this},ht:function(a,b){var c=2<arguments.length?B(G(arguments,1)):b;return this.set("innerHTML",db(a)?a(c):/{{/.test(a)?_(a,c):/^#\S+$/.test(a)?_(kb(a).text,c):a)}},tb.prototype),A({request:function(a,c,d,e){e=e||{};var f,g=0,h=sb(),i=d&&d.constructor==e.constructor;try{h.xhr=f=new XMLHttpRequest,h.stop0=function(){f.abort()},i&&(d=r(o,d,function(a,b){return r(rb,b,function(b){return encodeURIComponent(a)+(b!=Db?"="+encodeURIComponent(b):"")})}).join("&")),d==Db||/post/i.test(a)||(c+="?"+d,d=Db),f.open(a,c,!0,e.user,e.pass),i&&/post/i.test(a)&&f.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),o(e.headers,function(a,b){f.setRequestHeader(a,b)}),o(e.xhr,function(a,b){f[a]=b}),f.onreadystatechange=function(){4!=f.readyState||g++||(200==f.status?h(!0,[f.responseText,f]):h(!1,[f.status,f.responseText,f]))},f.send(d)}catch(j){g||h(!1,[0,Db,b(j)])}return h},toJSON:JSON.stringify,parseJSON:JSON.parse,ready:jb,loop:function(a){function b(a){o(Bb,function(b,c){c(a)}),Cb&&g(b)}function c(){return Bb[f]&&(delete Bb[f],Cb--),e}var d,e=0,f=zb++,g=wb.requestAnimationFrame||function(a){setTimeout(function(){a(+new Date)},33)};return Bb[f]=function(b){d=d||b,a(e=b-d,c)},Cb++||g(b),c},off:function(a){O(a.M),a.M=Db},setCookie:function(a,b,c,e){document.cookie=a+"="+(e?b:escape(b))+(c?"; expires="+(d(c)?c:new Date(+new Date+864e5*c)).toUTCString():"")},getCookie:function(a,b){var c,d=(c=RegExp("(^|;)\\s*"+a+"=([^;]*)").exec(document.cookie))&&c[2];return b?d:d&&unescape(d)},wait:function(a,b){var c=sb(),d=setTimeout(function(){c(!0,b)},a);return c.stop0=function(){c(!1),clearTimeout(d)},c}},nb),A({filter:cb(q),collect:cb(s),map:cb(v),sub:cb(G),reverse:y,each:p,toObject:z,find:E,findLast:F,contains:L,startsWith:w,endsWith:x,equals:M,call:cb(O),array:H,unite:I,merge:B,uniq:cb(J),intersection:cb(K),keys:cb(u),values:cb(function(a,b){var c=[];return b?p(b,function(b){c.push(a[b])}):o(a,function(a,b){c.push(b)}),c}),copyObj:A,extend:function(a){return B(G(arguments,1),a)},range:function(a,b){for(var c=[],d=b==Db?a:b,e=b!=Db?a:0;d>e;e++)c.push(e);return new tb(c)},bind:P,partial:function(a,b,c){return P(a,this,b,c)},eachObj:o,mapObj:function(a,b,c){var d={};return o(a,function(e,f){d[e]=b.call(c||a,e,f)}),d},filterObj:function(a,b,c){var d={};return o(a,function(e,f){b.call(c||a,e,f)&&(d[e]=f)}),d},isList:eb,isFunction:db,isObject:d,isNumber:f,isBool:h,isDate:g,isValue:i,isString:c,toString:b,dateClone:T,dateAdd:V,dateDiff:W,dateMidnight:function(a){return a=a||new Date,new Date(a.getFullYear(),a.getMonth(),a.getDate())},pad:Q,formatValue:function(a,d){var e,h,i=l(a,/^\?/);return g(d)?((h=/^\[(([+-]\d\d)(\d\d))\]\s*(.*)/.exec(i))&&(e=h[1],d=V(d,"minutes",S(h,2,d)),i=h[4]),l(i,/(\w)(\1*)(?:\[([^\]]+)\])?/g,function(a,b,f,g){return(b=Ib[b])&&(a=d["get"+b[0]](),g=g&&g.split(","),a=eb(b[1])?(g||b[1])[a]:b[1](a,g,e),a==Db||c(a)||(a=Q(f.length+1,a))),a})):E(i.split(/\s*\|\s*/),function(a){var c,e;if(c=/^([<>]?)(=?)([^:]*?)\s*:\s*(.*)$/.exec(a)){if(a=d,e=+c[3],(isNaN(e)||!f(a))&&(a=a==Db?"null":b(a),e=c[3]),c[1]){if(!c[2]&&a==e||"<"==c[1]&&a>e||">"==c[1]&&e>a)return Db}else if(a!=e)return Db;c=c[4]}else c=a;return f(d)?c.replace(/[0#](.*[0#])?/,function(a){var b,c=/^([^.]+)(\.)([^.]+)$/.exec(a)||/^([^,]+)(,)([^,]+)$/.exec(a),e=0>d?"-":"",f=/(\d+)(\.(\d+))?/.exec((e?-d:d).toFixed(c?c[3].length:0));return a=c?c[1]:a,b=c?R(c[3],l(f[3],/0+$/),!0):"",(e?"-":"")+("#"==a?f[1]:R(a,f[1]))+(b.length?c[2]:"")+b}):c})},parseDate:function(a,b){var c,d,e,f,g,h,i,j,k,o={},p=1,q=l(a,/^\?/);if(q!=a&&!n(b))return Db;if((e=/^\[([+-]\d\d)(\d\d)\]\s*(.*)/.exec(q))&&(c=e,q=e[3]),!(e=RegExp(q.replace(/(.)(\1*)(?:\[([^\]]*)\])?/g,function(a,b,c,e){return/[dmhkyhs]/i.test(b)?(o[p++]=b,a=c.length+1,"(\\d"+(2>a?"+":"{1,"+a+"}")+")"):"z"==b?(d=p,p+=2,"([+-]\\d\\d)(\\d\\d)"):/[Nna]/.test(b)?(o[p++]=[b,e&&e.split(",")],"([a-zA-Z\\u0080-\\u1fff]+)"):/w/i.test(b)?"[a-zA-Z\\u0080-\\u1fff]+":/\s/.test(b)?"\\s+":m(a)})).exec(b)))return vb;for(q=[0,0,0,0,0,0,0],f=1;p>f;f++)if(g=e[f],h=o[f],eb(h)){if(i=h[0],j=Jb[i],k=j[0],h=E(h[1]||j[1],function(a,b){return w(g.toLowerCase(),a.toLowerCase())?b:void 0}),h==Db)return vb;q[k]="a"==i?q[k]+12*h:h}else h&&(i=parseFloat(g),j=Jb[h],eb(j)?q[j[0]]+=i-j[1]:q[j]+=i);return q=new Date(q[0],q[1],q[2],q[3],q[4],q[5],q[6]),V(q,"minutes",-S(c,1,q)-S(e,d,q))},parseNumber:function(a,b){var c=l(a,/^\?/);return c==a||n(b)?(c=/(^|[^0#.,])(,|[0#.]*,[0#]+|[0#]+\.[0#]+\.[0#.,]*)($|[^0#.,])/.test(c)?",":".",c=parseFloat(l(l(l(b,","==c?/\./g:/,/g),c,"."),/^[^\d-]*(-?\d)/,"$1")),isNaN(c)?vb:c):Db},trim:n,isEmpty:function(a,b){return a==Db||!a.length||b&&/^\s*$/.test(a)},escapeRegExp:m,escapeHtml:$,format:function(a,b,c){return Z(a,c)(b)},template:Z,formatHtml:_,promise:sb},ub),document.addEventListener("DOMContentLoaded",function(){O(Ab),Ab=Db},!1),{HTML:function(){var a=lb("div");return ub(N(a.ht,a,arguments)[0].childNodes)},_:ub,$:nb,$$:kb,EE:lb,M:tb,getter:yb,setter:xb}});
\ No newline at end of file diff --git a/js/mqttws31.js b/js/mqttws31.js new file mode 100644 index 0000000..d5cf3a7 --- /dev/null +++ b/js/mqttws31.js @@ -0,0 +1,2143 @@ +/******************************************************************************* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * Contributors: + * Andrew Banks - initial API and implementation and initial documentation + *******************************************************************************/ + + +// Only expose a single object name in the global namespace. +// Everything must go through this module. Global Paho.MQTT module +// only has a single public function, client, which returns +// a Paho.MQTT client object given connection details. + +/** + * Send and receive messages using web browsers. + * <p> + * This programming interface lets a JavaScript client application use the MQTT V3.1 or + * V3.1.1 protocol to connect to an MQTT-supporting messaging server. + * + * The function supported includes: + * <ol> + * <li>Connecting to and disconnecting from a server. The server is identified by its host name and port number. + * <li>Specifying options that relate to the communications link with the server, + * for example the frequency of keep-alive heartbeats, and whether SSL/TLS is required. + * <li>Subscribing to and receiving messages from MQTT Topics. + * <li>Publishing messages to MQTT Topics. + * </ol> + * <p> + * The API consists of two main objects: + * <dl> + * <dt><b>{@link Paho.MQTT.Client}</b></dt> + * <dd>This contains methods that provide the functionality of the API, + * including provision of callbacks that notify the application when a message + * arrives from or is delivered to the messaging server, + * or when the status of its connection to the messaging server changes.</dd> + * <dt><b>{@link Paho.MQTT.Message}</b></dt> + * <dd>This encapsulates the payload of the message along with various attributes + * associated with its delivery, in particular the destination to which it has + * been (or is about to be) sent.</dd> + * </dl> + * <p> + * The programming interface validates parameters passed to it, and will throw + * an Error containing an error message intended for developer use, if it detects + * an error with any parameter. + * <p> + * Example: + * + * <code><pre> +client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId"); +client.onConnectionLost = onConnectionLost; +client.onMessageArrived = onMessageArrived; +client.connect({onSuccess:onConnect}); + +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"); + message.destinationName = "/World"; + client.send(message); +}; +function onConnectionLost(responseObject) { + if (responseObject.errorCode !== 0) + console.log("onConnectionLost:"+responseObject.errorMessage); +}; +function onMessageArrived(message) { + console.log("onMessageArrived:"+message.payloadString); + client.disconnect(); +}; + * </pre></code> + * @namespace Paho.MQTT + */ + +if (typeof Paho === "undefined") { + Paho = {}; +} + +Paho.MQTT = (function (global) { + + // Private variables below, these are only visible inside the function closure + // which is used to define the module. + + var version = "1.0.1"; + var buildLevel = "2014-11-18T11:57:44Z"; + + /** + * 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. + + /** + * 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 + * contain erroneous parameters. + * @param {Object} obj - User options object + * @param {Object} keys - valid keys and types that may exist in obj. + * @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 key in keys) + if (keys.hasOwnProperty(key)) + errorStr = errorStr+" "+key; + throw new Error(errorStr); + } + } + } + }; + + /** + * Return a new function which runs the user function bound + * to a fixed scope. + * @param {function} User function + * @param {object} Function scope + * @return {function} User function bound to another scope + * @private + */ + 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}."}, + }; + + /** 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 {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<substitutions.length; i++) { + field = "{"+i+"}"; + start = text.indexOf(field); + if(start > 0) { + var part1 = text.substring(0,start); + var part2 = text.substring(start+field.length); + text = part1+substitutions[i]+part2; + } + } + } + return text; + }; + + //MQTT protocol and version 6 M Q I s d p 3 + var MqttProtoIdentifierv3 = [0x00,0x06,0x4d,0x51,0x49,0x73,0x64,0x70,0x03]; + //MQTT proto/version for 311 4 M Q T T 4 + var MqttProtoIdentifierv4 = [0x00,0x04,0x4d,0x51,0x54,0x54,0x04]; + + /** + * Construct an MQTT wire protocol message. + * @param type MQTT packet type. + * @param options optional wire message attributes. + * + * Optional properties + * + * messageIdentifier: message ID in the range [0..65535] + * payloadMessage: Application Message - PUBLISH only + * connectStrings: array of 0 or more Strings to be put into the CONNECT payload + * topics: array of strings (SUBSCRIBE, UNSUBSCRIBE) + * requestQoS: array of QoS values [0..2] + * + * "Flag" properties + * cleanSession: true if present / false if absent (CONNECT) + * willMessage: true if present / false if absent (CONNECT) + * isRetained: true if present / false if absent (CONNECT) + * userName: true if present / false if absent (CONNECT) + * password: true if present / false if absent (CONNECT) + * keepAliveInterval: integer [0..65535] (CONNECT) + * + * @private + * @ignore + */ + var WireMessage = function (type, options) { + this.type = type; + for (var name in options) { + if (options.hasOwnProperty(name)) { + this[name] = options[name]; + } + } + }; + + WireMessage.prototype.encode = function() { + // Compute the first byte of the fixed header + var first = ((this.type & 0x0f) << 4); + + /* + * Now calculate the length of the variable header + payload by adding up the lengths + * of all the component parts + */ + + var remLength = 0; + var topicStrLength = new Array(); + var destinationNameLength = 0; + + // if the message contains a messageIdentifier then we need two bytes for that + if (this.messageIdentifier != undefined) + remLength += 2; + + switch(this.type) { + // If this a Connect then we need to include 12 bytes for its header + case MESSAGE_TYPE.CONNECT: + switch(this.mqttVersion) { + case 3: + remLength += MqttProtoIdentifierv3.length + 3; + break; + case 4: + remLength += MqttProtoIdentifierv4.length + 3; + break; + } + + remLength += UTF8Length(this.clientId) + 2; + if (this.willMessage != undefined) { + remLength += UTF8Length(this.willMessage.destinationName) + 2; + // Will message is always a string, sent as UTF-8 characters with a preceding length. + var willMessagePayloadBytes = this.willMessage.payloadBytes; + if (!(willMessagePayloadBytes instanceof Uint8Array)) + willMessagePayloadBytes = new Uint8Array(payloadBytes); + remLength += willMessagePayloadBytes.byteLength +2; + } + if (this.userName != undefined) + remLength += UTF8Length(this.userName) + 2; + if (this.password != undefined) + remLength += UTF8Length(this.password) + 2; + break; + + // Subscribe, Unsubscribe can both contain topic strings + case MESSAGE_TYPE.SUBSCRIBE: + first |= 0x02; // Qos = 1; + for ( var i = 0; i < this.topics.length; i++) { + topicStrLength[i] = UTF8Length(this.topics[i]); + remLength += topicStrLength[i] + 2; + } + remLength += this.requestedQos.length; // 1 byte for each topic's Qos + // QoS on Subscribe only + break; + + case MESSAGE_TYPE.UNSUBSCRIBE: + first |= 0x02; // Qos = 1; + for ( var i = 0; i < this.topics.length; i++) { + topicStrLength[i] = UTF8Length(this.topics[i]); + remLength += topicStrLength[i] + 2; + } + break; + + case MESSAGE_TYPE.PUBREL: + first |= 0x02; // Qos = 1; + break; + + case MESSAGE_TYPE.PUBLISH: + if (this.payloadMessage.duplicate) first |= 0x08; + first = first |= (this.payloadMessage.qos << 1); + if (this.payloadMessage.retained) first |= 0x01; + destinationNameLength = UTF8Length(this.payloadMessage.destinationName); + remLength += destinationNameLength + 2; + var payloadBytes = this.payloadMessage.payloadBytes; + remLength += payloadBytes.byteLength; + if (payloadBytes instanceof ArrayBuffer) + payloadBytes = new Uint8Array(payloadBytes); + else if (!(payloadBytes instanceof Uint8Array)) + payloadBytes = new Uint8Array(payloadBytes.buffer); + break; + + case MESSAGE_TYPE.DISCONNECT: + break; + + default: + ; + } + + // Now we can allocate a buffer for the message + + var mbi = encodeMBI(remLength); // Convert the length to MQTT MBI format + var pos = mbi.length + 1; // Offset of start of variable header + var buffer = new ArrayBuffer(remLength + pos); + var byteStream = new Uint8Array(buffer); // view it as a sequence of bytes + + //Write the fixed header into the buffer + byteStream[0] = first; + byteStream.set(mbi,1); + + // If this is a PUBLISH then the variable header starts with a topic + if (this.type == MESSAGE_TYPE.PUBLISH) + pos = writeString(this.payloadMessage.destinationName, destinationNameLength, byteStream, pos); + // If this is a CONNECT then the variable header contains the protocol name/version, flags and keepalive time + + else if (this.type == MESSAGE_TYPE.CONNECT) { + switch (this.mqttVersion) { + case 3: + byteStream.set(MqttProtoIdentifierv3, pos); + pos += MqttProtoIdentifierv3.length; + break; + case 4: + byteStream.set(MqttProtoIdentifierv4, pos); + pos += MqttProtoIdentifierv4.length; + break; + } + var connectFlags = 0; + if (this.cleanSession) + connectFlags = 0x02; + if (this.willMessage != undefined ) { + connectFlags |= 0x04; + connectFlags |= (this.willMessage.qos<<3); + if (this.willMessage.retained) { + connectFlags |= 0x20; + } + } + if (this.userName != undefined) + connectFlags |= 0x80; + if (this.password != undefined) + connectFlags |= 0x40; + byteStream[pos++] = connectFlags; + pos = writeUint16 (this.keepAliveInterval, byteStream, pos); + } + + // Output the messageIdentifier - if there is one + if (this.messageIdentifier != undefined) + pos = writeUint16 (this.messageIdentifier, byteStream, pos); + + switch(this.type) { + case MESSAGE_TYPE.CONNECT: + pos = writeString(this.clientId, UTF8Length(this.clientId), byteStream, pos); + if (this.willMessage != undefined) { + pos = writeString(this.willMessage.destinationName, UTF8Length(this.willMessage.destinationName), byteStream, pos); + pos = writeUint16(willMessagePayloadBytes.byteLength, byteStream, pos); + byteStream.set(willMessagePayloadBytes, pos); + pos += willMessagePayloadBytes.byteLength; + + } + if (this.userName != undefined) + pos = writeString(this.userName, UTF8Length(this.userName), byteStream, pos); + if (this.password != undefined) + pos = writeString(this.password, UTF8Length(this.password), byteStream, pos); + break; + + case MESSAGE_TYPE.PUBLISH: + // PUBLISH has a text or binary payload, if text do not add a 2 byte length field, just the UTF characters. + byteStream.set(payloadBytes, pos); + + break; + +// case MESSAGE_TYPE.PUBREC: +// case MESSAGE_TYPE.PUBREL: +// case MESSAGE_TYPE.PUBCOMP: +// break; + + case MESSAGE_TYPE.SUBSCRIBE: + // SUBSCRIBE has a list of topic strings and request QoS + for (var i=0; i<this.topics.length; i++) { + pos = writeString(this.topics[i], topicStrLength[i], byteStream, pos); + byteStream[pos++] = this.requestedQos[i]; + } + break; + + case MESSAGE_TYPE.UNSUBSCRIBE: + // UNSUBSCRIBE has a list of topic strings + for (var i=0; i<this.topics.length; i++) + pos = writeString(this.topics[i], topicStrLength[i], byteStream, pos); + break; + + default: + // Do nothing. + } + + return buffer; + } + + function decodeMessage(input,pos) { + var startingPos = pos; + var first = input[pos]; + var type = first >> 4; + var messageInfo = first &= 0x0f; + pos += 1; + + + // Decode the remaining length (MBI format) + + var digit; + var remLength = 0; + var multiplier = 1; + do { + if (pos == input.length) { + return [null,startingPos]; + } + digit = input[pos++]; + remLength += ((digit & 0x7F) * multiplier); + multiplier *= 128; + } while ((digit & 0x80) != 0); + + var endPos = pos+remLength; + if (endPos > input.length) { + return [null,startingPos]; + } + + var wireMessage = new WireMessage(type); + switch(type) { + case MESSAGE_TYPE.CONNACK: + var connectAcknowledgeFlags = input[pos++]; + if (connectAcknowledgeFlags & 0x01) + wireMessage.sessionPresent = true; + wireMessage.returnCode = input[pos++]; + break; + + case MESSAGE_TYPE.PUBLISH: + var qos = (messageInfo >> 1) & 0x03; + + var len = readUint16(input, pos); + pos += 2; + var topicName = parseUTF8(input, pos, len); + pos += len; + // If QoS 1 or 2 there will be a messageIdentifier + if (qos > 0) { + wireMessage.messageIdentifier = readUint16(input, pos); + pos += 2; + } + + var message = new Paho.MQTT.Message(input.subarray(pos, endPos)); + if ((messageInfo & 0x01) == 0x01) + message.retained = true; + if ((messageInfo & 0x08) == 0x08) + message.duplicate = true; + message.qos = qos; + message.destinationName = topicName; + wireMessage.payloadMessage = message; + break; + + case MESSAGE_TYPE.PUBACK: + case MESSAGE_TYPE.PUBREC: + case MESSAGE_TYPE.PUBREL: + case MESSAGE_TYPE.PUBCOMP: + case MESSAGE_TYPE.UNSUBACK: + wireMessage.messageIdentifier = readUint16(input, pos); + break; + + case MESSAGE_TYPE.SUBACK: + wireMessage.messageIdentifier = readUint16(input, pos); + pos += 2; + wireMessage.returnCode = input.subarray(pos, endPos); + break; + + default: + ; + } + + return [wireMessage,endPos]; + } + + function writeUint16(input, buffer, offset) { + buffer[offset++] = input >> 8; //MSB + buffer[offset++] = input % 256; //LSB + return offset; + } + + function writeString(input, utf8Length, buffer, offset) { + offset = writeUint16(utf8Length, buffer, offset); + stringToUTF8(input, buffer, offset); + return offset + utf8Length; + } + + function readUint16(buffer, offset) { + return 256*buffer[offset] + buffer[offset+1]; + } + + /** + * Encodes an MQTT Multi-Byte Integer + * @private + */ + function encodeMBI(number) { + var output = new Array(1); + var numBytes = 0; + + do { + var digit = number % 128; + number = number >> 7; + if (number > 0) { + digit |= 0x80; + } + output[numBytes++] = digit; + } while ( (number > 0) && (numBytes<4) ); + + return output; + } + + /** + * Takes a String and calculates its length in bytes when encoded in UTF8. + * @private + */ + function UTF8Length(input) { + var output = 0; + for (var i = 0; i<input.length; i++) + { + var charCode = input.charCodeAt(i); + if (charCode > 0x7FF) + { + // Surrogate pair means its a 4 byte character + if (0xD800 <= charCode && charCode <= 0xDBFF) + { + i++; + output++; + } + output +=3; + } + else if (charCode > 0x7F) + output +=2; + else + output++; + } + return output; + } + + /** + * Takes a String and writes it into an array as UTF8 encoded bytes. + * @private + */ + function stringToUTF8(input, output, start) { + var pos = start; + for (var i = 0; i<input.length; i++) { + var charCode = input.charCodeAt(i); + + // Check for a surrogate pair. + if (0xD800 <= charCode && charCode <= 0xDBFF) { + var lowCharCode = input.charCodeAt(++i); + if (isNaN(lowCharCode)) { + throw new Error(format(ERROR.MALFORMED_UNICODE, [charCode, lowCharCode])); + } + charCode = ((charCode - 0xD800)<<10) + (lowCharCode - 0xDC00) + 0x10000; + + } + + if (charCode <= 0x7F) { + output[pos++] = charCode; + } else if (charCode <= 0x7FF) { + output[pos++] = charCode>>6 & 0x1F | 0xC0; + output[pos++] = charCode & 0x3F | 0x80; + } else if (charCode <= 0xFFFF) { + output[pos++] = charCode>>12 & 0x0F | 0xE0; + output[pos++] = charCode>>6 & 0x3F | 0x80; + output[pos++] = charCode & 0x3F | 0x80; + } else { + output[pos++] = charCode>>18 & 0x07 | 0xF0; + output[pos++] = charCode>>12 & 0x3F | 0x80; + output[pos++] = charCode>>6 & 0x3F | 0x80; + output[pos++] = charCode & 0x3F | 0x80; + }; + } + return output; + } + + function parseUTF8(input, offset, length) { + var output = ""; + var utf16; + var pos = offset; + + while (pos < offset+length) + { + var byte1 = input[pos++]; + if (byte1 < 128) + utf16 = byte1; + else + { + var byte2 = input[pos++]-128; + if (byte2 < 0) + throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16),""])); + if (byte1 < 0xE0) // 2 byte character + utf16 = 64*(byte1-0xC0) + byte2; + else + { + var byte3 = input[pos++]-128; + if (byte3 < 0) + throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16)])); + if (byte1 < 0xF0) // 3 byte character + utf16 = 4096*(byte1-0xE0) + 64*byte2 + byte3; + else + { + var byte4 = input[pos++]-128; + if (byte4 < 0) + throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16), byte4.toString(16)])); + if (byte1 < 0xF8) // 4 byte character + utf16 = 262144*(byte1-0xF0) + 4096*byte2 + 64*byte3 + byte4; + else // longer encodings are not supported + throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16), byte4.toString(16)])); + } + } + } + + if (utf16 > 0xFFFF) // 4 byte character - express as a surrogate pair + { + utf16 -= 0x10000; + output += String.fromCharCode(0xD800 + (utf16 >> 10)); // lead character + utf16 = 0xDC00 + (utf16 & 0x3FF); // trail character + } + output += String.fromCharCode(utf16); + } + return output; + } + + /** + * Repeat keepalive requests, monitor responses. + * @ignore + */ + var Pinger = function(client, window, keepAliveInterval) { + this._client = client; + this._window = window; + this._keepAliveInterval = keepAliveInterval*1000; + this.isReset = false; + + var pingReq = new WireMessage(MESSAGE_TYPE.PINGREQ).encode(); + + var doTimeout = function (pinger) { + return function () { + return doPing.apply(pinger); + }; + }; + + /** @ignore */ + var doPing = function() { + if (!this.isReset) { + this._client._trace("Pinger.doPing", "Timed out"); + this._client._disconnected( ERROR.PING_TIMEOUT.code , format(ERROR.PING_TIMEOUT)); + } else { + this.isReset = false; + this._client._trace("Pinger.doPing", "send PINGREQ"); + this._client.socket.send(pingReq); + this.timeout = this._window.setTimeout(doTimeout(this), this._keepAliveInterval); + } + } + + this.reset = function() { + this.isReset = true; + this._window.clearTimeout(this.timeout); + if (this._keepAliveInterval > 0) + this.timeout = setTimeout(doTimeout(this), this._keepAliveInterval); + } + + this.cancel = function() { + this._window.clearTimeout(this.timeout); + } + }; + + /** + * Monitor request completion. + * @ignore + */ + var Timeout = function(client, window, timeoutSeconds, action, args) { + this._window = window; + if (!timeoutSeconds) + timeoutSeconds = 30; + + var doTimeout = function (action, client, args) { + return function () { + return action.apply(client, args); + }; + }; + this.timeout = setTimeout(doTimeout(action, client, args), timeoutSeconds * 1000); + + this.cancel = function() { + this._window.clearTimeout(this.timeout); + } + }; + + /* + * Internal implementation of the Websockets MQTT V3.1 client. + * + * @name Paho.MQTT.ClientImpl @constructor + * @param {String} host the DNS nameof the webSocket host. + * @param {Number} port the port number for that host. + * @param {String} clientId the MQ client identifier. + */ + var ClientImpl = function (uri, host, port, path, clientId) { + // Check dependencies are satisfied in this browser. + if (!("WebSocket" in global && global["WebSocket"] !== null)) { + throw new Error(format(ERROR.UNSUPPORTED, ["WebSocket"])); + } + if (!("localStorage" in global && global["localStorage"] !== null)) { + throw new Error(format(ERROR.UNSUPPORTED, ["localStorage"])); + } + if (!("ArrayBuffer" in global && global["ArrayBuffer"] !== null)) { + throw new Error(format(ERROR.UNSUPPORTED, ["ArrayBuffer"])); + } + this._trace("Paho.MQTT.Client", uri, host, port, path, clientId); + + this.host = host; + this.port = port; + this.path = path; + this.uri = uri; + this.clientId = clientId; + + // Local storagekeys are qualified with the following string. + // The conditional inclusion of path in the key is for backward + // compatibility to when the path was not configurable and assumed to + // be /mqtt + this._localKey=host+":"+port+(path!="/mqtt"?":"+path:"")+":"+clientId+":"; + + // Create private instance-only message queue + // Internal queue of messages to be sent, in sending order. + this._msg_queue = []; + + // Messages we have sent and are expecting a response for, indexed by their respective message ids. + this._sentMessages = {}; + + // Messages we have received and acknowleged and are expecting a confirm message for + // indexed by their respective message ids. + this._receivedMessages = {}; + + // Internal list of callbacks to be executed when messages + // have been successfully sent over web socket, e.g. disconnect + // when it doesn't have to wait for ACK, just message is dispatched. + this._notify_msg_sent = {}; + + // Unique identifier for SEND messages, incrementing + // counter as messages are sent. + this._message_identifier = 1; + + // Used to determine the transmission sequence of stored sent messages. + this._sequence = 0; + + + // Load the local state, if any, from the saved version, only restore state relevant to this client. + for (var key in localStorage) + if ( key.indexOf("Sent:"+this._localKey) == 0 + || key.indexOf("Received:"+this._localKey) == 0) + this.restore(key); + }; + + // Messaging Client public instance members. + ClientImpl.prototype.host; + ClientImpl.prototype.port; + ClientImpl.prototype.path; + ClientImpl.prototype.uri; + ClientImpl.prototype.clientId; + + // Messaging Client private instance members. + ClientImpl.prototype.socket; + /* true once we have received an acknowledgement to a CONNECT packet. */ + ClientImpl.prototype.connected = false; + /* The largest message identifier allowed, may not be larger than 2**16 but + * if set smaller reduces the maximum number of outbound messages allowed. + */ + ClientImpl.prototype.maxMessageIdentifier = 65536; + ClientImpl.prototype.connectOptions; + ClientImpl.prototype.hostIndex; + ClientImpl.prototype.onConnectionLost; + ClientImpl.prototype.onMessageDelivered; + ClientImpl.prototype.onMessageArrived; + ClientImpl.prototype.traceFunction; + ClientImpl.prototype._msg_queue = null; + ClientImpl.prototype._connectTimeout; + /* The sendPinger monitors how long we allow before we send data to prove to the server that we are alive. */ + ClientImpl.prototype.sendPinger = null; + /* The receivePinger monitors how long we allow before we require evidence that the server is alive. */ + ClientImpl.prototype.receivePinger = null; + + ClientImpl.prototype.receiveBuffer = null; + + ClientImpl.prototype._traceBuffer = null; + ClientImpl.prototype._MAX_TRACE_ENTRIES = 100; + + ClientImpl.prototype.connect = function (connectOptions) { + var connectOptionsMasked = this._traceMask(connectOptions, "password"); + this._trace("Client.connect", connectOptionsMasked, this.socket, this.connected); + + if (this.connected) + throw new Error(format(ERROR.INVALID_STATE, ["already connected"])); + if (this.socket) + throw new Error(format(ERROR.INVALID_STATE, ["already connected"])); + + this.connectOptions = connectOptions; + + if (connectOptions.uris) { + this.hostIndex = 0; + this._doConnect(connectOptions.uris[0]); + } else { + this._doConnect(this.uri); + } + + }; + + ClientImpl.prototype.subscribe = function (filter, subscribeOptions) { + this._trace("Client.subscribe", filter, subscribeOptions); + + if (!this.connected) + throw new Error(format(ERROR.INVALID_STATE, ["not connected"])); + + var wireMessage = new WireMessage(MESSAGE_TYPE.SUBSCRIBE); + wireMessage.topics=[filter]; + if (subscribeOptions.qos != undefined) + wireMessage.requestedQos = [subscribeOptions.qos]; + else + wireMessage.requestedQos = [0]; + + if (subscribeOptions.onSuccess) { + wireMessage.onSuccess = function(grantedQos) {subscribeOptions.onSuccess({invocationContext:subscribeOptions.invocationContext,grantedQos:grantedQos});}; + } + + if (subscribeOptions.onFailure) { + wireMessage.onFailure = function(errorCode) {subscribeOptions.onFailure({invocationContext:subscribeOptions.invocationContext,errorCode:errorCode});}; + } + + if (subscribeOptions.timeout) { + wireMessage.timeOut = new Timeout(this, window, subscribeOptions.timeout, subscribeOptions.onFailure + , [{invocationContext:subscribeOptions.invocationContext, + errorCode:ERROR.SUBSCRIBE_TIMEOUT.code, + errorMessage:format(ERROR.SUBSCRIBE_TIMEOUT)}]); + } + + // All subscriptions return a SUBACK. + this._requires_ack(wireMessage); + this._schedule_message(wireMessage); + }; + + /** @ignore */ + ClientImpl.prototype.unsubscribe = function(filter, unsubscribeOptions) { + this._trace("Client.unsubscribe", filter, unsubscribeOptions); + + if (!this.connected) + throw new Error(format(ERROR.INVALID_STATE, ["not connected"])); + + var wireMessage = new WireMessage(MESSAGE_TYPE.UNSUBSCRIBE); + wireMessage.topics = [filter]; + + if (unsubscribeOptions.onSuccess) { + wireMessage.callback = function() {unsubscribeOptions.onSuccess({invocationContext:unsubscribeOptions.invocationContext});}; + } + if (unsubscribeOptions.timeout) { + wireMessage.timeOut = new Timeout(this, window, unsubscribeOptions.timeout, unsubscribeOptions.onFailure + , [{invocationContext:unsubscribeOptions.invocationContext, + errorCode:ERROR.UNSUBSCRIBE_TIMEOUT.code, + errorMessage:format(ERROR.UNSUBSCRIBE_TIMEOUT)}]); + } + + // All unsubscribes return a SUBACK. + this._requires_ack(wireMessage); + this._schedule_message(wireMessage); + }; + + ClientImpl.prototype.send = function (message) { + this._trace("Client.send", message); + + if (!this.connected) + throw new Error(format(ERROR.INVALID_STATE, ["not connected"])); + + wireMessage = new WireMessage(MESSAGE_TYPE.PUBLISH); + wireMessage.payloadMessage = message; + + if (message.qos > 0) + this._requires_ack(wireMessage); + else if (this.onMessageDelivered) + this._notify_msg_sent[wireMessage] = this.onMessageDelivered(wireMessage.payloadMessage); + this._schedule_message(wireMessage); + }; + + ClientImpl.prototype.disconnect = function () { + this._trace("Client.disconnect"); + + if (!this.socket) + throw new Error(format(ERROR.INVALID_STATE, ["not connecting or connected"])); + + wireMessage = new WireMessage(MESSAGE_TYPE.DISCONNECT); + + // Run the disconnected call back as soon as the message has been sent, + // in case of a failure later on in the disconnect processing. + // as a consequence, the _disconected call back may be run several times. + this._notify_msg_sent[wireMessage] = scope(this._disconnected, this); + + this._schedule_message(wireMessage); + }; + + ClientImpl.prototype.getTraceLog = function () { + if ( this._traceBuffer !== null ) { + this._trace("Client.getTraceLog", new Date()); + this._trace("Client.getTraceLog in flight messages", this._sentMessages.length); + for (var key in this._sentMessages) + this._trace("_sentMessages ",key, this._sentMessages[key]); + for (var key in this._receivedMessages) + this._trace("_receivedMessages ",key, this._receivedMessages[key]); + + return this._traceBuffer; + } + }; + + ClientImpl.prototype.startTrace = function () { + if ( this._traceBuffer === null ) { + this._traceBuffer = []; + } + this._trace("Client.startTrace", new Date(), version); + }; + + ClientImpl.prototype.stopTrace = function () { + delete this._traceBuffer; + }; + + ClientImpl.prototype._doConnect = function (wsurl) { + // When the socket is open, this client will send the CONNECT WireMessage using the saved parameters. + if (this.connectOptions.useSSL) { + var uriParts = wsurl.split(":"); + uriParts[0] = "wss"; + wsurl = uriParts.join(":"); + } + this.connected = false; + if (this.connectOptions.mqttVersion < 4) { + this.socket = new WebSocket(wsurl, ["mqttv3.1"]); + } else { + this.socket = new WebSocket(wsurl, ["mqtt"]); + } + this.socket.binaryType = 'arraybuffer'; + + this.socket.onopen = scope(this._on_socket_open, this); + this.socket.onmessage = scope(this._on_socket_message, this); + this.socket.onerror = scope(this._on_socket_error, this); + this.socket.onclose = scope(this._on_socket_close, this); + + this.sendPinger = new Pinger(this, window, this.connectOptions.keepAliveInterval); + this.receivePinger = new Pinger(this, window, this.connectOptions.keepAliveInterval); + + this._connectTimeout = new Timeout(this, window, this.connectOptions.timeout, this._disconnected, [ERROR.CONNECT_TIMEOUT.code, format(ERROR.CONNECT_TIMEOUT)]); + }; + + + // Schedule a new message to be sent over the WebSockets + // connection. CONNECT messages cause WebSocket connection + // to be started. All other messages are queued internally + // until this has happened. When WS connection starts, process + // all outstanding messages. + ClientImpl.prototype._schedule_message = function (message) { + this._msg_queue.push(message); + // Process outstanding messages in the queue if we have an open socket, and have received CONNACK. + if (this.connected) { + this._process_queue(); + } + }; + + ClientImpl.prototype.store = function(prefix, wireMessage) { + var storedMessage = {type:wireMessage.type, messageIdentifier:wireMessage.messageIdentifier, version:1}; + + switch(wireMessage.type) { + case MESSAGE_TYPE.PUBLISH: + if(wireMessage.pubRecReceived) + storedMessage.pubRecReceived = true; + + // Convert the payload to a hex string. + storedMessage.payloadMessage = {}; + var hex = ""; + var messageBytes = wireMessage.payloadMessage.payloadBytes; + for (var i=0; i<messageBytes.length; i++) { + if (messageBytes[i] <= 0xF) + hex = hex+"0"+messageBytes[i].toString(16); + else + hex = hex+messageBytes[i].toString(16); + } + storedMessage.payloadMessage.payloadHex = hex; + + storedMessage.payloadMessage.qos = wireMessage.payloadMessage.qos; + storedMessage.payloadMessage.destinationName = wireMessage.payloadMessage.destinationName; + if (wireMessage.payloadMessage.duplicate) + storedMessage.payloadMessage.duplicate = true; + if (wireMessage.payloadMessage.retained) + storedMessage.payloadMessage.retained = true; + + // Add a sequence number to sent messages. + if ( prefix.indexOf("Sent:") == 0 ) { + if ( wireMessage.sequence === undefined ) + wireMessage.sequence = ++this._sequence; + storedMessage.sequence = wireMessage.sequence; + } + break; + + default: + throw Error(format(ERROR.INVALID_STORED_DATA, [key, storedMessage])); + } + localStorage.setItem(prefix+this._localKey+wireMessage.messageIdentifier, JSON.stringify(storedMessage)); + }; + + ClientImpl.prototype.restore = function(key) { + var value = localStorage.getItem(key); + var storedMessage = JSON.parse(value); + + var wireMessage = new WireMessage(storedMessage.type, storedMessage); + + switch(storedMessage.type) { + case MESSAGE_TYPE.PUBLISH: + // Replace the payload message with a Message object. + var hex = storedMessage.payloadMessage.payloadHex; + var buffer = new ArrayBuffer((hex.length)/2); + var byteStream = new Uint8Array(buffer); + var i = 0; + while (hex.length >= 2) { + var x = parseInt(hex.substring(0, 2), 16); + hex = hex.substring(2, hex.length); + byteStream[i++] = x; + } + var payloadMessage = new Paho.MQTT.Message(byteStream); + + payloadMessage.qos = storedMessage.payloadMessage.qos; + payloadMessage.destinationName = storedMessage.payloadMessage.destinationName; + if (storedMessage.payloadMessage.duplicate) + payloadMessage.duplicate = true; + if (storedMessage.payloadMessage.retained) + payloadMessage.retained = true; + wireMessage.payloadMessage = payloadMessage; + + break; + + default: + throw Error(format(ERROR.INVALID_STORED_DATA, [key, value])); + } + + if (key.indexOf("Sent:"+this._localKey) == 0) { + wireMessage.payloadMessage.duplicate = true; + this._sentMessages[wireMessage.messageIdentifier] = wireMessage; + } else if (key.indexOf("Received:"+this._localKey) == 0) { + this._receivedMessages[wireMessage.messageIdentifier] = wireMessage; + } + }; + + ClientImpl.prototype._process_queue = function () { + var message = null; + // Process messages in order they were added + var fifo = this._msg_queue.reverse(); + + // Send all queued messages down socket connection + while ((message = fifo.pop())) { + this._socket_send(message); + // Notify listeners that message was successfully sent + if (this._notify_msg_sent[message]) { + this._notify_msg_sent[message](); + delete this._notify_msg_sent[message]; + } + } + }; + + /** + * Expect an ACK response for this message. Add message to the set of in progress + * messages and set an unused identifier in this message. + * @ignore + */ + ClientImpl.prototype._requires_ack = function (wireMessage) { + var messageCount = Object.keys(this._sentMessages).length; + if (messageCount > this.maxMessageIdentifier) + throw Error ("Too many messages:"+messageCount); + + while(this._sentMessages[this._message_identifier] !== undefined) { + this._message_identifier++; + } + wireMessage.messageIdentifier = this._message_identifier; + this._sentMessages[wireMessage.messageIdentifier] = wireMessage; + if (wireMessage.type === MESSAGE_TYPE.PUBLISH) { + this.store("Sent:", wireMessage); + } + if (this._message_identifier === this.maxMessageIdentifier) { + this._message_identifier = 1; + } + }; + + /** + * Called when the underlying websocket has been opened. + * @ignore + */ + ClientImpl.prototype._on_socket_open = function () { + // Create the CONNECT message object. + var wireMessage = new WireMessage(MESSAGE_TYPE.CONNECT, this.connectOptions); + wireMessage.clientId = this.clientId; + this._socket_send(wireMessage); + }; + + /** + * Called when the underlying websocket has received a complete packet. + * @ignore + */ + ClientImpl.prototype._on_socket_message = function (event) { + this._trace("Client._on_socket_message", event.data); + // Reset the receive ping timer, we now have evidence the server is alive. + this.receivePinger.reset(); + var messages = this._deframeMessages(event.data); + for (var i = 0; i < messages.length; i+=1) { + this._handleMessage(messages[i]); + } + } + + ClientImpl.prototype._deframeMessages = function(data) { + var byteArray = new Uint8Array(data); + if (this.receiveBuffer) { + var newData = new Uint8Array(this.receiveBuffer.length+byteArray.length); + newData.set(this.receiveBuffer); + newData.set(byteArray,this.receiveBuffer.length); + byteArray = newData; + delete this.receiveBuffer; + } + try { + var offset = 0; + var messages = []; + while(offset < byteArray.length) { + var result = decodeMessage(byteArray,offset); + var wireMessage = result[0]; + offset = result[1]; + if (wireMessage !== null) { + messages.push(wireMessage); + } else { + break; + } + } + if (offset < byteArray.length) { + this.receiveBuffer = byteArray.subarray(offset); + } + } catch (error) { + this._disconnected(ERROR.INTERNAL_ERROR.code , format(ERROR.INTERNAL_ERROR, [error.message,error.stack.toString()])); + return; + } + return messages; + } + + ClientImpl.prototype._handleMessage = function(wireMessage) { + + this._trace("Client._handleMessage", wireMessage); + + try { + switch(wireMessage.type) { + case MESSAGE_TYPE.CONNACK: + this._connectTimeout.cancel(); + + // If we have started using clean session then clear up the local state. + if (this.connectOptions.cleanSession) { + for (var key in this._sentMessages) { + var sentMessage = this._sentMessages[key]; + localStorage.removeItem("Sent:"+this._localKey+sentMessage.messageIdentifier); + } + this._sentMessages = {}; + + for (var key in this._receivedMessages) { + var receivedMessage = this._receivedMessages[key]; + localStorage.removeItem("Received:"+this._localKey+receivedMessage.messageIdentifier); + } + this._receivedMessages = {}; + } + // Client connected and ready for business. + if (wireMessage.returnCode === 0) { + this.connected = true; + // Jump to the end of the list of uris and stop looking for a good host. + if (this.connectOptions.uris) + this.hostIndex = this.connectOptions.uris.length; + } else { + this._disconnected(ERROR.CONNACK_RETURNCODE.code , format(ERROR.CONNACK_RETURNCODE, [wireMessage.returnCode, CONNACK_RC[wireMessage.returnCode]])); + break; + } + + // Resend messages. + var sequencedMessages = new Array(); + for (var msgId in this._sentMessages) { + if (this._sentMessages.hasOwnProperty(msgId)) + sequencedMessages.push(this._sentMessages[msgId]); + } + + // Sort sentMessages into the original sent order. + var sequencedMessages = sequencedMessages.sort(function(a,b) {return a.sequence - b.sequence;} ); + for (var i=0, len=sequencedMessages.length; i<len; i++) { + var sentMessage = sequencedMessages[i]; + if (sentMessage.type == MESSAGE_TYPE.PUBLISH && sentMessage.pubRecReceived) { + var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {messageIdentifier:sentMessage.messageIdentifier}); + this._schedule_message(pubRelMessage); + } else { + this._schedule_message(sentMessage); + }; + } + + // Execute the connectOptions.onSuccess callback if there is one. + if (this.connectOptions.onSuccess) { + this.connectOptions.onSuccess({invocationContext:this.connectOptions.invocationContext}); + } + + // Process all queued messages now that the connection is established. + this._process_queue(); + break; + + case MESSAGE_TYPE.PUBLISH: + this._receivePublish(wireMessage); + break; + + case MESSAGE_TYPE.PUBACK: + var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; + // If this is a re flow of a PUBACK after we have restarted receivedMessage will not exist. + if (sentMessage) { + delete this._sentMessages[wireMessage.messageIdentifier]; + localStorage.removeItem("Sent:"+this._localKey+wireMessage.messageIdentifier); + if (this.onMessageDelivered) + this.onMessageDelivered(sentMessage.payloadMessage); + } + break; + + case MESSAGE_TYPE.PUBREC: + var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; + // If this is a re flow of a PUBREC after we have restarted receivedMessage will not exist. + if (sentMessage) { + sentMessage.pubRecReceived = true; + var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {messageIdentifier:wireMessage.messageIdentifier}); + this.store("Sent:", sentMessage); + this._schedule_message(pubRelMessage); + } + break; + + case MESSAGE_TYPE.PUBREL: + var receivedMessage = this._receivedMessages[wireMessage.messageIdentifier]; + localStorage.removeItem("Received:"+this._localKey+wireMessage.messageIdentifier); + // If this is a re flow of a PUBREL after we have restarted receivedMessage will not exist. + if (receivedMessage) { + this._receiveMessage(receivedMessage); + delete this._receivedMessages[wireMessage.messageIdentifier]; + } + // Always flow PubComp, we may have previously flowed PubComp but the server lost it and restarted. + var pubCompMessage = new WireMessage(MESSAGE_TYPE.PUBCOMP, {messageIdentifier:wireMessage.messageIdentifier}); + this._schedule_message(pubCompMessage); + break; + + case MESSAGE_TYPE.PUBCOMP: + var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; + delete this._sentMessages[wireMessage.messageIdentifier]; + localStorage.removeItem("Sent:"+this._localKey+wireMessage.messageIdentifier); + if (this.onMessageDelivered) + this.onMessageDelivered(sentMessage.payloadMessage); + break; + + case MESSAGE_TYPE.SUBACK: + var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; + if (sentMessage) { + if(sentMessage.timeOut) + sentMessage.timeOut.cancel(); + wireMessage.returnCode.indexOf = Array.prototype.indexOf; + if (wireMessage.returnCode.indexOf(0x80) !== -1) { + if (sentMessage.onFailure) { + sentMessage.onFailure(wireMessage.returnCode); + } + } else if (sentMessage.onSuccess) { + sentMessage.onSuccess(wireMessage.returnCode); + } + delete this._sentMessages[wireMessage.messageIdentifier]; + } + break; + + case MESSAGE_TYPE.UNSUBACK: + var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; + if (sentMessage) { + if (sentMessage.timeOut) + sentMessage.timeOut.cancel(); + if (sentMessage.callback) { + sentMessage.callback(); + } + delete this._sentMessages[wireMessage.messageIdentifier]; + } + + break; + + case MESSAGE_TYPE.PINGRESP: + /* The sendPinger or receivePinger may have sent a ping, the receivePinger has already been reset. */ + this.sendPinger.reset(); + break; + + case MESSAGE_TYPE.DISCONNECT: + // Clients do not expect to receive disconnect packets. + this._disconnected(ERROR.INVALID_MQTT_MESSAGE_TYPE.code , format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type])); + break; + + default: + this._disconnected(ERROR.INVALID_MQTT_MESSAGE_TYPE.code , format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type])); + }; + } catch (error) { + this._disconnected(ERROR.INTERNAL_ERROR.code , format(ERROR.INTERNAL_ERROR, [error.message,error.stack.toString()])); + return; + } + }; + + /** @ignore */ + ClientImpl.prototype._on_socket_error = function (error) { + this._disconnected(ERROR.SOCKET_ERROR.code , format(ERROR.SOCKET_ERROR, [error.data])); + }; + + /** @ignore */ + ClientImpl.prototype._on_socket_close = function () { + this._disconnected(ERROR.SOCKET_CLOSE.code , format(ERROR.SOCKET_CLOSE)); + }; + + /** @ignore */ + ClientImpl.prototype._socket_send = function (wireMessage) { + + if (wireMessage.type == 1) { + var wireMessageMasked = this._traceMask(wireMessage, "password"); + this._trace("Client._socket_send", wireMessageMasked); + } + else this._trace("Client._socket_send", wireMessage); + + this.socket.send(wireMessage.encode()); + /* We have proved to the server we are alive. */ + this.sendPinger.reset(); + }; + + /** @ignore */ + ClientImpl.prototype._receivePublish = function (wireMessage) { + switch(wireMessage.payloadMessage.qos) { + case "undefined": + case 0: + this._receiveMessage(wireMessage); + break; + + case 1: + var pubAckMessage = new WireMessage(MESSAGE_TYPE.PUBACK, {messageIdentifier:wireMessage.messageIdentifier}); + this._schedule_message(pubAckMessage); + this._receiveMessage(wireMessage); + break; + + case 2: + this._receivedMessages[wireMessage.messageIdentifier] = wireMessage; + this.store("Received:", wireMessage); + var pubRecMessage = new WireMessage(MESSAGE_TYPE.PUBREC, {messageIdentifier:wireMessage.messageIdentifier}); + this._schedule_message(pubRecMessage); + + break; + + default: + throw Error("Invaild qos="+wireMmessage.payloadMessage.qos); + }; + }; + + /** @ignore */ + ClientImpl.prototype._receiveMessage = function (wireMessage) { + if (this.onMessageArrived) { + this.onMessageArrived(wireMessage.payloadMessage); + } + }; + + /** + * Client has disconnected either at its own request or because the server + * or network disconnected it. Remove all non-durable state. + * @param {errorCode} [number] the error number. + * @param {errorText} [string] the error text. + * @ignore + */ + ClientImpl.prototype._disconnected = function (errorCode, errorText) { + this._trace("Client._disconnected", errorCode, errorText); + + this.sendPinger.cancel(); + this.receivePinger.cancel(); + if (this._connectTimeout) + this._connectTimeout.cancel(); + // Clear message buffers. + this._msg_queue = []; + this._notify_msg_sent = {}; + + if (this.socket) { + // Cancel all socket callbacks so that they cannot be driven again by this socket. + this.socket.onopen = null; + this.socket.onmessage = null; + this.socket.onerror = null; + this.socket.onclose = null; + if (this.socket.readyState === 1) + this.socket.close(); + delete this.socket; + } + + if (this.connectOptions.uris && this.hostIndex < this.connectOptions.uris.length-1) { + // Try the next host. + this.hostIndex++; + this._doConnect(this.connectOptions.uris[this.hostIndex]); + + } else { + + if (errorCode === undefined) { + errorCode = ERROR.OK.code; + errorText = format(ERROR.OK); + } + + // Run any application callbacks last as they may attempt to reconnect and hence create a new socket. + if (this.connected) { + this.connected = false; + // Execute the connectionLostCallback if there is one, and we were connected. + if (this.onConnectionLost) + this.onConnectionLost({errorCode:errorCode, errorMessage:errorText}); + } else { + // Otherwise we never had a connection, so indicate that the connect has failed. + if (this.connectOptions.mqttVersion === 4 && this.connectOptions.mqttVersionExplicit === false) { + this._trace("Failed to connect V4, dropping back to V3") + this.connectOptions.mqttVersion = 3; + if (this.connectOptions.uris) { + this.hostIndex = 0; + this._doConnect(this.connectOptions.uris[0]); + } else { + this._doConnect(this.uri); + } + } else if(this.connectOptions.onFailure) { + this.connectOptions.onFailure({invocationContext:this.connectOptions.invocationContext, errorCode:errorCode, errorMessage:errorText}); + } + } + } + }; + + /** @ignore */ + ClientImpl.prototype._trace = function () { + // Pass trace message back to client's callback function + if (this.traceFunction) { + for (var i in arguments) + { + if (typeof arguments[i] !== "undefined") + arguments[i] = JSON.stringify(arguments[i]); + } + var record = Array.prototype.slice.call(arguments).join(""); + this.traceFunction ({severity: "Debug", message: record }); + } + + //buffer style trace + if ( this._traceBuffer !== null ) { + for (var i = 0, max = arguments.length; i < max; i++) { + if ( this._traceBuffer.length == this._MAX_TRACE_ENTRIES ) { + this._traceBuffer.shift(); + } + if (i === 0) this._traceBuffer.push(arguments[i]); + else if (typeof arguments[i] === "undefined" ) this._traceBuffer.push(arguments[i]); + else this._traceBuffer.push(" "+JSON.stringify(arguments[i])); + }; + }; + }; + + /** @ignore */ + ClientImpl.prototype._traceMask = function (traceObject, masked) { + var traceObjectMasked = {}; + for (var attr in traceObject) { + if (traceObject.hasOwnProperty(attr)) { + if (attr == masked) + traceObjectMasked[attr] = "******"; + else + traceObjectMasked[attr] = traceObject[attr]; + } + } + return traceObjectMasked; + }; + + // ------------------------------------------------------------------------ + // Public Programming interface. + // ------------------------------------------------------------------------ + + /** + * The JavaScript application communicates to the server using a {@link Paho.MQTT.Client} object. + * <p> + * Most applications will create just one Client object and then call its connect() method, + * however applications can create more than one Client object if they wish. + * In this case the combination of host, port and clientId attributes must be different for each Client object. + * <p> + * The send, subscribe and unsubscribe methods are implemented as asynchronous JavaScript methods + * (even though the underlying protocol exchange might be synchronous in nature). + * This means they signal their completion by calling back to the application, + * via Success or Failure callback functions provided by the application on the method in question. + * Such callbacks are called at most once per method invocation and do not persist beyond the lifetime + * of the script that made the invocation. + * <p> + * In contrast there are some callback functions, most notably <i>onMessageArrived</i>, + * that are defined on the {@link Paho.MQTT.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 + * + * @constructor + * + * @param {string} host - the address of the messaging server, as a fully qualified WebSocket URI, as a DNS name or dotted decimal IP address. + * @param {number} port - the port number to connect to - only required if host is not a URI + * @param {string} path - the path on the host to connect to - only used if host is not a URI. Default: '/mqtt'. + * @param {string} clientId - the Messaging client identifier, between 1 and 23 characters in length. + * + * @property {string} host - <i>read only</i> the server's DNS hostname or dotted decimal IP address. + * @property {number} port - <i>read only</i> the server's port. + * @property {string} path - <i>read only</i> the server's path. + * @property {string} clientId - <i>read only</i> used when connecting to the server. + * @property {function} onConnectionLost - called when a connection has been lost. + * after a connect() method has succeeded. + * Establish the call back used when a connection has been lost. The connection may be + * lost because the client initiates a disconnect or because the server or network + * cause the client to be disconnected. The disconnect call back may be called without + * the connectionComplete call back being invoked if, for example the client fails to + * connect. + * A single response object parameter is passed to the onConnectionLost callback containing the following fields: + * <ol> + * <li>errorCode + * <li>errorMessage + * </ol> + * @property {function} onMessageDelivered called when a message has been delivered. + * All processing that this Client will ever do has been completed. So, for example, + * in the case of a Qos=2 message sent by this client, the PubComp flow has been received from the server + * and the message has been removed from persistent storage before this callback is invoked. + * Parameters passed to the onMessageDelivered callback are: + * <ol> + * <li>{@link Paho.MQTT.Message} that was delivered. + * </ol> + * @property {function} onMessageArrived called when a message has arrived in this Paho.MQTT.client. + * Parameters passed to the onMessageArrived callback are: + * <ol> + * <li>{@link Paho.MQTT.Message} that has arrived. + * </ol> + */ + var Client = function (host, port, path, clientId) { + + var uri; + + if (typeof host !== "string") + throw new Error(format(ERROR.INVALID_TYPE, [typeof host, "host"])); + + if (arguments.length == 2) { + // host: must be full ws:// uri + // port: clientId + clientId = port; + uri = host; + var match = uri.match(/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/); + if (match) { + host = match[4]||match[2]; + port = parseInt(match[7]); + path = match[8]; + } else { + throw new Error(format(ERROR.INVALID_ARGUMENT,[host,"host"])); + } + } else { + if (arguments.length == 3) { + clientId = path; + path = "/mqtt"; + } + if (typeof port !== "number" || port < 0) + throw new Error(format(ERROR.INVALID_TYPE, [typeof port, "port"])); + if (typeof path !== "string") + throw new Error(format(ERROR.INVALID_TYPE, [typeof path, "path"])); + + var ipv6AddSBracket = (host.indexOf(":") != -1 && host.slice(0,1) != "[" && host.slice(-1) != "]"); + uri = "ws://"+(ipv6AddSBracket?"["+host+"]":host)+":"+port+path; + } + + var clientIdLength = 0; + for (var i = 0; i<clientId.length; i++) { + var charCode = clientId.charCodeAt(i); + if (0xD800 <= charCode && charCode <= 0xDBFF) { + i++; // Surrogate pair. + } + clientIdLength++; + } + if (typeof clientId !== "string" || clientIdLength > 65535) + throw new Error(format(ERROR.INVALID_ARGUMENT, [clientId, "clientId"])); + + var client = new ClientImpl(uri, host, port, path, clientId); + this._getHost = function() { return host; }; + this._setHost = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; + + this._getPort = function() { return port; }; + this._setPort = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; + + this._getPath = function() { return path; }; + this._setPath = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; + + this._getURI = function() { return uri; }; + this._setURI = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; + + this._getClientId = function() { return client.clientId; }; + this._setClientId = function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }; + + this._getOnConnectionLost = function() { return client.onConnectionLost; }; + this._setOnConnectionLost = function(newOnConnectionLost) { + if (typeof newOnConnectionLost === "function") + client.onConnectionLost = newOnConnectionLost; + else + throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnConnectionLost, "onConnectionLost"])); + }; + + this._getOnMessageDelivered = function() { return client.onMessageDelivered; }; + this._setOnMessageDelivered = function(newOnMessageDelivered) { + if (typeof newOnMessageDelivered === "function") + client.onMessageDelivered = newOnMessageDelivered; + else + throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnMessageDelivered, "onMessageDelivered"])); + }; + + this._getOnMessageArrived = function() { return client.onMessageArrived; }; + this._setOnMessageArrived = function(newOnMessageArrived) { + if (typeof newOnMessageArrived === "function") + client.onMessageArrived = newOnMessageArrived; + else + throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnMessageArrived, "onMessageArrived"])); + }; + + this._getTrace = function() { return client.traceFunction; }; + this._setTrace = function(trace) { + if(typeof trace === "function"){ + client.traceFunction = trace; + }else{ + throw new Error(format(ERROR.INVALID_TYPE, [typeof trace, "onTrace"])); + } + }; + + /** + * Connect this Messaging client to its server. + * + * @name Paho.MQTT.Client#connect + * @function + * @param {Object} connectOptions - attributes used with the connection. + * @param {number} connectOptions.timeout - If the connect has not succeeded within this + * number of seconds, it is deemed to have failed. + * The default is 30 seconds. + * @param {string} connectOptions.userName - Authentication username for this connection. + * @param {string} connectOptions.password - Authentication password for this connection. + * @param {Paho.MQTT.Message} connectOptions.willMessage - sent by the server when the client + * disconnects abnormally. + * @param {Number} connectOptions.keepAliveInterval - the server disconnects this client if + * there is no activity for this number of seconds. + * The default value of 60 seconds is assumed if not set. + * @param {boolean} connectOptions.cleanSession - if true(default) the client and server + * persistent state is deleted on successful connect. + * @param {boolean} connectOptions.useSSL - if present and true, use an SSL Websocket connection. + * @param {object} connectOptions.invocationContext - passed to the onSuccess callback or onFailure callback. + * @param {function} connectOptions.onSuccess - called when the connect acknowledgement + * has been received from the server. + * A single response object parameter is passed to the onSuccess callback containing the following fields: + * <ol> + * <li>invocationContext as passed in to the onSuccess method in the connectOptions. + * </ol> + * @config {function} [onFailure] called when the connect request has failed or timed out. + * A single response object parameter is passed to the onFailure callback containing the following fields: + * <ol> + * <li>invocationContext as passed in to the onFailure method in the connectOptions. + * <li>errorCode a number indicating the nature of the error. + * <li>errorMessage text describing the error. + * </ol> + * @config {Array} [hosts] If present this contains either a set of hostnames or fully qualified + * WebSocket URIs (ws://example.com:1883/mqtt), that are tried in order in place + * of the host and port paramater on the construtor. The hosts are tried one at at time in order until + * one of then succeeds. + * @config {Array} [ports] If present the set of ports matching the hosts. If hosts contains URIs, this property + * is not used. + * @throws {InvalidState} if the client is not in disconnected state. The client must have received connectionLost + * or disconnected before calling connect for a second or subsequent time. + */ + this.connect = function (connectOptions) { + connectOptions = connectOptions || {} ; + validate(connectOptions, {timeout:"number", + userName:"string", + password:"string", + willMessage:"object", + keepAliveInterval:"number", + cleanSession:"boolean", + useSSL:"boolean", + invocationContext:"object", + onSuccess:"function", + onFailure:"function", + hosts:"object", + ports:"object", + mqttVersion:"number"}); + + // If no keep alive interval is set, assume 60 seconds. + if (connectOptions.keepAliveInterval === undefined) + connectOptions.keepAliveInterval = 60; + + if (connectOptions.mqttVersion > 4 || connectOptions.mqttVersion < 3) { + throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.mqttVersion, "connectOptions.mqttVersion"])); + } + + if (connectOptions.mqttVersion === undefined) { + connectOptions.mqttVersionExplicit = false; + connectOptions.mqttVersion = 4; + } else { + connectOptions.mqttVersionExplicit = true; + } + + //Check that if password is set, so is username + if (connectOptions.password === undefined && connectOptions.userName !== undefined) + throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.password, "connectOptions.password"])) + + if (connectOptions.willMessage) { + if (!(connectOptions.willMessage instanceof Message)) + throw new Error(format(ERROR.INVALID_TYPE, [connectOptions.willMessage, "connectOptions.willMessage"])); + // The will message must have a payload that can be represented as a string. + // Cause the willMessage to throw an exception if this is not the case. + connectOptions.willMessage.stringPayload; + + if (typeof connectOptions.willMessage.destinationName === "undefined") + throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.willMessage.destinationName, "connectOptions.willMessage.destinationName"])); + } + if (typeof connectOptions.cleanSession === "undefined") + connectOptions.cleanSession = true; + if (connectOptions.hosts) { + + if (!(connectOptions.hosts instanceof Array) ) + throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts, "connectOptions.hosts"])); + if (connectOptions.hosts.length <1 ) + throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts, "connectOptions.hosts"])); + + var usingURIs = false; + for (var i = 0; i<connectOptions.hosts.length; i++) { + if (typeof connectOptions.hosts[i] !== "string") + throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.hosts[i], "connectOptions.hosts["+i+"]"])); + if (/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/.test(connectOptions.hosts[i])) { + if (i == 0) { + usingURIs = true; + } else if (!usingURIs) { + throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts[i], "connectOptions.hosts["+i+"]"])); + } + } else if (usingURIs) { + throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts[i], "connectOptions.hosts["+i+"]"])); + } + } + + if (!usingURIs) { + if (!connectOptions.ports) + throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"])); + if (!(connectOptions.ports instanceof Array) ) + throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"])); + if (connectOptions.hosts.length != connectOptions.ports.length) + throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"])); + + connectOptions.uris = []; + + for (var i = 0; i<connectOptions.hosts.length; i++) { + if (typeof connectOptions.ports[i] !== "number" || connectOptions.ports[i] < 0) + throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.ports[i], "connectOptions.ports["+i+"]"])); + var host = connectOptions.hosts[i]; + var port = connectOptions.ports[i]; + + var ipv6 = (host.indexOf(":") != -1); + uri = "ws://"+(ipv6?"["+host+"]":host)+":"+port+path; + connectOptions.uris.push(uri); + } + } else { + connectOptions.uris = connectOptions.hosts; + } + } + + client.connect(connectOptions); + }; + + /** + * Subscribe for messages, request receipt of a copy of messages sent to the destinations described by the filter. + * + * @name Paho.MQTT.Client#subscribe + * @function + * @param {string} filter describing the destinations to receive messages from. + * <br> + * @param {object} subscribeOptions - used to control the subscription + * + * @param {number} subscribeOptions.qos - the maiximum qos of any publications sent + * as a result of making this subscription. + * @param {object} subscribeOptions.invocationContext - passed to the onSuccess callback + * or onFailure callback. + * @param {function} subscribeOptions.onSuccess - called when the subscribe acknowledgement + * has been received from the server. + * A single response object parameter is passed to the onSuccess callback containing the following fields: + * <ol> + * <li>invocationContext if set in the subscribeOptions. + * </ol> + * @param {function} subscribeOptions.onFailure - called when the subscribe request has failed or timed out. + * A single response object parameter is passed to the onFailure callback containing the following fields: + * <ol> + * <li>invocationContext - if set in the subscribeOptions. + * <li>errorCode - a number indicating the nature of the error. + * <li>errorMessage - text describing the error. + * </ol> + * @param {number} subscribeOptions.timeout - which, if present, determines the number of + * seconds after which the onFailure calback is called. + * The presence of a timeout does not prevent the onSuccess + * callback from being called when the subscribe completes. + * @throws {InvalidState} if the client is not in connected state. + */ + this.subscribe = function (filter, subscribeOptions) { + if (typeof filter !== "string") + throw new Error("Invalid argument:"+filter); + subscribeOptions = subscribeOptions || {} ; + validate(subscribeOptions, {qos:"number", + invocationContext:"object", + onSuccess:"function", + onFailure:"function", + timeout:"number" + }); + if (subscribeOptions.timeout && !subscribeOptions.onFailure) + throw new Error("subscribeOptions.timeout specified with no onFailure callback."); + if (typeof subscribeOptions.qos !== "undefined" + && !(subscribeOptions.qos === 0 || subscribeOptions.qos === 1 || subscribeOptions.qos === 2 )) + throw new Error(format(ERROR.INVALID_ARGUMENT, [subscribeOptions.qos, "subscribeOptions.qos"])); + client.subscribe(filter, subscribeOptions); + }; + + /** + * Unsubscribe for messages, stop receiving messages sent to destinations described by the filter. + * + * @name Paho.MQTT.Client#unsubscribe + * @function + * @param {string} filter - describing the destinations to receive messages from. + * @param {object} unsubscribeOptions - used to control the subscription + * @param {object} unsubscribeOptions.invocationContext - passed to the onSuccess callback + or onFailure callback. + * @param {function} unsubscribeOptions.onSuccess - called when the unsubscribe acknowledgement has been received from the server. + * A single response object parameter is passed to the + * onSuccess callback containing the following fields: + * <ol> + * <li>invocationContext - if set in the unsubscribeOptions. + * </ol> + * @param {function} unsubscribeOptions.onFailure called when the unsubscribe request has failed or timed out. + * A single response object parameter is passed to the onFailure callback containing the following fields: + * <ol> + * <li>invocationContext - if set in the unsubscribeOptions. + * <li>errorCode - a number indicating the nature of the error. + * <li>errorMessage - text describing the error. + * </ol> + * @param {number} unsubscribeOptions.timeout - which, if present, determines the number of seconds + * after which the onFailure callback is called. The presence of + * a timeout does not prevent the onSuccess callback from being + * called when the unsubscribe completes + * @throws {InvalidState} if the client is not in connected state. + */ + this.unsubscribe = function (filter, unsubscribeOptions) { + if (typeof filter !== "string") + throw new Error("Invalid argument:"+filter); + unsubscribeOptions = unsubscribeOptions || {} ; + validate(unsubscribeOptions, {invocationContext:"object", + onSuccess:"function", + onFailure:"function", + timeout:"number" + }); + if (unsubscribeOptions.timeout && !unsubscribeOptions.onFailure) + throw new Error("unsubscribeOptions.timeout specified with no onFailure callback."); + client.unsubscribe(filter, unsubscribeOptions); + }; + + /** + * Send a message to the consumers of the destination in the Message. + * + * @name Paho.MQTT.Client#send + * @function + * @param {string|Paho.MQTT.Message} topic - <b>mandatory</b> The name of the destination to which the message is to be sent. + * - If it is the only parameter, used as Paho.MQTT.Message object. + * @param {String|ArrayBuffer} payload - The message data to be sent. + * @param {number} qos The Quality of Service used to deliver the message. + * <dl> + * <dt>0 Best effort (default). + * <dt>1 At least once. + * <dt>2 Exactly once. + * </dl> + * @param {Boolean} retained If true, the message is to be retained by the server and delivered + * to both current and future subscriptions. + * If false the server only delivers the message to current subscribers, this is the default for new Messages. + * A received message has the retained boolean set to true if the message was published + * with the retained boolean set to true + * and the subscrption was made after the message has been published. + * @throws {InvalidState} if the client is not connected. + */ + this.send = function (topic,payload,qos,retained) { + var message ; + + if(arguments.length == 0){ + throw new Error("Invalid argument."+"length"); + + }else if(arguments.length == 1) { + + if (!(topic instanceof Message) && (typeof topic !== "string")) + throw new Error("Invalid argument:"+ typeof topic); + + message = topic; + if (typeof message.destinationName === "undefined") + throw new Error(format(ERROR.INVALID_ARGUMENT,[message.destinationName,"Message.destinationName"])); + client.send(message); + + }else { + //parameter checking in Message object + message = new Message(payload); + message.destinationName = topic; + if(arguments.length >= 3) + message.qos = qos; + if(arguments.length >= 4) + message.retained = retained; + client.send(message); + } + }; + + /** + * Normal disconnect of this Messaging client from its server. + * + * @name Paho.MQTT.Client#disconnect + * @function + * @throws {InvalidState} if the client is already disconnected. + */ + this.disconnect = function () { + client.disconnect(); + }; + + /** + * Get the contents of the trace log. + * + * @name Paho.MQTT.Client#getTraceLog + * @function + * @return {Object[]} tracebuffer containing the time ordered trace records. + */ + this.getTraceLog = function () { + return client.getTraceLog(); + } + + /** + * Start tracing. + * + * @name Paho.MQTT.Client#startTrace + * @function + */ + this.startTrace = function () { + client.startTrace(); + }; + + /** + * Stop tracing. + * + * @name Paho.MQTT.Client#stopTrace + * @function + */ + this.stopTrace = function () { + client.stopTrace(); + }; + + this.isConnected = function() { + return client.connected; + }; + }; + + Client.prototype = { + get host() { return this._getHost(); }, + set host(newHost) { this._setHost(newHost); }, + + get port() { return this._getPort(); }, + set port(newPort) { this._setPort(newPort); }, + + get path() { return this._getPath(); }, + set path(newPath) { this._setPath(newPath); }, + + get clientId() { return this._getClientId(); }, + set clientId(newClientId) { this._setClientId(newClientId); }, + + get onConnectionLost() { return this._getOnConnectionLost(); }, + set onConnectionLost(newOnConnectionLost) { this._setOnConnectionLost(newOnConnectionLost); }, + + get onMessageDelivered() { return this._getOnMessageDelivered(); }, + set onMessageDelivered(newOnMessageDelivered) { this._setOnMessageDelivered(newOnMessageDelivered); }, + + get onMessageArrived() { return this._getOnMessageArrived(); }, + set onMessageArrived(newOnMessageArrived) { this._setOnMessageArrived(newOnMessageArrived); }, + + get trace() { return this._getTrace(); }, + set trace(newTraceFunction) { this._setTrace(newTraceFunction); } + + }; + + /** + * An application message, sent or received. + * <p> + * All attributes may be null, which implies the default values. + * + * @name Paho.MQTT.Message + * @constructor + * @param {String|ArrayBuffer} payload The message data to be sent. + * <p> + * @property {string} payloadString <i>read only</i> The payload as a string if the payload consists of valid UTF-8 characters. + * @property {ArrayBuffer} payloadBytes <i>read only</i> The payload as an ArrayBuffer. + * <p> + * @property {string} destinationName <b>mandatory</b> The name of the destination to which the message is to be sent + * (for messages about to be sent) or the name of the destination from which the message has been received. + * (for messages received by the onMessage function). + * <p> + * @property {number} qos The Quality of Service used to deliver the message. + * <dl> + * <dt>0 Best effort (default). + * <dt>1 At least once. + * <dt>2 Exactly once. + * </dl> + * <p> + * @property {Boolean} retained If true, the message is to be retained by the server and delivered + * to both current and future subscriptions. + * If false the server only delivers the message to current subscribers, this is the default for new Messages. + * A received message has the retained boolean set to true if the message was published + * with the retained boolean set to true + * and the subscrption was made after the message has been published. + * <p> + * @property {Boolean} duplicate <i>read only</i> If true, this message might be a duplicate of one which has already been received. + * This is only set on messages received from the server. + * + */ + 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; + } else { + return payload; + }; + }; + + var destinationName = undefined; + 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 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"])); + }; + + 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 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); diff --git a/js/sortable.js b/js/sortable.js new file mode 100644 index 0000000..617e090 --- /dev/null +++ b/js/sortable.js @@ -0,0 +1,319 @@ +/* +Table sorting script by Joost de Valk, check it out at http://www.joostdevalk.nl/code/sortable-table/. +Based on a script from http://www.kryogenix.org/code/browser/sorttable/. +Distributed under the MIT license: http://www.kryogenix.org/code/browser/licence.html . + +Copyright (c) 1997-2007 Stuart Langridge, Joost de Valk. + +Version 1.5.7 +*/ + +/* You can change these values */ +var europeandate = true; +var alternate_row_colors = true; + +/* Don't change anything below this unless you know what you're doing */ +addEvent(window, "load", sortables_init); + +var SORT_COLUMN_INDEX; +var thead = false; + +function sortables_init() { + // Find all tables with class sortable and make them sortable + if (!document.getElementsByTagName) return; + tbls = document.getElementsByTagName("table"); + for (ti=0;ti<tbls.length;ti++) { + thisTbl = tbls[ti]; + if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) { + ts_makeSortable(thisTbl); + } + } +} + +function ts_makeSortable(t) { + if (t.rows && t.rows.length > 0) { + if (t.tHead && t.tHead.rows.length > 0) { + var firstRow = t.tHead.rows[t.tHead.rows.length-1]; + thead = true; + } else { + var firstRow = t.rows[0]; + } + } + if (!firstRow) return; + + // We have a first row: assume it's the header, and make its contents clickable links + for (var i=0;i<firstRow.cells.length;i++) { + var cell = firstRow.cells[i]; + var txt = ts_getInnerText(cell); + if (cell.className != "unsortable" && cell.className.indexOf("unsortable") == -1) { + cell.innerHTML = '<a href="#" class="sortheader" onclick="ts_resortTable(this, '+i+');return false;">'+txt+'<span class="sortarrow"> ↓</span></a>'; + } + } + if (alternate_row_colors) { + alternate(t); + } +} + +function ts_getInnerText(el) { + if (typeof el == "string") return el; + if (typeof el == "undefined") { return el }; + if (el.innerText) return el.innerText; //Not needed but it is faster + var str = ""; + + var cs = el.childNodes; + var l = cs.length; + for (var i = 0; i < l; i++) { + switch (cs[i].nodeType) { + case 1: //ELEMENT_NODE + str += ts_getInnerText(cs[i]); + break; + case 3: //TEXT_NODE + str += cs[i].nodeValue; + break; + } + } + return str; +} + +function ts_resortTable(lnk, clid) { + var span; + for (var ci=0;ci<lnk.childNodes.length;ci++) { + if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci]; + } + var spantext = ts_getInnerText(span); + var td = lnk.parentNode; + var column = clid || td.cellIndex; + var t = getParent(td,'TABLE'); + // Work out a type for the column + if (t.rows.length <= 1) return; + var itm = ""; + var i = 0; + while (itm == "" && i < t.tBodies[0].rows.length) { + var itm = ts_getInnerText(t.tBodies[0].rows[i].cells[column]); + itm = trim(itm); + if (itm.substr(0,4) == "<!--" || itm.length == 0) { + itm = ""; + } + i++; + } + if (itm == "") return; + sortfn = ts_sort_caseinsensitive; + if (itm.match(/^\d\d[\/\.-][a-zA-z][a-zA-Z][a-zA-Z][\/\.-]\d\d\d\d$/)) sortfn = ts_sort_date; + if (itm.match(/^\d\d[\/\.-]\d\d[\/\.-]\d\d\d{2}?$/)) sortfn = ts_sort_date; + if (itm.match(/^-?[£$€Û¢´]\d/)) sortfn = ts_sort_numeric; + if (itm.match(/^-?(\d+[,\.]?)+(E[-+][\d]+)?%?$/)) sortfn = ts_sort_numeric; + SORT_COLUMN_INDEX = column; + var firstRow = new Array(); + var newRows = new Array(); + for (k=0;k<t.tBodies.length;k++) { + for (i=0;i<t.tBodies[k].rows[0].length;i++) { + firstRow[i] = t.tBodies[k].rows[0][i]; + } + } + for (k=0;k<t.tBodies.length;k++) { + if (!thead) { + // Skip the first row + for (j=1;j<t.tBodies[k].rows.length;j++) { + newRows[j-1] = t.tBodies[k].rows[j]; + } + } else { + // Do NOT skip the first row + for (j=0;j<t.tBodies[k].rows.length;j++) { + newRows[j] = t.tBodies[k].rows[j]; + } + } + } + newRows.sort(sortfn); + if (span.getAttribute("sortdir") == 'down') { + ARROW = ' &darr'; + newRows.reverse(); + span.setAttribute('sortdir','up'); + } else { + ARROW = ' ↑'; + span.setAttribute('sortdir','down'); + } + // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones + // don't do sortbottom rows + for (i=0; i<newRows.length; i++) { + if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) { + t.tBodies[0].appendChild(newRows[i]); + } + } + // do sortbottom rows only + for (i=0; i<newRows.length; i++) { + if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) + t.tBodies[0].appendChild(newRows[i]); + } + // Delete any other arrows there may be showing + var allspans = document.getElementsByTagName("span"); + for (var ci=0;ci<allspans.length;ci++) { + if (allspans[ci].className == 'sortarrow') { + if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us? + allspans[ci].innerHTML = ' ↓'; + } + } + } + span.innerHTML = ARROW; + alternate(t); +} + +function getParent(el, pTagName) { + if (el == null) { + return null; + } else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()) { + return el; + } else { + return getParent(el.parentNode, pTagName); + } +} + +function sort_date(date) { + // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX + dt = "00000000"; + if (date.length == 11) { + mtstr = date.substr(3,3); + mtstr = mtstr.toLowerCase(); + switch(mtstr) { + case "jan": var mt = "01"; break; + case "feb": var mt = "02"; break; + case "mar": var mt = "03"; break; + case "apr": var mt = "04"; break; + case "may": var mt = "05"; break; + case "jun": var mt = "06"; break; + case "jul": var mt = "07"; break; + case "aug": var mt = "08"; break; + case "sep": var mt = "09"; break; + case "oct": var mt = "10"; break; + case "nov": var mt = "11"; break; + case "dec": var mt = "12"; break; + // default: var mt = "00"; + } + dt = date.substr(7,4)+mt+date.substr(0,2); + return dt; + } else if (date.length == 10) { + if (europeandate == false) { + dt = date.substr(6,4)+date.substr(0,2)+date.substr(3,2); + return dt; + } else { + dt = date.substr(6,4)+date.substr(3,2)+date.substr(0,2); + return dt; + } + } else if (date.length == 8) { + yr = date.substr(6,2); + if (parseInt(yr) < 50) { + yr = '20'+yr; + } else { + yr = '19'+yr; + } + if (europeandate == true) { + dt = yr+date.substr(3,2)+date.substr(0,2); + return dt; + } else { + dt = yr+date.substr(0,2)+date.substr(3,2); + return dt; + } + } + return dt; +} + +function ts_sort_date(a,b) { + dt1 = sort_date(ts_getInnerText(a.cells[SORT_COLUMN_INDEX])); + dt2 = sort_date(ts_getInnerText(b.cells[SORT_COLUMN_INDEX])); + + if (dt1==dt2) { + return 0; + } + if (dt1<dt2) { + return -1; + } + return 1; +} +function ts_sort_numeric(a,b) { + var aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]); + aa = clean_num(aa); + var bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]); + bb = clean_num(bb); + return compare_numeric(aa,bb); +} +function compare_numeric(a,b) { + var a = parseFloat(a); + a = (isNaN(a) ? 0 : a); + var b = parseFloat(b); + b = (isNaN(b) ? 0 : b); + return a - b; +} +function ts_sort_caseinsensitive(a,b) { + aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase(); + bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase(); + if (aa==bb) { + return 0; + } + if (aa<bb) { + return -1; + } + return 1; +} +function ts_sort_default(a,b) { + aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]); + bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]); + if (aa==bb) { + return 0; + } + if (aa<bb) { + return -1; + } + return 1; +} +function addEvent(elm, evType, fn, useCapture) +// addEvent and removeEvent +// cross-browser event handling for IE5+, NS6 and Mozilla +// By Scott Andrew +{ + if (elm.addEventListener){ + elm.addEventListener(evType, fn, useCapture); + return true; + } else if (elm.attachEvent){ + var r = elm.attachEvent("on"+evType, fn); + return r; + } else { + alert("Handler could not be removed"); + } +} +function clean_num(str) { + str = str.replace(new RegExp(/[^-?0-9.]/g),""); + return str; +} +function trim(s) { + return s.replace(/^\s+|\s+$/g, ""); +} +function alternate(table) { + // Take object table and get all it's tbodies. + var tableBodies = table.getElementsByTagName("tbody"); + // Loop through these tbodies + for (var i = 0; i < tableBodies.length; i++) { + // Take the tbody, and get all it's rows + var tableRows = tableBodies[i].getElementsByTagName("tr"); + // Loop through these rows + // Start at 1 because we want to leave the heading row untouched + for (var j = 0; j < tableRows.length; j++) { + // Check if j is even, and apply classes for both possible results + if ( (j % 2) == 0 ) { + if ( !(tableRows[j].className.indexOf('odd') == -1) ) { + tableRows[j].className = tableRows[j].className.replace('odd', 'even'); + } else { + if ( tableRows[j].className.indexOf('even') == -1 ) { + tableRows[j].className += " even"; + } + } + } else { + if ( !(tableRows[j].className.indexOf('even') == -1) ) { + tableRows[j].className = tableRows[j].className.replace('even', 'odd'); + } else { + if ( tableRows[j].className.indexOf('odd') == -1 ) { + tableRows[j].className += " odd"; + } + } + } + } + } +} |