forked from webduinoio/webduino-blockly
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebduino-base.min.js
More file actions
3 lines (3 loc) · 68.7 KB
/
webduino-base.min.js
File metadata and controls
3 lines (3 loc) · 68.7 KB
1
2
3
!function(e,t){"use strict";function n(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n<t.length;n++)t[n]=arguments[n+1];var i={callback:e,args:t};return c[a]=i,r(a),a++}function i(e){delete c[e]}function s(e){var n=e.callback,i=e.args;switch(i.length){case 0:n();break;case 1:n(i[0]);break;case 2:n(i[0],i[1]);break;case 3:n(i[0],i[1],i[2]);break;default:n.apply(t,i)}}function o(e){if(h)setTimeout(o,0,e);else{var t=c[e];if(t){h=!0;try{s(t)}finally{i(e),h=!1}}}}if(!e.setImmediate){var r,a=1,c={},h=!1,u=e.document,l=Object.getPrototypeOf&&Object.getPrototypeOf(e);l=l&&l.setTimeout?l:e,"[object process]"==={}.toString.call(e.process)?function(){r=function(e){process.nextTick(function(){o(e)})}}():function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=n,t}}()?function(){var t="setImmediate$"+Math.random()+"$",n=function(n){n.source===e&&"string"==typeof n.data&&0===n.data.indexOf(t)&&o(+n.data.slice(t.length))};e.addEventListener?e.addEventListener("message",n,!1):e.attachEvent("onmessage",n),r=function(n){e.postMessage(t+n,"*")}}():e.MessageChannel?function(){var e=new MessageChannel;e.port1.onmessage=function(e){o(e.data)},r=function(t){e.port2.postMessage(t)}}():u&&"onreadystatechange"in u.createElement("script")?function(){var e=u.documentElement;r=function(t){var n=u.createElement("script");n.onreadystatechange=function(){o(t),n.onreadystatechange=null,e.removeChild(n),n=null},e.appendChild(n)}}():function(){r=function(e){setTimeout(o,0,e)}}(),l.setImmediate=n,l.clearImmediate=i}}("undefined"==typeof self?"undefined"==typeof global?this:global:self),"undefined"==typeof Paho&&(Paho={}),Paho.MQTT=function(e){function t(e,t){var n=t,i=e[t],o=i>>4,r=i&=15;t+=1;var a,u=0,l=1;do{if(t==e.length)return[null,n];a=e[t++],u+=(127&a)*l,l*=128}while(0!=(128&a));var d=t+u;if(d>e.length)return[null,n];var f=new m(o);switch(o){case h.CONNACK:1&e[t++]&&(f.sessionPresent=!0),f.returnCode=e[t++];break;case h.PUBLISH:var _=r>>1&3,p=s(e,t);t+=2;var g=c(e,t,p);t+=p,_>0&&(f.messageIdentifier=s(e,t),t+=2);var v=new Paho.MQTT.Message(e.subarray(t,d));1==(1&r)&&(v.retained=!0),8==(8&r)&&(v.duplicate=!0),v.qos=_,v.destinationName=g,f.payloadMessage=v;break;case h.PUBACK:case h.PUBREC:case h.PUBREL:case h.PUBCOMP:case h.UNSUBACK:f.messageIdentifier=s(e,t);break;case h.SUBACK:f.messageIdentifier=s(e,t),t+=2,f.returnCode=e.subarray(t,d)}return[f,d]}function n(e,t,n){return t[n++]=e>>8,t[n++]=e%256,n}function i(e,t,i,s){return s=n(t,i,s),a(e,i,s),s+t}function s(e,t){return 256*e[t]+e[t+1]}function o(e){var t=new Array(1),n=0;do{var i=e%128;e>>=7,e>0&&(i|=128),t[n++]=i}while(e>0&&n<4);return t}function r(e){for(var t=0,n=0;n<e.length;n++){var i=e.charCodeAt(n);i>2047?(55296<=i&&i<=56319&&(n++,t++),t+=3):i>127?t+=2:t++}return t}function a(e,t,n){for(var i=n,s=0;s<e.length;s++){var o=e.charCodeAt(s);if(55296<=o&&o<=56319){var r=e.charCodeAt(++s);if(isNaN(r))throw new Error(_(d.MALFORMED_UNICODE,[o,r]));o=r-56320+(o-55296<<10)+65536}o<=127?t[i++]=o:o<=2047?(t[i++]=o>>6&31|192,t[i++]=63&o|128):o<=65535?(t[i++]=o>>12&15|224,t[i++]=o>>6&63|128,t[i++]=63&o|128):(t[i++]=o>>18&7|240,t[i++]=o>>12&63|128,t[i++]=o>>6&63|128,t[i++]=63&o|128)}return t}function c(e,t,n){for(var i,s="",o=t;o<t+n;){var r=e[o++];if(r<128)i=r;else{var a=e[o++]-128;if(a<0)throw new Error(_(d.MALFORMED_UTF,[r.toString(16),a.toString(16),""]));if(r<224)i=64*(r-192)+a;else{var c=e[o++]-128;if(c<0)throw new Error(_(d.MALFORMED_UTF,[r.toString(16),a.toString(16),c.toString(16)]));if(r<240)i=4096*(r-224)+64*a+c;else{var h=e[o++]-128;if(h<0)throw new Error(_(d.MALFORMED_UTF,[r.toString(16),a.toString(16),c.toString(16),h.toString(16)]));if(!(r<248))throw new Error(_(d.MALFORMED_UTF,[r.toString(16),a.toString(16),c.toString(16),h.toString(16)]));i=262144*(r-240)+4096*a+64*c+h}}}i>65535&&(i-=65536,s+=String.fromCharCode(55296+(i>>10)),i=56320+(1023&i)),s+=String.fromCharCode(i)}return s}var h={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},u=function(e,t){for(var n in e)if(e.hasOwnProperty(n)){if(!t.hasOwnProperty(n)){var i="Unknown property, "+n+". Valid properties are:";for(var n in t)t.hasOwnProperty(n)&&(i=i+" "+n);throw new Error(i)}if(typeof e[n]!==t[n])throw new Error(_(d.INVALID_TYPE,[typeof e[n],n]))}},l=function(e,t){return function(){return e.apply(t,arguments)}},d={OK:{code:0,text:"AMQJSC0000I OK."},CONNECT_TIMEOUT:{code:1,text:"AMQJSC0001E Connect timed out."},SUBSCRIBE_TIMEOUT:{code:2,text:"AMQJS0002E Subscribe timed out."},UNSUBSCRIBE_TIMEOUT:{code:3,text:"AMQJS0003E Unsubscribe timed out."},PING_TIMEOUT:{code:4,text:"AMQJS0004E Ping timed out."},INTERNAL_ERROR:{code:5,text:"AMQJS0005E Internal error. Error Message: {0}, Stack trace: {1}"},CONNACK_RETURNCODE:{code:6,text:"AMQJS0006E Bad Connack return code:{0} {1}."},SOCKET_ERROR:{code:7,text:"AMQJS0007E Socket error:{0}."},SOCKET_CLOSE:{code:8,text:"AMQJS0008I Socket closed."},MALFORMED_UTF:{code:9,text:"AMQJS0009E Malformed UTF data:{0} {1} {2}."},UNSUPPORTED:{code:10,text:"AMQJS0010E {0} is not supported by this browser."},INVALID_STATE:{code:11,text:"AMQJS0011E Invalid state {0}."},INVALID_TYPE:{code:12,text:"AMQJS0012E Invalid type {0} for {1}."},INVALID_ARGUMENT:{code:13,text:"AMQJS0013E Invalid argument {0} for {1}."},UNSUPPORTED_OPERATION:{code:14,text:"AMQJS0014E Unsupported operation."},INVALID_STORED_DATA:{code:15,text:"AMQJS0015E Invalid data in local storage key={0} value={1}."},INVALID_MQTT_MESSAGE_TYPE:{code:16,text:"AMQJS0016E Invalid MQTT message type {0}."},MALFORMED_UNICODE:{code:17,text:"AMQJS0017E Malformed Unicode string:{0} {1}."},BUFFER_FULL:{code:18,text:"AMQJS0018E Message buffer is full, maximum buffer size: ${0}."}},f={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"},_=function(e,t){var n=e.text;if(t)for(var i,s,o=0;o<t.length;o++)if(i="{"+o+"}",(s=n.indexOf(i))>0){var r=n.substring(0,s),a=n.substring(s+i.length);n=r+t[o]+a}return n},p=[0,6,77,81,73,115,100,112,3],g=[0,4,77,81,84,84,4],m=function(e,t){this.type=e;for(var n in t)t.hasOwnProperty(n)&&(this[n]=t[n])};m.prototype.encode=function(){var e=(15&this.type)<<4,t=0,s=new Array,a=0;switch(void 0!=this.messageIdentifier&&(t+=2),this.type){case h.CONNECT:switch(this.mqttVersion){case 3:t+=p.length+3;break;case 4:t+=g.length+3}if(t+=r(this.clientId)+2,void 0!=this.willMessage){t+=r(this.willMessage.destinationName)+2;var c=this.willMessage.payloadBytes;c instanceof Uint8Array||(c=new Uint8Array(l)),t+=c.byteLength+2}void 0!=this.userName&&(t+=r(this.userName)+2),void 0!=this.password&&(t+=r(this.password)+2);break;case h.SUBSCRIBE:e|=2;for(var u=0;u<this.topics.length;u++)s[u]=r(this.topics[u]),t+=s[u]+2;t+=this.requestedQos.length;break;case h.UNSUBSCRIBE:e|=2;for(var u=0;u<this.topics.length;u++)s[u]=r(this.topics[u]),t+=s[u]+2;break;case h.PUBREL:e|=2;break;case h.PUBLISH:this.payloadMessage.duplicate&&(e|=8),e=e|=this.payloadMessage.qos<<1,this.payloadMessage.retained&&(e|=1),a=r(this.payloadMessage.destinationName),t+=a+2;var l=this.payloadMessage.payloadBytes;t+=l.byteLength,l instanceof ArrayBuffer?l=new Uint8Array(l):l instanceof Uint8Array||(l=new Uint8Array(l.buffer));break;case h.DISCONNECT:}var d=o(t),f=d.length+1,_=new ArrayBuffer(t+f),m=new Uint8Array(_);if(m[0]=e,m.set(d,1),this.type==h.PUBLISH)f=i(this.payloadMessage.destinationName,a,m,f);else if(this.type==h.CONNECT){switch(this.mqttVersion){case 3:m.set(p,f),f+=p.length;break;case 4:m.set(g,f),f+=g.length}var v=0;this.cleanSession&&(v=2),void 0!=this.willMessage&&(v|=4,v|=this.willMessage.qos<<3,this.willMessage.retained&&(v|=32)),void 0!=this.userName&&(v|=128),void 0!=this.password&&(v|=64),m[f++]=v,f=n(this.keepAliveInterval,m,f)}switch(void 0!=this.messageIdentifier&&(f=n(this.messageIdentifier,m,f)),this.type){case h.CONNECT:f=i(this.clientId,r(this.clientId),m,f),void 0!=this.willMessage&&(f=i(this.willMessage.destinationName,r(this.willMessage.destinationName),m,f),f=n(c.byteLength,m,f),m.set(c,f),f+=c.byteLength),void 0!=this.userName&&(f=i(this.userName,r(this.userName),m,f)),void 0!=this.password&&(f=i(this.password,r(this.password),m,f));break;case h.PUBLISH:m.set(l,f);break;case h.SUBSCRIBE:for(var u=0;u<this.topics.length;u++)f=i(this.topics[u],s[u],m,f),m[f++]=this.requestedQos[u];break;case h.UNSUBSCRIBE:for(var u=0;u<this.topics.length;u++)f=i(this.topics[u],s[u],m,f)}return _};var v=function(e,t,n){this._client=e,this._window=t,this._keepAliveInterval=1e3*n,this.isReset=!1;var i=new m(h.PINGREQ).encode(),s=function(e){return function(){return o.apply(e)}},o=function(){this.isReset?(this.isReset=!1,this._client._trace("Pinger.doPing","send PINGREQ"),this._client.socket.send(i),this.timeout=this._window.setTimeout(s(this),this._keepAliveInterval)):(this._client._trace("Pinger.doPing","Timed out"),this._client._disconnected(d.PING_TIMEOUT.code,_(d.PING_TIMEOUT)))};this.reset=function(){this.isReset=!0,this._window.clearTimeout(this.timeout),this._keepAliveInterval>0&&(this.timeout=setTimeout(s(this),this._keepAliveInterval))},this.cancel=function(){this._window.clearTimeout(this.timeout)}},E=function(e,t,n){this._client=e,this._window=t,this._reconnectInterval=1e3*n;var i=function(e){return function(){return s.apply(e)}},s=function(){this._client.connected?(this._client._trace("Reconnector.doReconnect","ALREADY CONNECTED"),this._window.clearTimeout(this.reconnectorTimer)):(this._client._trace("Reconnector.doReconnect","reconnecting"),this._client.connectOptions.uris?(this._client.hostIndex=0,this._client._doConnect(this._client.connectOptions.uris[0])):this._client._doConnect(this._client.uri),this.reconnectorTimer=this._window.setTimeout(i(this),this._reconnectInterval))};this.reset=function(){this._window.clearTimeout(this.reconnectorTimer),this.reconnectorTimer=this._window.setTimeout(i(this),this._reconnectInterval)},this.cancel=function(){this._window.clearTimeout(this.reconnectorTimer)}},b=function(e,t,n,i,s){this._window=t,n||(n=30);this.timeout=setTimeout(function(e,t,n){return function(){return e.apply(t,n)}}(i,e,s),1e3*n),this.cancel=function(){this._window.clearTimeout(this.timeout)}},y=function(t,n,i,s,o){if(!("WebSocket"in e&&null!==e.WebSocket))throw new Error(_(d.UNSUPPORTED,["WebSocket"]));if("localStorage"in e&&null!==e.localStorage||(localStorage={store:{},setItem:function(e,t){this.store[e]=t},getItem:function(e){return this.store[e]},removeItem:function(e){delete this.store[e]}}),!("ArrayBuffer"in e&&null!==e.ArrayBuffer))throw new Error(_(d.UNSUPPORTED,["ArrayBuffer"]));this._trace("Paho.MQTT.Client",t,n,i,s,o),this.host=n,this.port=i,this.path=s,this.uri=t,this.clientId=o,this._wsuri=null,this._localKey=n+":"+i+("/mqtt"!=s?":"+s:"")+":"+o+":",this._msg_queue=[],this._buffered_queue=[],this._sentMessages={},this._receivedMessages={},this._notify_msg_sent={},this._message_identifier=1,this._sequence=0;for(var r in localStorage)0!=r.indexOf("Sent:"+this._localKey)&&0!=r.indexOf("Received:"+this._localKey)||this.restore(r)};y.prototype.host,y.prototype.port,y.prototype.path,y.prototype.uri,y.prototype.clientId,y.prototype.socket,y.prototype.connected=!1,y.prototype.maxMessageIdentifier=65536,y.prototype.connectOptions,y.prototype.hostIndex,y.prototype.onConnected,y.prototype.onConnectionLost,y.prototype.onMessageDelivered,y.prototype.onMessageArrived,y.prototype.traceFunction,y.prototype._msg_queue=null,y.prototype._buffered_queue=null,y.prototype._connectTimeout,y.prototype.sendPinger=null,y.prototype.receivePinger=null,y.prototype.reconnector=null,y.prototype.disconnectedPublishing=!1,y.prototype.disconnectedBufferSize=5e3,y.prototype.receiveBuffer=null,y.prototype._traceBuffer=null,y.prototype._MAX_TRACE_ENTRIES=100,y.prototype.connect=function(e){var t=this._traceMask(e,"password");if(this._trace("Client.connect",t,this.socket,this.connected),this.connected)throw new Error(_(d.INVALID_STATE,["already connected"]));if(this.socket)throw new Error(_(d.INVALID_STATE,["already connected"]));this.connectOptions=e,e.uris?(this.hostIndex=0,this._doConnect(e.uris[0])):this._doConnect(this.uri)},y.prototype.subscribe=function(e,t){if(this._trace("Client.subscribe",e,t),!this.connected)throw new Error(_(d.INVALID_STATE,["not connected"]));var n=new m(h.SUBSCRIBE);n.topics=[e],void 0!=t.qos?n.requestedQos=[t.qos]:n.requestedQos=[0],t.onSuccess&&(n.onSuccess=function(e){t.onSuccess({invocationContext:t.invocationContext,grantedQos:e})}),t.onFailure&&(n.onFailure=function(e){t.onFailure({invocationContext:t.invocationContext,errorCode:e})}),t.timeout&&(n.timeOut=new b(this,window,t.timeout,t.onFailure,[{invocationContext:t.invocationContext,errorCode:d.SUBSCRIBE_TIMEOUT.code,errorMessage:_(d.SUBSCRIBE_TIMEOUT)}])),this._requires_ack(n),this._schedule_message(n)},y.prototype.unsubscribe=function(e,t){if(this._trace("Client.unsubscribe",e,t),!this.connected)throw new Error(_(d.INVALID_STATE,["not connected"]));var n=new m(h.UNSUBSCRIBE);n.topics=[e],t.onSuccess&&(n.callback=function(){t.onSuccess({invocationContext:t.invocationContext})}),t.timeout&&(n.timeOut=new b(this,window,t.timeout,t.onFailure,[{invocationContext:t.invocationContext,errorCode:d.UNSUBSCRIBE_TIMEOUT.code,errorMessage:_(d.UNSUBSCRIBE_TIMEOUT)}])),this._requires_ack(n),this._schedule_message(n)},y.prototype.send=function(e){if(this._trace("Client.send",e),!this.connected){if(this.reconnector&&this.disconnectedPublishing){if(this._buffered_queue.length===this.disconnectedBufferSize)throw new Error(_(d.BUFFER_FULL,[this._buffered_queue.length]));return void this._buffered_queue.push(e)}throw new Error(_(d.INVALID_STATE,["not connected"]))}wireMessage=new m(h.PUBLISH),wireMessage.payloadMessage=e,e.qos>0?this._requires_ack(wireMessage):this.onMessageDelivered&&(this._notify_msg_sent[wireMessage]=this.onMessageDelivered(wireMessage.payloadMessage)),this._schedule_message(wireMessage)},y.prototype.disconnect=function(){if(this._trace("Client.disconnect"),!this.socket)throw new Error(_(d.INVALID_STATE,["not connecting or connected"]));wireMessage=new m(h.DISCONNECT),this._notify_msg_sent[wireMessage]=l(this._disconnected,this),this._schedule_message(wireMessage)},y.prototype.getTraceLog=function(){if(null!==this._traceBuffer){this._trace("Client.getTraceLog",new Date),this._trace("Client.getTraceLog in flight messages",this._sentMessages.length);for(var e in this._sentMessages)this._trace("_sentMessages ",e,this._sentMessages[e]);for(var e in this._receivedMessages)this._trace("_receivedMessages ",e,this._receivedMessages[e]);return this._traceBuffer}},y.prototype.startTrace=function(){null===this._traceBuffer&&(this._traceBuffer=[]),this._trace("Client.startTrace",new Date,"@VERSION@")},y.prototype.stopTrace=function(){delete this._traceBuffer},y.prototype._doConnect=function(e){if(this.connectOptions.useSSL){var t=e.split(":");t[0]="wss",e=t.join(":")}this._wsuri=e,this.connected=!1,this.connectOptions.mqttVersion<4?this.socket=new WebSocket(e,["mqttv3.1"]):this.socket=new WebSocket(e,["mqtt"]),this.socket.binaryType="arraybuffer",this.socket.onopen=l(this._on_socket_open,this),this.socket.onmessage=l(this._on_socket_message,this),this.socket.onerror=l(this._on_socket_error,this),this.socket.onclose=l(this._on_socket_close,this),this.sendPinger=new v(this,window,this.connectOptions.keepAliveInterval),this.receivePinger=new v(this,window,this.connectOptions.keepAliveInterval),this._connectTimeout=new b(this,window,this.connectOptions.timeout,this._disconnected,[d.CONNECT_TIMEOUT.code,_(d.CONNECT_TIMEOUT)])},y.prototype._schedule_message=function(e){this._msg_queue.push(e),this.connected&&null===this.reconnector&&this._process_queue()},y.prototype.store=function(e,t){var n={type:t.type,messageIdentifier:t.messageIdentifier,version:1};switch(t.type){case h.PUBLISH:t.pubRecReceived&&(n.pubRecReceived=!0),n.payloadMessage={};for(var i="",s=t.payloadMessage.payloadBytes,o=0;o<s.length;o++)s[o]<=15?i=i+"0"+s[o].toString(16):i+=s[o].toString(16);n.payloadMessage.payloadHex=i,n.payloadMessage.qos=t.payloadMessage.qos,n.payloadMessage.destinationName=t.payloadMessage.destinationName,t.payloadMessage.duplicate&&(n.payloadMessage.duplicate=!0),t.payloadMessage.retained&&(n.payloadMessage.retained=!0),0==e.indexOf("Sent:")&&(void 0===t.sequence&&(t.sequence=++this._sequence),n.sequence=t.sequence);break;default:throw Error(_(d.INVALID_STORED_DATA,[key,n]))}localStorage.setItem(e+this._localKey+t.messageIdentifier,JSON.stringify(n))},y.prototype.restore=function(e){var t=localStorage.getItem(e),n=JSON.parse(t),i=new m(n.type,n);switch(n.type){case h.PUBLISH:for(var s=n.payloadMessage.payloadHex,o=new ArrayBuffer(s.length/2),r=new Uint8Array(o),a=0;s.length>=2;){var c=parseInt(s.substring(0,2),16);s=s.substring(2,s.length),r[a++]=c}var u=new Paho.MQTT.Message(r);u.qos=n.payloadMessage.qos,u.destinationName=n.payloadMessage.destinationName,n.payloadMessage.duplicate&&(u.duplicate=!0),n.payloadMessage.retained&&(u.retained=!0),i.payloadMessage=u;break;default:throw Error(_(d.INVALID_STORED_DATA,[e,t]))}0==e.indexOf("Sent:"+this._localKey)?(i.payloadMessage.duplicate=!0,this._sentMessages[i.messageIdentifier]=i):0==e.indexOf("Received:"+this._localKey)&&(this._receivedMessages[i.messageIdentifier]=i)},y.prototype._process_queue=function(){for(var e=null,t=this._msg_queue.reverse();e=t.pop();)this._socket_send(e),this._notify_msg_sent[e]&&(this._notify_msg_sent[e](),delete this._notify_msg_sent[e])},y.prototype._requires_ack=function(e){var t=Object.keys(this._sentMessages).length;if(t>this.maxMessageIdentifier)throw Error("Too many messages:"+t);for(;void 0!==this._sentMessages[this._message_identifier];)this._message_identifier++;e.messageIdentifier=this._message_identifier,this._sentMessages[e.messageIdentifier]=e,e.type===h.PUBLISH&&this.store("Sent:",e),this._message_identifier===this.maxMessageIdentifier&&(this._message_identifier=1)},y.prototype._on_socket_open=function(){var e=new m(h.CONNECT,this.connectOptions);e.clientId=this.clientId,this._socket_send(e)},y.prototype._on_socket_message=function(e){this._trace("Client._on_socket_message",e.data);for(var t=this._deframeMessages(e.data),n=0;n<t.length;n+=1)this._handleMessage(t[n])},y.prototype._deframeMessages=function(e){var n=new Uint8Array(e);if(this.receiveBuffer){var i=new Uint8Array(this.receiveBuffer.length+n.length);i.set(this.receiveBuffer),i.set(n,this.receiveBuffer.length),n=i,delete this.receiveBuffer}try{for(var s=0,o=[];s<n.length;){var r=t(n,s),a=r[0];if(s=r[1],null===a)break;o.push(a)}s<n.length&&(this.receiveBuffer=n.subarray(s))}catch(e){return void this._disconnected(d.INTERNAL_ERROR.code,_(d.INTERNAL_ERROR,[e.message,e.stack.toString()]))}return o},y.prototype._handleMessage=function(e){this._trace("Client._handleMessage",e);try{switch(e.type){case h.CONNACK:if(this._connectTimeout.cancel(),this._connectTimeout=null,this.connectOptions.cleanSession){for(var t in this._sentMessages){var n=this._sentMessages[t];localStorage.removeItem("Sent:"+this._localKey+n.messageIdentifier)}this._sentMessages={};for(var t in this._receivedMessages){var i=this._receivedMessages[t];localStorage.removeItem("Received:"+this._localKey+i.messageIdentifier)}this._receivedMessages={}}if(0!==e.returnCode){this._disconnected(d.CONNACK_RETURNCODE.code,_(d.CONNACK_RETURNCODE,[e.returnCode,f[e.returnCode]]));break}this.connected=!0,this.connectOptions.uris&&(this.hostIndex=this.connectOptions.uris.length);var s=new Array;for(var o in this._sentMessages)this._sentMessages.hasOwnProperty(o)&&s.push(this._sentMessages[o]);for(var s=s.sort(function(e,t){return e.sequence-t.sequence}),r=0,a=s.length;r<a;r++){var n=s[r];if(n.type==h.PUBLISH&&n.pubRecReceived){var c=new m(h.PUBREL,{messageIdentifier:n.messageIdentifier});this._schedule_message(c)}else this._schedule_message(n)}if(this.reconnector){for(var u=this._buffered_queue.reverse(),l=null;l=u.pop();){var e=new m(h.PUBLISH);e.payloadMessage=l,l.qos>0?this._requires_ack(e):this.onMessageDelivered&&(this._notify_msg_sent[e]=this.onMessageDelivered(e.payloadMessage)),this._schedule_message(e)}this._buffered_queue=[]}this.connectOptions.onSuccess&&null==this.reconnector&&this.connectOptions.onSuccess({invocationContext:this.connectOptions.invocationContext}),reconnect=!1,this.connectOptions.reconnect&&this.reconnector&&(reconnect=!0,this.reconnector.cancel(),this.reconnector=null,this.onConnected&&this.onConnected({reconnect:reconnect,uri:this._wsuri})),this._process_queue();break;case h.PUBLISH:this._receivePublish(e);break;case h.PUBACK:var n=this._sentMessages[e.messageIdentifier];n&&(delete this._sentMessages[e.messageIdentifier],localStorage.removeItem("Sent:"+this._localKey+e.messageIdentifier),this.onMessageDelivered&&this.onMessageDelivered(n.payloadMessage));break;case h.PUBREC:var n=this._sentMessages[e.messageIdentifier];if(n){n.pubRecReceived=!0;var c=new m(h.PUBREL,{messageIdentifier:e.messageIdentifier});this.store("Sent:",n),this._schedule_message(c)}break;case h.PUBREL:var i=this._receivedMessages[e.messageIdentifier];localStorage.removeItem("Received:"+this._localKey+e.messageIdentifier),i&&(this._receiveMessage(i),delete this._receivedMessages[e.messageIdentifier]);var p=new m(h.PUBCOMP,{messageIdentifier:e.messageIdentifier});this._schedule_message(p);break;case h.PUBCOMP:var n=this._sentMessages[e.messageIdentifier];delete this._sentMessages[e.messageIdentifier],localStorage.removeItem("Sent:"+this._localKey+e.messageIdentifier),this.onMessageDelivered&&this.onMessageDelivered(n.payloadMessage);break;case h.SUBACK:var n=this._sentMessages[e.messageIdentifier];n&&(n.timeOut&&n.timeOut.cancel(),128===e.returnCode[0]?n.onFailure&&n.onFailure(e.returnCode):n.onSuccess&&n.onSuccess(e.returnCode),delete this._sentMessages[e.messageIdentifier]);break;case h.UNSUBACK:var n=this._sentMessages[e.messageIdentifier];n&&(n.timeOut&&n.timeOut.cancel(),n.callback&&n.callback(),delete this._sentMessages[e.messageIdentifier]);break;case h.PINGRESP:this.sendPinger.reset();break;case h.DISCONNECT:this._disconnected(d.INVALID_MQTT_MESSAGE_TYPE.code,_(d.INVALID_MQTT_MESSAGE_TYPE,[e.type]));break;default:this._disconnected(d.INVALID_MQTT_MESSAGE_TYPE.code,_(d.INVALID_MQTT_MESSAGE_TYPE,[e.type]))}}catch(e){return void this._disconnected(d.INTERNAL_ERROR.code,_(d.INTERNAL_ERROR,[e.message,e.stack.toString()]))}},y.prototype._on_socket_error=function(e){this._disconnected(d.SOCKET_ERROR.code,_(d.SOCKET_ERROR,[e.data]))},y.prototype._on_socket_close=function(){this._disconnected(d.SOCKET_CLOSE.code,_(d.SOCKET_CLOSE))},y.prototype._socket_send=function(e){if(1==e.type){var t=this._traceMask(e,"password");this._trace("Client._socket_send",t)}else this._trace("Client._socket_send",e);this.socket.send(e.encode()),this.sendPinger.reset()},y.prototype._receivePublish=function(e){switch(e.payloadMessage.qos){case"undefined":case 0:this._receiveMessage(e);break;case 1:var t=new m(h.PUBACK,{messageIdentifier:e.messageIdentifier});this._schedule_message(t),this._receiveMessage(e);break;case 2:this._receivedMessages[e.messageIdentifier]=e,this.store("Received:",e);var n=new m(h.PUBREC,{messageIdentifier:e.messageIdentifier});this._schedule_message(n);break;default:throw Error("Invaild qos="+wireMmessage.payloadMessage.qos)}},y.prototype._receiveMessage=function(e){this.onMessageArrived&&this.onMessageArrived(e.payloadMessage)},y.prototype._connected=function(e,t){this.onConnected&&this.onConnected({reconnect:e,uri:t})},y.prototype._disconnected=function(e,t){this._trace("Client._disconnected",e,t,new Date),this.connected&&e===d.CONNECT_TIMEOUT.code||(this.sendPinger.cancel(),this.receivePinger.cancel(),this._connectTimeout&&(this._connectTimeout.cancel(),this._connectTimeout=null),this.reconnector||(this._msg_queue=[],this._notify_msg_sent={}),this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,1===this.socket.readyState&&this.socket.close(),delete this.socket),this.connectOptions.uris&&this.hostIndex<this.connectOptions.uris.length-1?(this.hostIndex++,this._doConnect(this.connectOptions.uris[this.hostIndex])):(void 0===e&&(e=d.OK.code,t=_(d.OK)),this.connected?(this.connected=!1,this.onConnectionLost&&(reconnect=!1,this.connectOptions.reconnect&&(reconnect=this.connectOptions.reconnect),this.onConnectionLost({errorCode:e,errorMessage:t,reconnect:reconnect,uri:this._wsuri})),e!==d.OK.code&&this.connectOptions.reconnect&&(this._trace("Client._disconnected","starting auto reconnect"),this.reconnector=new E(this,window,this.connectOptions.reconnectInterval),this.reconnector.reset())):this.reconnector?this._trace("Client._disconnected","auto reconnect is already in progress",new Date):4===this.connectOptions.mqttVersion&&!1===this.connectOptions.mqttVersionExplicit?(this._trace("Failed to connect V4, dropping back to V3"),this.connectOptions.mqttVersion=3,this.connectOptions.uris?(this.hostIndex=0,this._doConnect(this.connectOptions.uris[0])):this._doConnect(this.uri)):this.connectOptions.onFailure&&this.connectOptions.onFailure({invocationContext:this.connectOptions.invocationContext,errorCode:e,errorMessage:t})))},y.prototype._trace=function(){if(this.traceFunction){for(var e in arguments)void 0!==arguments[e]&&(arguments[e]=JSON.stringify(arguments[e]));var t=Array.prototype.slice.call(arguments).join("");this.traceFunction({severity:"Debug",message:t})}if(null!==this._traceBuffer)for(var e=0,n=arguments.length;e<n;e++)this._traceBuffer.length==this._MAX_TRACE_ENTRIES&&this._traceBuffer.shift(),0===e?this._traceBuffer.push(arguments[e]):void 0===arguments[e]?this._traceBuffer.push(arguments[e]):this._traceBuffer.push(" "+JSON.stringify(arguments[e]))},y.prototype._traceMask=function(e,t){var n={};for(var i in e)e.hasOwnProperty(i)&&(n[i]=i==t?"******":e[i]);return n};var I=function(e,t,n,i){var s;if("string"!=typeof e)throw new Error(_(d.INVALID_TYPE,[typeof e,"host"]));if(2==arguments.length){i=t,s=e;var o=s.match(/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/);if(!o)throw new Error(_(d.INVALID_ARGUMENT,[e,"host"]));e=o[4]||o[2],t=parseInt(o[7]),n=o[8]}else{if(3==arguments.length&&(i=n,n="/mqtt"),"number"!=typeof t||t<0)throw new Error(_(d.INVALID_TYPE,[typeof t,"port"]));if("string"!=typeof n)throw new Error(_(d.INVALID_TYPE,[typeof n,"path"]));var r=-1!=e.indexOf(":")&&"["!=e.slice(0,1)&&"]"!=e.slice(-1);s="ws://"+(r?"["+e+"]":e)+":"+t+n}for(var a=0,c=0;c<i.length;c++){var h=i.charCodeAt(c);55296<=h&&h<=56319&&c++,a++}if("string"!=typeof i||a>65535)throw new Error(_(d.INVALID_ARGUMENT,[i,"clientId"]));var l=new y(s,e,t,n,i);this._getHost=function(){return e},this._setHost=function(){throw new Error(_(d.UNSUPPORTED_OPERATION))},this._getPort=function(){return t},this._setPort=function(){throw new Error(_(d.UNSUPPORTED_OPERATION))},this._getPath=function(){return n},this._setPath=function(){throw new Error(_(d.UNSUPPORTED_OPERATION))},this._getURI=function(){return s},this._setURI=function(){throw new Error(_(d.UNSUPPORTED_OPERATION))},this._getClientId=function(){return l.clientId},this._setClientId=function(){throw new Error(_(d.UNSUPPORTED_OPERATION))},this._getOnConnected=function(){return l.onConnected},this._setOnConnected=function(e){if("function"!=typeof e)throw new Error(_(d.INVALID_TYPE,[typeof e,"onConnected"]));l.onConnected=e},this._getDisconnectedPublishing=function(){return l.disconnectedPublishing},this._setDisconnectedPublishing=function(e){l.disconnectedPublishing=e},this._getDisconnectedBufferSize=function(){return l.disconnectedBufferSize},this._setDisconnectedBufferSize=function(e){l.disconnectedBufferSize=e},this._getOnConnectionLost=function(){return l.onConnectionLost},this._setOnConnectionLost=function(e){if("function"!=typeof e)throw new Error(_(d.INVALID_TYPE,[typeof e,"onConnectionLost"]));l.onConnectionLost=e},this._getOnMessageDelivered=function(){return l.onMessageDelivered},this._setOnMessageDelivered=function(e){if("function"!=typeof e)throw new Error(_(d.INVALID_TYPE,[typeof e,"onMessageDelivered"]));l.onMessageDelivered=e},this._getOnMessageArrived=function(){return l.onMessageArrived},this._setOnMessageArrived=function(e){if("function"!=typeof e)throw new Error(_(d.INVALID_TYPE,[typeof e,"onMessageArrived"]));l.onMessageArrived=e},this._getTrace=function(){return l.traceFunction},this._setTrace=function(e){if("function"!=typeof e)throw new Error(_(d.INVALID_TYPE,[typeof e,"onTrace"]));l.traceFunction=e},this.connect=function(e){if(e=e||{},u(e,{timeout:"number",userName:"string",password:"string",willMessage:"object",keepAliveInterval:"number",cleanSession:"boolean",useSSL:"boolean",invocationContext:"object",onSuccess:"function",onFailure:"function",hosts:"object",ports:"object",reconnect:"boolean",reconnectInterval:"number",mqttVersion:"number",mqttVersionExplicit:"boolean",uris:"object"}),void 0===e.keepAliveInterval&&(e.keepAliveInterval=60),e.mqttVersion>4||e.mqttVersion<3)throw new Error(_(d.INVALID_ARGUMENT,[e.mqttVersion,"connectOptions.mqttVersion"]));if(void 0===e.mqttVersion?(e.mqttVersionExplicit=!1,e.mqttVersion=4):e.mqttVersionExplicit=!0,void 0!==e.password&&void 0===e.userName)throw new Error(_(d.INVALID_ARGUMENT,[e.password,"connectOptions.password"]));if(void 0===e.reconnectInterval&&(e.reconnectInterval=10),e.willMessage){if(!(e.willMessage instanceof w))throw new Error(_(d.INVALID_TYPE,[e.willMessage,"connectOptions.willMessage"]));if(e.willMessage.stringPayload,void 0===e.willMessage.destinationName)throw new Error(_(d.INVALID_TYPE,[typeof e.willMessage.destinationName,"connectOptions.willMessage.destinationName"]))}if(void 0===e.cleanSession&&(e.cleanSession=!0),e.hosts){if(!(e.hosts instanceof Array))throw new Error(_(d.INVALID_ARGUMENT,[e.hosts,"connectOptions.hosts"]));if(e.hosts.length<1)throw new Error(_(d.INVALID_ARGUMENT,[e.hosts,"connectOptions.hosts"]));for(var t=!1,i=0;i<e.hosts.length;i++){if("string"!=typeof e.hosts[i])throw new Error(_(d.INVALID_TYPE,[typeof e.hosts[i],"connectOptions.hosts["+i+"]"]));if(/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/.test(e.hosts[i])){if(0==i)t=!0;else if(!t)throw new Error(_(d.INVALID_ARGUMENT,[e.hosts[i],"connectOptions.hosts["+i+"]"]))}else if(t)throw new Error(_(d.INVALID_ARGUMENT,[e.hosts[i],"connectOptions.hosts["+i+"]"]))}if(t)e.uris=e.hosts;else{if(!e.ports)throw new Error(_(d.INVALID_ARGUMENT,[e.ports,"connectOptions.ports"]));if(!(e.ports instanceof Array))throw new Error(_(d.INVALID_ARGUMENT,[e.ports,"connectOptions.ports"]));if(e.hosts.length!=e.ports.length)throw new Error(_(d.INVALID_ARGUMENT,[e.ports,"connectOptions.ports"]));e.uris=[];for(var i=0;i<e.hosts.length;i++){if("number"!=typeof e.ports[i]||e.ports[i]<0)throw new Error(_(d.INVALID_TYPE,[typeof e.ports[i],"connectOptions.ports["+i+"]"]));var o=e.hosts[i],r=e.ports[i],a=-1!=o.indexOf(":");s="ws://"+(a?"["+o+"]":o)+":"+r+n,e.uris.push(s)}}}l.connect(e)},this.subscribe=function(e,t){if("string"!=typeof e)throw new Error("Invalid argument:"+e);if(t=t||{},u(t,{qos:"number",invocationContext:"object",onSuccess:"function",onFailure:"function",timeout:"number"}),t.timeout&&!t.onFailure)throw new Error("subscribeOptions.timeout specified with no onFailure callback.");if(void 0!==t.qos&&0!==t.qos&&1!==t.qos&&2!==t.qos)throw new Error(_(d.INVALID_ARGUMENT,[t.qos,"subscribeOptions.qos"]));l.subscribe(e,t)},this.unsubscribe=function(e,t){if("string"!=typeof e)throw new Error("Invalid argument:"+e);if(t=t||{},u(t,{invocationContext:"object",onSuccess:"function",onFailure:"function",timeout:"number"}),t.timeout&&!t.onFailure)throw new Error("unsubscribeOptions.timeout specified with no onFailure callback.");l.unsubscribe(e,t)},
this.send=function(e,t,n,i){var s;if(0==arguments.length)throw new Error("Invalid argument.length");if(1==arguments.length){if(!(e instanceof w)&&"string"!=typeof e)throw new Error("Invalid argument:"+typeof e);if(s=e,void 0===s.destinationName)throw new Error(_(d.INVALID_ARGUMENT,[s.destinationName,"Message.destinationName"]));l.send(s)}else s=new w(t),s.destinationName=e,arguments.length>=3&&(s.qos=n),arguments.length>=4&&(s.retained=i),l.send(s)},this.disconnect=function(){l.disconnect()},this.getTraceLog=function(){return l.getTraceLog()},this.startTrace=function(){l.startTrace()},this.stopTrace=function(){l.stopTrace()},this.isConnected=function(){return l.connected}};I.prototype={get host(){return this._getHost()},set host(e){this._setHost(e)},get port(){return this._getPort()},set port(e){this._setPort(e)},get path(){return this._getPath()},set path(e){this._setPath(e)},get clientId(){return this._getClientId()},set clientId(e){this._setClientId(e)},get onConnected(){return this._getOnConnected()},set onConnected(e){this._setOnConnected(e)},get disconnectedPublishing(){return this._getDisconnectedPublishing()},set disconnectedPublishing(e){this._setDisconnectedPublishing(e)},get disconnectedBufferSize(){return this._getDisconnectedBufferSize()},set disconnectedBufferSize(e){this._setDisconnectedBufferSize(e)},get onConnectionLost(){return this._getOnConnectionLost()},set onConnectionLost(e){this._setOnConnectionLost(e)},get onMessageDelivered(){return this._getOnMessageDelivered()},set onMessageDelivered(e){this._setOnMessageDelivered(e)},get onMessageArrived(){return this._getOnMessageArrived()},set onMessageArrived(e){this._setOnMessageArrived(e)},get trace(){return this._getTrace()},set trace(e){this._setTrace(e)}};var w=function(e){var t;if(!("string"==typeof e||e instanceof ArrayBuffer||e instanceof Int8Array||e instanceof Uint8Array||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array))throw _(d.INVALID_ARGUMENT,[e,"newPayload"]);t=e,this._getPayloadString=function(){return"string"==typeof t?t:c(t,0,t.length)},this._getPayloadBytes=function(){if("string"==typeof t){var e=new ArrayBuffer(r(t)),n=new Uint8Array(e);return a(t,n,0),n}return t};var n=void 0;this._getDestinationName=function(){return n},this._setDestinationName=function(e){if("string"!=typeof e)throw new Error(_(d.INVALID_ARGUMENT,[e,"newDestinationName"]));n=e};var i=0;this._getQos=function(){return i},this._setQos=function(e){if(0!==e&&1!==e&&2!==e)throw new Error("Invalid argument:"+e);i=e};var s=!1;this._getRetained=function(){return s},this._setRetained=function(e){if("boolean"!=typeof e)throw new Error(_(d.INVALID_ARGUMENT,[e,"newRetained"]));s=e};var o=!1;this._getDuplicate=function(){return o},this._setDuplicate=function(e){o=e}};return w.prototype={get payloadString(){return this._getPayloadString()},get payloadBytes(){return this._getPayloadBytes()},get destinationName(){return this._getDestinationName()},set destinationName(e){this._setDestinationName(e)},get qos(){return this._getQos()},set qos(e){this._setQos(e)},get retained(){return this._getRetained()},set retained(e){this._setRetained(e)},get duplicate(){return this._getDuplicate()},set duplicate(e){this._setDuplicate(e)}},{Client:I,Message:w}}(window);var webduino=webduino||{version:"0.4.16"};"undefined"!=typeof exports&&(module.exports=webduino),function(e){"undefined"==typeof exports?e(webduino||{}):module.exports=e}(function(e){"use strict";function t(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function n(e){return"function"==typeof e}function i(e){return"number"==typeof e}function s(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}var r;r=t.prototype,r._events=void 0,r._maxListeners=void 0,t.defaultMaxListeners=10,r.setMaxListeners=function(e){if(!i(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.emit=function(e){var t,i,r,a,c;if(this._events||(this._events={}),t=this._events[e],o(t))return!1;if(n(t))switch(arguments.length){case 1:t.call(this);break;case 2:t.call(this,arguments[1]);break;case 3:t.call(this,arguments[1],arguments[2]);break;default:r=Array.prototype.slice.call(arguments,1),t.apply(this,r)}else if(s(t))for(r=Array.prototype.slice.call(arguments,1),c=t.slice(),i=c.length,a=0;a<i;a++)c[a].apply(this,r);return!0},r.addListener=function(e,i){var r;if(!n(i))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,n(i.listener)?i.listener:i),this._events[e]?s(this._events[e])?this._events[e].push(i):this._events[e]=[this._events[e],i]:this._events[e]=i,s(this._events[e])&&!this._events[e].warned&&(r=o(this._maxListeners)?t.defaultMaxListeners:this._maxListeners)&&r>0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},r.on=r.addListener,r.once=function(e,t){function i(){this.removeListener(e,i),s||(s=!0,t.apply(this,arguments))}if(!n(t))throw TypeError("listener must be a function");var s=!1;return i.listener=t,this.on(e,i),this},r.removeListener=function(e,t){var i,o,r,a;if(!n(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(i=this._events[e],r=i.length,o=-1,i===t||n(i.listener)&&i.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(s(i)){for(a=r;a-- >0;)if(i[a]===t||i[a].listener&&i[a].listener===t){o=a;break}if(o<0)return this;1===i.length?(i.length=0,delete this._events[e]):i.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.removeAllListeners=function(e){var t,i;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(i=this._events[e],n(i))this.removeListener(e,i);else if(i)for(;i.length;)this.removeListener(e,i[i.length-1]);return delete this._events[e],this},r.listeners=function(e){return this._events&&this._events[e]?n(this._events[e])?[this._events[e]]:this._events[e].slice():[]},t.listenerCount=function(e,t){return e._events&&e._events[t]?n(e._events[t])?1:e._events[t].length:0},e.EventEmitter=t}),function(e){"undefined"==typeof exports?e(webduino||{}):module.exports=e}(function(e){"use strict";function t(e){return"function"==typeof e}function n(e){return"[object Object]"===u.call(e)}function i(e){return n(e)&&e.constructor===Object&&!e.nodeType&&!e.setInterval}function s(e){return Array.isArray(e)}function o(){var e,n,r,a,c,h,u=arguments[0]||{},l=1,d=arguments.length,f=!1;for("boolean"==typeof u&&(f=u,u=arguments[1]||{},l=2),"object"==typeof u||t(u)||(u={});l<d;l++)if(null!==(e=arguments[l])){"string"==typeof e&&(e=e.split(""));for(n in e)r=u[n],a=e[n],u!==a&&(f&&a&&(i(a)||(c=s(a)))?(c?(c=!1,h=r&&s(r)?r:[]):h=r&&i(r)?r:{},u[n]=o(f,h,a)):void 0!==a&&(u[n]=a))}return u}function r(e){if(c){var t=document.createElement("a");return t.href=e,t}return require("url").parse(e)}function a(){return(Math.random()*Date.now()).toString(36).replace(/\./g,"")}var c="undefined"==typeof exports,h=Object.prototype,u=(h.hasOwnProperty,h.toString);e.util={isFn:t,isFunction:t,isObject:n,isHash:i,isArray:s,extend:o,parseURL:r,randomId:a}}),function(e){"undefined"==typeof exports?e(webduino||{}):module.exports=e}(function(e){"use strict";function t(e,t,n){this.resolve=e,this.reject=t,this.custom=n}function n(e,t,n){if("function"==typeof e.custom){var i=function(){return e.custom.apply(i,arguments)};i.resolve=e.resolve,i.reject=e.reject,i.call(null,t,n)}else{if(t)return e.reject(t);e.resolve(n)}}function i(e,i){return function(){var s=this,o=Array.prototype.slice.call(arguments);return new Promise(function(r,a){var c=new t(r,a,i);o.push(n.bind(null,c)),e.apply(s,o)})}}"undefined"!=typeof exports&&"undefined"==typeof Promise&&(Promise=require("es6-promise").Promise),e.util.promisify=i}),function(e){"undefined"==typeof exports?e(webduino||{}):module.exports=e}(function(e){"use strict";function t(e){i.call(this)}var n,i=e.EventEmitter,s={OPEN:"open",MESSAGE:"message",ERROR:"error",CLOSE:"close"};t.prototype=n=Object.create(i.prototype,{constructor:{value:t},isOpen:{value:!1}}),n.send=function(e){throw new Error("direct call on abstract method.")},n.close=function(){throw new Error("direct call on abstract method.")},n.flush=function(){throw new Error("direct call on abstract method.")},e.TransportEvent=s,e.Transport=t,e.transport=e.transport||{}}),function(e){"use strict";function t(e){d.call(this,e),this._options=e,this._client=null,this._timer=null,this._sendTimer=null,this._buf=[],this._status="",this._connHandler=i.bind(this),this._connFailedHandler=s.bind(this),this._messageHandler=o.bind(this),this._sendOutHandler=c.bind(this),this._disconnHandler=a.bind(this),n(this)}function n(e){e._client=new Paho.MQTT.Client(e._options.server,"_"+e._options.device+(e._options.multi?"."+_.randomId():"")),e._client.onMessageArrived=e._messageHandler,e._client.onConnectionLost=e._disconnHandler,e._client.onConnected=e._connHandler,e._client.connect({userName:e._options.login||"",password:e._options.password||"",timeout:t.CONNECT_TIMEOUT,keepAliveInterval:t.KEEPALIVE_INTERVAL,onSuccess:e._connHandler,onFailure:e._connFailedHandler,reconnect:!!e._options.autoReconnect,reconnectInterval:t.RECONNECT_PERIOD})}function i(){this._client.subscribe(this._options.device+g.PONG),this._client.subscribe(this._options.device+g.STATUS)}function s(e){this.emit(f.ERROR,new Error(e.errorMessage))}function o(e){var t=e.destinationName,n=this._status;switch(t.substr(t.lastIndexOf("/")+1)){case"STATUS":this._status=e.payloadString,r(this,this._status,n);break;default:this._status===p.OK&&this.emit(f.MESSAGE,e.payloadBytes)}}function r(e,t,n){t!==n&&(t===p.OK?e.emit(f.OPEN):e.emit(f.ERROR,new Error("board connection failed.")))}function a(e){e.errorCode&&e.reconnect||(delete this._client,e.errorCode&&this.emit(f.ERROR,new Error(e.errorMessage)),this.emit(f.CLOSE))}function c(){var e=new Paho.MQTT.Message(new Uint8Array(this._buf).buffer);e.destinationName=this._options.device+g.PING,e.qos=0,this.isOpen&&this._client.send(e),h(this)}function h(e){e._buf=[],clearImmediate(e._sendTimer),e._sendTimer=null}var u,l=Array.prototype.push,d=e.Transport,f=e.TransportEvent,_=e.util,p={OK:"OK"},g={PING:"/PING",PONG:"/PONG",STATUS:"/STATUS"};t.prototype=u=Object.create(d.prototype,{constructor:{value:t},isOpen:{get:function(){return this._client&&this._client.isConnected()}}}),u.send=function(e){this._buf.length+e.length+this._options.device.length+g.PING.length+4>t.MAX_PACKET_SIZE&&this._sendOutHandler(),l.apply(this._buf,e),this._sendTimer||(this._sendTimer=setImmediate(this._sendOutHandler))},u.close=function(){this._client&&(this._client.isConnected()?this._client.disconnect():delete this._client)},u.flush=function(){this._buf&&this._buf.length&&this._sendOutHandler()},t.RECONNECT_PERIOD=1,t.KEEPALIVE_INTERVAL=15,t.CONNECT_TIMEOUT=30,t.MAX_PACKET_SIZE=128,e.transport.mqtt=t}(webduino),function(e){"use strict";function t(e){d.call(this,e),this._options=e,this._client=null,this._sendTimer=null,this._buf=[],this._connHandler=i.bind(this),this._messageHandler=s.bind(this),this._sendOutHandler=a.bind(this),this._disconnHandler=o.bind(this),this._errorHandler=r.bind(this),n(this)}function n(e){var t=e._options.url;e._options.url=0===t.indexOf("ws://")?t:"ws://"+t,e._client=new l(e._options.url),e._client.binaryType="arraybuffer",e._client.onopen=e._connHandler,e._client.onmessage=e._messageHandler,e._client.onclose=e._disconnHandler,e._client.onerror=e._errorHandler}function i(e){this.emit(f.OPEN,e)}function s(e){this.emit(f.MESSAGE,new Uint8Array(e.data))}function o(e){delete this._client,this.emit(f.CLOSE,e)}function r(e){this.emit(f.ERROR,e)}function a(){var e=new Uint8Array(this._buf).buffer;this.isOpen&&this._client.send(e),c(this)}function c(e){e._buf=[],clearImmediate(e._sendTimer),e._sendTimer=null}var h,u=Array.prototype.push,l=WebSocket,d=e.Transport,f=e.TransportEvent;t.prototype=h=Object.create(d.prototype,{constructor:{value:t},isOpen:{get:function(){return this._client&&this._client.readyState===l.OPEN}}}),h.send=function(e){this._buf.length+e.length>t.MAX_PACKET_SIZE&&this._sendOutHandler(),u.apply(this._buf,e),this._sendTimer||(this._sendTimer=setImmediate(this._sendOutHandler))},h.close=function(){this._client&&(this._client.readyState===l.OPEN?this._client.close():delete this._client)},h.flush=function(){this._buf&&this._buf.length&&this._sendOutHandler()},t.MAX_PACKET_SIZE=64,e.transport.websocket=t}(webduino),function(e){"undefined"==typeof exports?e(webduino||{}):module.exports=e}(function(e){"use strict";function t(e,t,s){o.call(this),this._board=e,this._type=s,this._capabilities={},this._number=t,this._analogNumber=void 0,this._analogWriteResolution=255,this._analogReadResolution=1023,this._value=0,this._lastValue=-1,this._preFilterValue=0,this._average=0,this._minimum=Math.pow(2,16),this._maximum=0,this._sum=0,this._numSamples=0,this._filters=null,this._generator=null,this._state=void 0,this._analogReporting=!1,this._sendOutHandler=i.bind(this),this._autoSetValueCallback=this.autoSetValue.bind(this),n(this)}function n(e){var n=e._type;e._board;if(n===t.DOUT||n===t.AOUT||n===t.SERVO)o.listenerCount(e,r.CHANGE)||e.on(r.CHANGE,e._sendOutHandler);else if(o.listenerCount(e,r.CHANGE))try{e.removeListener(r.CHANGE,e._sendOutHandler)}catch(e){debug("debug: caught self removeEventListener exception")}}function i(e){var n=e._type,i=e._number,s=e._board,o=e.value;switch(n){case t.DOUT:s.sendDigitalData(i,o);break;case t.AOUT:s.sendAnalogData(i,o);break;case t.SERVO:s.sendServoData(i,o)}}var s,o=e.EventEmitter,r={CHANGE:"change",RISING_EDGE:"risingEdge",FALLING_EDGE:"fallingEdge"};t.prototype=s=Object.create(o.prototype,{constructor:{value:t},capabilities:{get:function(){return this._capabilities}},analogNumber:{get:function(){return this._analogNumber}},number:{get:function(){return this._number}},analogWriteResolution:{get:function(){return this._analogWriteResolution}},analogReadResolution:{get:function(){return this._analogReadResolution}},state:{get:function(){return this._state},set:function(e){this._type===t.PWM&&(e/=this._analogWriteResolution),this.value=this._value=this._state=e}},type:{get:function(){return this._type}},average:{get:function(){return this._average}},minimum:{get:function(){return this._minimum}},maximum:{get:function(){return this._maximum}},value:{get:function(){return this._value},set:function(e){this._lastValue=this._value,this._preFilterValue=e,this._value=this.applyFilters(e),this.calculateMinMaxAndMean(this._value),this.detectChange(this._lastValue,this._value)}},lastValue:{get:function(){return this._lastValue}},preFilterValue:{get:function(){return this._preFilterValue}},filters:{get:function(){return this._filters},set:function(e){this._filters=e}},generator:{get:function(){return this._generator}}}),s.setAnalogNumber=function(e){this._analogNumber=e},s.setAnalogWriteResolution=function(e){this._analogWriteResolution=e},s.setAnalogReadResolution=function(e){this._analogReadResolution=e},s.setCapabilities=function(e){this._capabilities=e;var n=this._capabilities[t.PWM],i=this._capabilities[t.AIN];n&&(this._analogWriteResolution=Math.pow(2,n)-1),i&&(this._analogReadResolution=Math.pow(2,i)-1)},s.setMode=function(e,i){var s=this._number,o=this._board;e>=0&&e<t.TOTAL_PIN_MODES&&(this._type=e,n(this),i&&!0===i||o.setPinMode(s,e))},s.detectChange=function(e,t){e!==t&&(this.emit(r.CHANGE,this),e<=0&&0!==t?this.emit(r.RISING_EDGE,this):0!==e&&t<=0&&this.emit(r.FALLING_EDGE,this))},s.clearWeight=function(){this._sum=this._average,this._numSamples=1},s.calculateMinMaxAndMean=function(e){var t=Number.MAX_VALUE;this._minimum=Math.min(e,this._minimum),this._maximum=Math.max(e,this._maximum),this._sum+=e,this._average=this._sum/++this._numSamples,this._numSamples>=t&&this.clearWeight()},s.clear=function(){this._minimum=this._maximum=this._average=this._lastValue=this._preFilterValue,this.clearWeight()},s.addFilter=function(e){null!==e&&(null===this._filters&&(this._filters=[]),this._filters.push(e))},s.removeFilter=function(e){var t;this._filters.length<1||-1!==(t=this._filters.indexOf(e))&&this._filters.splice(t,1)},s.addGenerator=function(e){this.removeGenerator(),this._generator=e,this._generator.on("update",this._autoSetValueCallback)},s.removeGenerator=function(){null!==this._generator&&this._generator.removeListener("update",this._autoSetValueCallback),delete this._generator},s.removeAllFilters=function(){delete this._filters},s.autoSetValue=function(e){this.value=e},s.applyFilters=function(e){var t;if(null===this._filters)return e;t=e;for(var n=this._filters.length,i=0;i<n;i++)t=this._filters[i].processSample(t);return t},s.read=function(){var e=this._type,n=this._board,i=this;switch(e){case t.DOUT:case t.AOUT:case t.SERVO:return n.queryPinState(i._number).then(function(e){return e.state});case t.AIN:i._analogReporting||n.enableAnalogPin(i._analogNumber);case t.DIN:return new Promise(function(e){setImmediate(function(){e(i.value)})})}},s.write=function(e){var n=this._type;n!==t.DOUT&&n!==t.AOUT&&n!==t.SERVO||(this.value=e)},t.HIGH=1,t.LOW=0,t.ON=1,t.OFF=0,t.DIN=0,t.DOUT=1,t.AIN=2,t.AOUT=3,t.PWM=3,t.SERVO=4,t.SHIFT=5,t.I2C=6,t.ONEWIRE=7,t.STEPPER=8,t.TOTAL_PIN_MODES=9,e.PinEvent=r,e.Pin=t}),function(e){"undefined"==typeof exports?e(webduino||{}):module.exports=e}(function(e){"use strict";function t(){n.call(this)}var n=e.EventEmitter;t.prototype=Object.create(n.prototype,{constructor:{value:t},type:{get:function(){return this._type}}}),e.Module=t,e.module=e.module||{}}),function(e){"undefined"==typeof exports?e(webduino||{}):module.exports=e}(function(e){"use strict";function t(e){f.call(this),this._options=e,this._buf=[],this._digitalPort=[],this._numPorts=0,this._analogPinMapping=[],this._digitalPinMapping=[],this._i2cPins=[],this._ioPins=[],this._totalPins=0,this._totalAnalogPins=0,this._samplingInterval=19,this._isReady=!1,this._firmwareName="",this._firmwareVersion=0,this._capabilityQueryResponseReceived=!1,this._numPinStateRequests=0,this._transport=null,this._pinStateEventCenter=new f,this._initialVersionResultHandler=n.bind(this),this._openHandler=i.bind(this),this._messageHandler=s.bind(this),this._errorHandler=o.bind(this),this._closeHandler=r.bind(this),this._cleanupHandler=a.bind(this),c(this),this._setTransport(this._options.transport)}function n(e){var t=10*e.version;e.name;if(!(t>=23))throw new Error("You must upload StandardFirmata version 2.3 or greater from Arduino version 1.0 or higher");this.queryCapabilities()}function i(){this.begin()}function s(e){var t=e.length;if(t)for(var n=0;n<t;n++)this.processInput(e[n]);else this.processInput(e)}function o(e){this._isReady=!1,this.emit(m.ERROR,e),setImmediate(this.disconnect.bind(this))}function r(){this._isReady=!1,this._transport.removeAllListeners(),delete this._transport,this.emit(m.DISCONNECT)}function a(){this.disconnect(function(){"undefined"!=typeof exports&&process.exit()})}function c(e){"undefined"==typeof exports?window.addEventListener("beforeunload",e._cleanupHandler):(process.addListener("SIGINT",e._cleanupHandler),process.addListener("uncaughtException",e._cleanupHandler))}function h(e){"undefined"==typeof exports?window.removeEventListener("beforeunload",e._cleanupHandler):(process.removeListener("SIGINT",e._cleanupHandler),process.removeListener("uncaughtException",e._cleanupHandler))}function u(e){console&&console.log(e.stack||e)}var l,d=Array.prototype.push,f=e.EventEmitter,_=e.TransportEvent,p=(e.Transport,e.Pin),g=e.util,m={ANALOG_DATA:"analogData",DIGITAL_DATA:"digitalData",FIRMWARE_VERSION:"firmwareVersion",FIRMWARE_NAME:"firmwareName",STRING_MESSAGE:"stringMessage",SYSEX_MESSAGE:"sysexMessage",PIN_STATE_RESPONSE:"pinStateResponse",READY:"ready",ERROR:"error",BEFOREDISCONNECT:"beforeDisconnect",DISCONNECT:"disconnect"};t.prototype=l=Object.create(f.prototype,{constructor:{value:t},samplingInterval:{get:function(){return this._samplingInterval},set:function(e){if(!(e>=t.MIN_SAMPLING_INTERVAL&&e<=t.MAX_SAMPLING_INTERVAL))throw new Error("warning: Sampling interval must be between "+t.MIN_SAMPLING_INTERVAL+" and "+t.MAX_SAMPLING_INTERVAL);this._samplingInterval=e,this.send([240,122,127&e,e>>7&127,247])}},isReady:{get:function(){return this._isReady}},isConnected:{get:function(){return this._transport&&this._transport.isOpen}}}),l.begin=function(){this.once(m.FIRMWARE_NAME,this._initialVersionResultHandler),this.reportFirmware()},l.processInput=function(e){var t,n;this._buf.push(e),t=this._buf.length,n=this._buf[0],n>=128&&240!==n?3===t&&(this.processMultiByteCommand(this._buf),this._buf=[]):240===n&&247===e?(this.processSysexCommand(this._buf),this._buf=[]):e>=128&&n<128&&(this._buf=[],247!==e&&this._buf.push(e))},l.processMultiByteCommand=function(e){var t,n=e[0];switch(n<240&&(n&=240,t=15&e[0]),n){case 144:this.processDigitalMessage(t,e[1],e[2]);break;case 249:this._firmwareVersion=e[1]+e[2]/10,this.emit(m.FIRMWARE_VERSION,{version:this._firmwareVersion});break;case 224:this.processAnalogMessage(t,e[1],e[2])}},l.processDigitalMessage=function(e,t,n){var i,s=8*e,o=s+8,r=t|n<<7,a={};o>=this._totalPins&&(o=this._totalPins);for(var c=0,h=s;h<o;h++){if(void 0===(a=this.getDigitalPin(h)))return;a.type===p.DIN&&(i=r>>c&1)!==a.value&&(a.value=i,this.emit(m.DIGITAL_DATA,{pin:a})),c++}},l.processAnalogMessage=function(e,t,n){var i=this.getAnalogPin(e);void 0!==i&&(i.value=this.getValueFromTwo7bitBytes(t,n)/i.analogReadResolution,i.value!==i.lastValue&&(this._isReady&&(i._analogReporting=!0),this.emit(m.ANALOG_DATA,{pin:i})))},l.processSysexCommand=function(e){switch(e.shift(),e.pop(),e[0]){case 121:this.processQueryFirmwareResult(e);break;case 113:this.processSysExString(e);break;case 108:this.processCapabilitiesResponse(e);break;case 110:this.processPinStateResponse(e);break;case 106:this.processAnalogMappingResponse(e);break;default:this.emit(m.SYSEX_MESSAGE,{message:e})}},l.processQueryFirmwareResult=function(e){for(var t,n=3,i=e.length;n<i;n+=2)t=e[n],t+=e[n+1],this._firmwareName+=String.fromCharCode(t);this._firmwareVersion=e[1]+e[2]/10,this.emit(m.FIRMWARE_NAME,{name:this._firmwareName,version:this._firmwareVersion})},l.processSysExString=function(e){for(var t,n="",i=e.length,s=1;s<i;s+=2)t=e[s],t+=e[s+1],n+=String.fromCharCode(t);this.emit(m.STRING_MESSAGE,{message:n})},l.processCapabilitiesResponse=function(e){var t,n,i={},s=1,o=0,r=0,a=e.length;for(this._capabilityQueryResponseReceived=!0;s<=a;)127===e[s]?(this._digitalPinMapping[o]=o,t=void 0,i[p.DOUT]&&(t=p.DOUT),i[p.AIN]&&(t=p.AIN,this._analogPinMapping[r++]=o),n=new p(this,o,t),n.setCapabilities(i),this._ioPins[o]=n,n._capabilities[p.I2C]&&this._i2cPins.push(n.number),i={},o++,s++):(i[e[s]]=e[s+1],s+=2);this._numPorts=Math.ceil(o/8);for(var c=0;c<this._numPorts;c++)this._digitalPort[c]=0;this._totalPins=o,this._totalAnalogPins=r,this.queryAnalogMapping()},l.processAnalogMappingResponse=function(e){for(var t=e.length,n=1;n<t;n++)127!==e[n]&&(this._analogPinMapping[e[n]]=n-1,this.getPin(n-1).setAnalogNumber(e[n]));this.startup()},l.startup=function(){this.enableDigitalPins(),setTimeout(function(){this._isReady=!0,this.emit(m.READY,this)}.bind(this),2e3)},l.systemReset=function(){this.send([255])},l.processPinStateResponse=function(e){if(!(this._numPinStateRequests<=0)){var t,n=e.length,i=e[1],s=e[2],o=this._ioPins[i];n>4?t=this.getValueFromTwo7bitBytes(e[3],e[4]):n>3&&(t=e[3]),o.type!==s&&o.setMode(s,!0),o.state=t,this._numPinStateRequests--,this._numPinStateRequests<0&&(this._numPinStateRequests=0),this._pinStateEventCenter.emit(i,o),this.emit(m.PIN_STATE_RESPONSE,{pin:o})}},l.toDec=function(e){return e=e.substring(0,1),e.charCodeAt(0)},l.sendAnalogData=function(e,t){var n=this.getDigitalPin(e).analogWriteResolution;t*=n,t=t<0?0:t,t=t>n?n:t,e>15||t>Math.pow(2,14)?this.sendExtendedAnalogData(e,t):this.send([224|15&e,127&t,t>>7&127])},l.sendExtendedAnalogData=function(e,t){var n=[];if(t>Math.pow(2,16))throw new Error("Extended Analog values > 16 bits are not currently supported by StandardFirmata");n[0]=240,n[1]=111,n[2]=e,n[3]=127&t,n[4]=t>>7&127,t>=Math.pow(2,14)&&(n[5]=t>>14&127),n.push(247),this.send(n)},l.sendDigitalData=function(e,t){var n=Math.floor(e/8);if(t===p.HIGH)this._digitalPort[n]|=t<<e%8;else{if(t!==p.LOW)throw new Error("Invalid value passed to sendDigital, value must be 0 or 1.");this._digitalPort[n]&=~(1<<e%8)}this.sendDigitalPort(n,this._digitalPort[n])},l.sendServoData=function(e,t){var n=this.getDigitalPin(e);n.type===p.SERVO&&n.lastValue!==t&&this.sendAnalogData(e,t)},l.queryCapabilities=function(){this.send([240,107,247])},l.queryAnalogMapping=function(){this.send([240,105,247])},l.getValueFromTwo7bitBytes=function(e,t){return t<<7|e},l.getTransport=function(){return this._transport},l._setTransport=function(t){var n=t;"string"==typeof t&&(n=e.transport[t]),n&&(t=new n(this._options))&&(t.on(_.OPEN,this._openHandler),t.on(_.MESSAGE,this._messageHandler),t.on(_.ERROR,this._errorHandler),t.on(_.CLOSE,this._closeHandler),this._transport=t)},l.reportVersion=function(){this.send(249)},l.reportFirmware=function(){this.send([240,121,247])},l.enableDigitalPins=function(){for(var e=0;e<this._numPorts;e++)this.sendDigitalPortReporting(e,p.ON)},l.disableDigitalPins=function(){for(var e=0;e<this._numPorts;e++)this.sendDigitalPortReporting(e,p.OFF)},l.sendDigitalPortReporting=function(e,t){this.send([208|e,t])},l.enableAnalogPin=function(e){this.sendAnalogPinReporting(e,p.ON),this.getAnalogPin(e)._analogReporting=!0},l.disableAnalogPin=function(e){this.sendAnalogPinReporting(e,p.OFF),this.getAnalogPin(e)._analogReporting=!1},l.sendAnalogPinReporting=function(e,t){this.send([192|e,t])},l.setDigitalPinMode=function(e,t,n){this.getDigitalPin(e).setMode(t,n)},l.setAnalogPinMode=function(e,t,n){this.getAnalogPin(e).setMode(t,n)},l.setPinMode=function(e,t){this.send([244,e,t])},l.enablePullUp=function(e){this.sendDigitalData(e,p.HIGH)},l.getFirmwareName=function(){return this._firmwareName},l.getFirmwareVersion=function(){return this._firmwareVersion},l.getPinCapabilities=function(){var e,t,n,i,s=[],o={0:"input",1:"output",2:"analog",3:"pwm",4:"servo",5:"shift",6:"i2c",7:"onewire",8:"stepper"};e=this._ioPins.length;for(var r=0;r<e;r++){t={},n=this._ioPins[r]._capabilities,i=!1;for(var a in n)n.hasOwnProperty(a)&&(i=!0,a>=0&&(t[o[a]]=this._ioPins[r]._capabilities[a]));s[r]=i?t:{"not available":"0"}}return s},l.queryPinState=function(e,t){var n,i=this,s=[],o=[];if(n=i._pinStateEventCenter.once.bind(i._pinStateEventCenter),e=g.isArray(e)?e:[e],e=e.map(function(e){return e instanceof p?e:i.getPin(e)}),e.forEach(function(e){s.push(g.promisify(n,function(e){this.resolve(e)})(e.number)),d.apply(o,[240,109,e.number,247]),i._numPinStateRequests++}),i.send(o),"function"!=typeof t)return e.length>1?s:s[0];Promise.all(s).then(function(e){t.call(i,e.length>1?e:e[0])})},l.sendDigitalPort=function(e,t){this.send([144|15&e,127&t,t>>7])},l.sendString=function(e){for(var t=[],n=0,i=e.length;n<i;n++)t.push(127&this.toDec(e[n])),t.push(this.toDec(e[n])>>7&127);this.sendSysex(113,t)},l.sendSysex=function(e,t){var n=[];n[0]=240,n[1]=e;for(var i=0,s=t.length;i<s;i++)n.push(t[i]);n.push(247),this.send(n)},l.sendServoAttach=function(e,t,n){var i,s=[];t=t||544,n=n||2400,s[0]=240,s[1]=112,s[2]=e,s[3]=t%128,s[4]=t>>7,s[5]=n%128,s[6]=n>>7,s[7]=247,this.send(s),i=this.getDigitalPin(e),i.setMode(p.SERVO,!0)},l.getPin=function(e){return this._ioPins[e]},l.getAnalogPin=function(e){return this._ioPins[this._analogPinMapping[e]]},l.getDigitalPin=function(e){return this._ioPins[this._digitalPinMapping[e]]},l.getPins=function(){return this._ioPins},l.analogToDigital=function(e){return this.getAnalogPin(e).number},l.getPinCount=function(){return this._totalPins},l.getAnalogPinCount=function(){return this._totalAnalogPins},l.getI2cPins=function(){return this._i2cPins},l.reportCapabilities=function(){for(var e,t=this.getPinCapabilities(),n=t.length,i=0;i<n;i++){u("Pin "+i+":");for(var s in t[i])t[i].hasOwnProperty(s)&&(e=t[i][s],u("\t"+s+" ("+e+(e>1?" bits)":" bit)")))}},l.send=function(e){this.isConnected&&this._transport.send(e)},l.close=function(e){this.disconnect(e)},l.flush=function(){this.isConnected&&this._transport.flush()},l.disconnect=function(e){e=e||function(){},this.isConnected&&this.emit(m.BEFOREDISCONNECT),this._isReady=!1,h(this),this._transport?this._transport.isOpen?(this.once(m.DISCONNECT,e),this._transport.close()):(this._transport.removeAllListeners(),delete this._transport,e()):e()},t.MIN_SAMPLING_INTERVAL=20,t.MAX_SAMPLING_INTERVAL=15e3,e.BoardEvent=m,e.Board=t,e.board=e.board||{}}),function(e){"undefined"==typeof exports?e(webduino||{}):module.exports=e}(function(e){"use strict";function t(e){"string"==typeof e&&(e={device:e}),e=r.extend(n(e),e),e.server=i(e.server),c.call(this,e)}function n(e){return{transport:"mqtt",server:t.DEFAULT_SERVER,login:"admin",password:"password",autoReconnect:!1,multi:!1}}function i(e){return-1===e.indexOf("://")&&(e=("undefined"!=typeof location&&"https:"===location.protocol?"wss:":"ws:")+"//"+e),e=r.parseURL(e),e.protocol+"//"+e.host+"/"}function s(e,t){e._transport.emit(a.MESSAGE,t)}var o,r=e.util,a=e.TransportEvent,c=e.Board;t.prototype=o=Object.create(c.prototype,{constructor:{value:t}}),o.reportFirmware=function(){s(this,[240,121,2,4,119,0,101,0,98,0,100,0,117,0,105,0,110,0,111,0,46,0,105,0,110,0,111,0,247])},o.queryCapabilities=function(){s(this,[240,108,127,127,0,1,1,1,4,14,127,0,1,1,1,3,8,4,14,127,0,1,1,1,4,14,127,0,1,1,1,3,8,4,14,127,0,1,1,1,3,8,4,14,127,0,1,1,1,4,14,127,0,1,1,1,4,14,127,0,1,1,1,3,8,4,14,127,0,1,1,1,3,8,4,14,127,0,1,1,1,3,8,4,14,127,0,1,1,1,4,14,127,0,1,1,1,4,14,127,0,1,1,1,2,10,4,14,127,0,1,1,1,2,10,4,14,127,0,1,1,1,2,10,4,14,127,0,1,1,1,2,10,4,14,127,0,1,1,1,2,10,4,14,127,0,1,1,1,2,10,4,14,127,2,10,127,2,10,127,247])},o.queryAnalogMapping=function(){s(this,[240,106,127,127,127,127,127,127,127,127,127,127,127,127,127,127,0,1,2,3,4,5,6,7,247])},t.DEFAULT_SERVER="wss://ws.webduino.io:443",e.WebArduino=t}),function(e){"undefined"==typeof exports?e(webduino||{}):module.exports=e}(function(e){"use strict";function t(e){"string"==typeof e&&(e={transport:"serial",path:e}),e=s.extend(n(e),e),o.call(this,e)}function n(e){return{serial:{transport:"serial",baudRate:57600},bluetooth:{transport:"bluetooth",uuid:"1101"}}[e.transport]||{}}var i,s=e.util,o=e.Board,r=e.BoardEvent;t.prototype=i=Object.create(o.prototype,{constructor:{value:t}}),i.begin=function(){this.once(r.FIRMWARE_NAME,this._initialVersionResultHandler),"serial"!==this._options.transport&&this.reportFirmware()},e.Arduino=t});var chrome=chrome||{};chrome._api=function(e){"use strict";function t(e){return function(){var t=o.call(arguments),n=++c+"";"function"==typeof t[t.length-1]&&(r[n]=t.pop()),s(n,e,t)}}function n(e){return function(t){var n=++c+"";"function"==typeof t&&(a[n]=t,s(n,e,[]))}}function i(e){return function(t){Object.keys(a).some(function(n){if(a[n]===t)return delete a[n],s(n,e,[]),!0})}}function s(t,n,i){delete chrome.runtime.lastError,e.postMessage({jsonrpc:"2.0",id:t,method:n,params:i},e.location.origin)}var o=Array.prototype.slice,r={},a={},c=0;return e.addEventListener("message",function(e){var t=e.data;if(t.jsonrpc&&!t.method){if(t.exception)throw r[t.id]&&delete r[t.id],new Error(t.exception);t.error&&(chrome.runtime.lastError={message:t.error}),r[t.id]?(r[t.id].apply(void 0,t.result),
delete r[t.id]):a[t.id]&&a[t.id].apply(void 0,t.result)}},!1),{proxyRequest:t,proxyAddListener:n,proxyRemoveListener:i}}(window),chrome.runtime=chrome.runtime||{},chrome.serial=chrome.serial||function(e){"use strict";var t=Array.prototype.slice,n=e.proxyRequest,i=e.proxyAddListener,s=e.proxyRemoveListener,o=n("chrome.serial.send");return{getDevices:n("chrome.serial.getDevices"),connect:n("chrome.serial.connect"),update:n("chrome.serial.update"),disconnect:n("chrome.serial.disconnect"),setPaused:n("chrome.serial.setPaused"),getInfo:n("chrome.serial.getInfo"),getConnections:n("chrome.serial.getConnections"),send:function(e,n,i){o.apply(void 0,[e,t.call(new Uint8Array(n)),i])},flush:n("chrome.serial.flush"),getControlSignals:n("chrome.serial.getControlSignals"),setControlSignals:n("chrome.serial.setControlSignals"),setBreak:n("chrome.serial.setBreak"),clearBreak:n("chrome.serial.clearBreak"),onReceive:{addListener:i("chrome.serial.onReceive.addListener"),removeListener:s("chrome.serial.onReceive.removeListener")},onReceiveError:{addListener:i("chrome.serial.onReceiveError.addListener"),removeListener:s("chrome.serial.onReceiveError.removeListener")}}}(chrome._api),function(e){"use strict";function t(e){d.call(this,e),this._options=e,this._connectionId=null,this._sendTimer=null,this._buf=[],this._connHandler=i.bind(this),this._messageHandler=s.bind(this),this._sendOutHandler=a.bind(this),this._disconnHandler=o.bind(this),this._errorHandler=r.bind(this),n(this)}function n(e){var t=e._options;l.onReceive.addListener(e._messageHandler),l.onReceiveError.addListener(e._errorHandler),l.connect(t.path,{bitrate:t.baudRate},e._connHandler)}function i(e){this._connectionId=e.connectionId,this.emit(f.OPEN)}function s(e){e.connectionId===this._connectionId&&this.emit(f.MESSAGE,e.data)}function o(e){l.onReceive.removeListener(this._messageHandler),l.onReceiveError.removeListener(this._errorHandler),delete this._connectionId,this.emit(f.CLOSE)}function r(e){this.emit(f.ERROR,new Error(JSON.stringify(e)))}function a(){var e=new Uint8Array(this._buf).buffer;this.isOpen&&l.send(this._connectionId,e),c(this)}function c(e){e._buf=[],clearImmediate(e._sendTimer),e._sendTimer=null}var h,u=Array.prototype.push,l=chrome.serial,d=e.Transport,f=e.TransportEvent;t.prototype=h=Object.create(d.prototype,{constructor:{value:t},isOpen:{get:function(){return!!this._connectionId}}}),h.send=function(e){u.apply(this._buf,e),this._sendTimer||(this._sendTimer=setImmediate(this._sendOutHandler))},h.close=function(){this._connectionId&&l.disconnect(this._connectionId,this._disconnHandler)},e.transport.serial=t}(webduino),chrome.bluetooth=chrome.bluetooth||function(e){"use strict";var t=e.proxyRequest;return{getAdapterState:t("chrome.bluetooth.getAdapterState"),getDevice:t("chrome.bluetooth.getDevice"),getDevices:t("chrome.bluetooth.getDevices"),startDiscovery:t("chrome.bluetooth.startDiscovery"),stopDiscovery:t("chrome.bluetooth.stopDiscovery")}}(chrome._api),chrome.bluetoothSocket=chrome.bluetoothSocket||function(e){"use strict";var t=Array.prototype.slice,n=e.proxyRequest,i=e.proxyAddListener,s=e.proxyRemoveListener,o=n("chrome.bluetoothSocket.send");return{create:n("chrome.bluetoothSocket.create"),connect:n("chrome.bluetoothSocket.connect"),update:n("chrome.bluetoothSocket.update"),disconnect:n("chrome.bluetoothSocket.disconnect"),close:n("chrome.bluetoothSocket.close"),setPaused:n("chrome.bluetoothSocket.setPaused"),getInfo:n("chrome.bluetoothSocket.getInfo"),getSockets:n("chrome.bluetoothSocket.getSockets"),send:function(e,n,i){o.apply(void 0,[e,t.call(new Uint8Array(n)),i])},listenUsingRfcomm:n("chrome.bluetoothSocket.listenUsingRfcomm"),listenUsingL2cap:n("chrome.bluetoothSocket.listenUsingL2cap"),onAccept:{addListener:i("chrome.bluetoothSocket.onAccept.addListener"),removeListener:s("chrome.bluetoothSocket.onAccept.removeListener")},onAcceptError:{addListener:i("chrome.bluetoothSocket.onAcceptError.addListener"),removeListener:s("chrome.bluetoothSocket.onAcceptError.removeListener")},onReceive:{addListener:i("chrome.bluetoothSocket.onReceive.addListener"),removeListener:s("chrome.bluetoothSocket.onReceive.removeListener")},onReceiveError:{addListener:i("chrome.bluetoothSocket.onReceiveError.addListener"),removeListener:s("chrome.bluetoothSocket.onReceiveError.removeListener")}}}(chrome._api),function(e){"use strict";function t(e){d.call(this,e),this._options=e,this._socketId=null,this._sendTimer=null,this._buf=[],this._messageHandler=s.bind(this),this._sendOutHandler=a.bind(this),this._disconnHandler=o.bind(this),this._errorHandler=r.bind(this),n(this)}function n(e){var s=e._options;i(s.address,function(i,o){i||!o?e.emit(f.ERROR,new Error(i)):(l.onReceive.addListener(e._messageHandler),l.onReceiveError.addListener(e._errorHandler),l.connect(o,s.address,s.uuid,function(){chrome.runtime.lastError?(console.log(chrome.runtime.lastError.message),l.close(o,function(){l.onReceive.removeListener(e._messageHandler),l.onReceiveError.removeListener(e._errorHandler),++_<=t.MAX_RETRIES?n(e):e.emit(f.ERROR,new Error("too many retries"))})):(_=0,e._socketId=o,e.emit(f.OPEN))}))})}function i(e,t){var n;chrome.bluetooth.getAdapterState(function(i){i.available?chrome.bluetooth.getDevice(e,function(i){i?l.getSockets(function(e){e.some(function(e){if(!e.connected)return n=e.socketId,!0}),void 0===n?l.create(function(e){t(null,e.socketId)}):t(null,n)}):t('No such device "'+e+'"')}):t("Bluetooth adapter not available")})}function s(e){e.socketId===this._socketId&&this.emit(f.MESSAGE,e.data)}function o(){l.onReceive.removeListener(this._messageHandler),l.onReceiveError.removeListener(this._errorHandler),delete this._socketId,this.emit(f.CLOSE)}function r(e){this.emit(f.ERROR,new Error(JSON.stringify(e)))}function a(){var e=new Uint8Array(this._buf).buffer;this.isOpen&&l.send(this._socketId,e),c(this)}function c(e){e._buf=[],clearImmediate(e._sendTimer),e._sendTimer=null}var h,u=Array.prototype.push,l=chrome.bluetoothSocket,d=e.Transport,f=e.TransportEvent,_=0;t.prototype=h=Object.create(d.prototype,{constructor:{value:t},isOpen:{get:function(){return!!this._socketId}}}),h.send=function(e){u.apply(this._buf,e),this._sendTimer||(this._sendTimer=setImmediate(this._sendOutHandler))},h.close=function(){this._socketId&&l.close(this._socketId,this._disconnHandler)},t.MAX_RETRIES=10,e.transport.bluetooth=t}(webduino);