blueapp.io
Version:
BlueApp.io library to connect to remote Bluetooth devices.
1 lines • 88.4 kB
JavaScript
!function a(o,s,c){function u(t,e){if(!s[t]){if(!o[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(l)return l(t,!0);var n=new Error("Cannot find module '"+t+"'");throw n.code="MODULE_NOT_FOUND",n}var i=s[t]={exports:{}};o[t][0].call(i.exports,function(e){return u(o[t][1][e]||e)},i,i.exports,a,o,s,c)}return s[t].exports}for(var l="function"==typeof require&&require,e=0;e<c.length;e++)u(c[e]);return u}({1:[function(m,e,t){!function(){for(var e,t=/\+/g,r=/([^&=]+)=?([^&]*)/g,n=function(e){return decodeURIComponent(e.replace(t," "))},i=window.location.search.substring(1),a={},o=void 0,s=void 0,c={};e=r.exec(i);)a[n(e[1])]=n(e[2]);var u=a.token,l=a.uuid,f=a.proxyUrl,p="true"==a.app;window.wbDialogCancel=function(e){var t=document.getElementById("wb-pf-picker");t&&(t.style.display="none"),s&&clearTimeout(s),o&&o(e)};var d=function(e){e.peripheral?function(e){clearTimeout(s),c[e.uuid]=e;var t='<table cellpadding="0" cellspacing="0"><tbody><tr>';for(var r in c)t+="</tr><tr onclick='onPeripheralSelect(\""+r+"\")'>",t+="<td>"+c[r].name+"</td>";document.getElementById("wb-pf-peripheral").innerHTML=t}(e.peripheral):(o=e.reject,function(t){var e=document.createElement("div");e.setAttribute("id","wb-pf-peripheral");var r=document.createElement("div");r.setAttribute("id","wb-pf-scanDialog");var n=document.createElement("div");n.setAttribute("id","wb-pf-picker"),n.appendChild(e),document.body.appendChild(r),document.body.appendChild(n),c={},window.onPeripheralSelect=function(e){document.getElementById("wb-pf-picker").style.display="none",t(c[e])},s=setTimeout(function(){console.log("Requested device not found :("),window.wbDialogCancel("Requested device not found!")},6e4),document.getElementById("wb-pf-scanDialog").innerHTML='<style>.modal { display: block; position: fixed; z-index: 1; padding-top: 100px; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0.4);}.modal-content { background-color: #fefefe; margin: auto; padding: 20px; border: 1px solid #888; width: 80%;}@media screen and (max-width: 680px) {.modal-content {width: 80%;}}.spacing-table td { border-width: 3px 0; padding: 10px 10px;}.div-border { border-collapse: collapse; border: 1px solid #b5aeae;;}tr:hover { background: #dddddd !important;}</style><div id= "wb-pf-picker" style= "z-index: 100;" class= "modal"> <div class= "modal-content"> <div style="font-size: 15px; padding-bottom: 10px; color: black"> App wants to pair with : </div> <div class= "spacing-table div-border" style="color: black" id=\'wb-pf-peripheral\'> </div> <div style="text-align: right; margin-top: 10px; font-size: 14px;"> <button type= "button" onclick= "window.wbDialogCancel(\'Scan stopped!\')" style="padding: 4px;">Cancel</button> </div> </div></div>'}(e.select))},h=function(){if("object"==typeof window.bawb)return window.bawb;var r,e;if("scan"===l&&(e=d,l=void 0),p){e=d;var t=function(e){r.onerror&&r.onerror(e)},n=function(e){if(e&&r.onmessage){var t={data:e};r.onmessage(t)}};(r={}).close=function(){blueappio.request("close",void 0,n,t)},r.send=function(e){blueappio.request("message",e,n,t)},blueappio.request("init",{},n,t)}return window.BlueAppWebBluetooth=m("blueapp-wb"),window.bawbConfig={url:f,token:u,scanFilters:{uuids:[l]},stream:r,returnData:e,errorCallback:window.wbDialogCancel},window.bawb=window.BlueAppWebBluetooth.init(window.bawbConfig).navigator.bluetooth,window.bawb};function v(){Object.defineProperty?Object.defineProperty(navigator,"bluetooth",{get:h}):Object.prototype.__defineGetter__&&navigator.__defineGetter__("bluetooth",h);navigator.bluetooth}"object"==typeof navigator?p?document.addEventListener("deviceready",v,!1):u&&v():console.log("Browser does not support the navigator object")}()},{"blueapp-wb":7}],2:[function(e,t,r){var d=e("./util.js"),h=e("./wb-device").BluetoothDevice,v=e("./wb-filters"),m=e("./wb-advertisement");t.exports.BluetoothLEScan=function(e,r,n,t,i){var a=this,o=!1,s=t.filters,c=t.keepRepeatedDevices,u=t.acceptAllAdvertisements,l=r.getGateway(),f=d.hashCode(JSON.stringify(t));function p(e){var t;(t=n?v.filterScan(r,e,a.filters).peripheral:e)&&(e._wbBluetoothDevice||(e._wbBluetoothDevice={}),e._wbBluetoothDevice[f]||(e._wbBluetoothDevice[f]=new h(r,t)),i.emit("advertisementreceived",new m.BluetoothAdvertisingEvent(t,e._wbBluetoothDevice[f])))}Object.defineProperty(a,"active",{get:function(){return o}}),Object.defineProperty(a,"filters",{get:function(){return s}}),Object.defineProperty(a,"keepRepeatedDevices",{get:function(){return c}}),Object.defineProperty(a,"acceptAllAdvertisements",{get:function(){return u}}),a.stop=function(){o=!1,l.removeListener("scan",p),console.log("Stop scan requested"),l.stopScan(function(){})},a._handleScan=function(e,t){l.scan({fulfill:function(){e(a),o=!0,l.on("scan",p)},reject:t})}}},{"./util.js":27,"./wb-advertisement":28,"./wb-device":31,"./wb-filters":33}],3:[function(e,t,r){var n=e("events"),i=e("util");t.exports.makeEmitter=function(e){i.inherits(e,n)},t.exports.instantiateEmitter=function(e){n.call(e)}},{events:37,util:41}],4:[function(e,t,r){var s=e("./util");function c(e,t,r){var n=e.match(/.{1,2}/g);if(!(n.length>=t.length))return!1;for(var i=0;i<t.length;i++)if((t[i]&r[i])!=(parseInt(n[i],16)&r[i]))return!1;return!0}t.exports.nameFilter=function(e,t){return!e.name||e.name===t.name},t.exports.namePrefixFilter=function(e,t){return!e.namePrefix||-1<t.name.indexOf(e.namePrefix)},t.exports.servicesFilter=function(e,t,r){if(t.services){for(var n=!0,i=0;i<t.services.length;i++){s.toVensiUUID(e.BluetoothUUID.getService(t.services[i]));-1===r.serviceUUIDs.indexOf(s.toVensiUUID(e.BluetoothUUID.getService(t.services[i])))&&(n=!1)}return n}return!0},t.exports.manufacturerDataFilter=function(e,t){if(e.manufacturerData){if(s.isEmpty(e.manufacturerData))return!1;var r=t.getAllMfrData();for(var n in e.manufacturerData)if(e.manufacturerData.hasOwnProperty(n)){for(var i=parseInt(n,10).toString(16).toUpperCase(),a=i.length;a<4;a++)i="0"+i;if("string"!=typeof r[i])return!1;if(!s.isEmpty(e.manufacturerData[n])&&"mask"in e.manufacturerData[n]){if(0==c(r[i],e.manufacturerData[n].dataPrefix,e.manufacturerData[n].mask))return!1}else{var o=s.arrayAsHex(e.manufacturerData[n].dataPrefix);if(0!=r[i].indexOf(o))return!1}}return!0}return!0},t.exports.serviceDataFilter=function(e,t){if(e.serviceData){var r=t.getAllSvcData();if(s.isEmpty(e.serviceData))return!1;for(var n in e.serviceData)if(e.serviceData.hasOwnProperty(n)){if(!r.hasOwnProperty(n))return!1;if(!s.isEmpty(e.serviceData[n]))return!1}return!0}return!0}},{"./util":27}],5:[function(e,t,r){var m=e("./util"),c=e("./wb-errors"),g=e("./wb-errors").errors;function _(e,t){var r,n,i,a={};if(0!=t.length)for(var o=0;o<t.length;o++){var s=t[o];if(r=e,i=!(i=void 0),"string"==typeof(n=s)?m.isHex(n)?m.isLowercase(n)||(i=!1):m.toVensiUUID(r.BluetoothUUID.getService(n))||(i=!1):"number"!=typeof n&&(i=!1),!i)return a={error:!0,message:c.invalidServiceUUIDMessage(s)}}else a={error:!0,message:"Illegal filter object"};return a}function b(e){return"object"!=typeof e.manufacturerData||m.isEmpty(e.manufacturerData)||!function(e){for(var t in e.manufacturerData)if(e.manufacturerData.hasOwnProperty(t)){if(!(m.stringIsInteger(t)&&null!=t&&0<t&&t<65535))return!1;if("object"!=typeof e.manufacturerData[t]||!(m.isEmpty(e.manufacturerData[t])||"dataPrefix"in e.manufacturerData[t]))return!1;if("dataPrefix"in e.manufacturerData[t]){if(e.manufacturerData[t].dataPrefix instanceof Uint8Array==0)return!1;if("mask"in e.manufacturerData[t]){if(e.manufacturerData[t].mask instanceof Uint8Array==0)return!1;if(e.manufacturerData[t].dataPrefix.byteLength!=e.manufacturerData[t].mask.byteLength)return!1}}}return!0}(e)?{error:!0,message:g.INVALID_MFR_DATA_FORMAT}:{}}function y(e){return"object"!=typeof e.serviceData||m.isEmpty(e.serviceData)||!function(e){for(var t in e.serviceData)if(e.serviceData.hasOwnProperty(t)&&!m.isEmpty(e.serviceData[t]))return!1;return!0}(e)?{error:!0,message:g.INVALID_SERVICE_DATA_FORMAT}:{}}t.exports.validateFilters=function(e,t,r,n){var i,a,o,s,c,u=4==arguments.length,l=(a=r,o=u,(i=t)&&0<i.length&&a?o?{error:!0,message:g.INVALID_OPTIONS_ERROR_MESSAGE}:{error:!0,message:g.INVALID_LESCAN_OPTIONS_ERROR_MESSAGE}:i&&0!=i.length||!a?i||a?{error:!1,isFiltering:!0}:o?{error:!0,message:g.INVALID_OPTIONS_ERROR_MESSAGE}:{error:!0,message:g.INVALID_LESCAN_OPTIONS_ERROR_MESSAGE}:{error:!1,isFiltering:!1});if(l.error)return l;if(l.isFiltering)for(var f=0;f<t.length;f++){var p=t[f];for(var d in p)if(p.hasOwnProperty(d)&&null!=p[d]){var h;switch(d){case"services":h=_(e,p.services);break;case"name":h="string"!=typeof(c=p).name||248<m.getUTF8Length(c.name)?{error:!0,message:g.INVALID_NAME_ERROR_MESSAGE}:{};break;case"namePrefix":h=0==(s=p).namePrefix.length||"string"!=typeof s.namePrefix||248<m.getUTF8Length(s.namePrefix)?{error:!0,message:g.INVALID_NAME_PREFIX_ERROR_MESSAGE}:{};break;case"manufacturerData":h=b(p);break;case"serviceData":h=y(p);break;default:h={error:!0,message:"Illegal filter object"}}if(h.error)return h}}if(n){var v=_(e,n);if(v.error)return v}return l}},{"./util":27,"./wb-errors":32}],6:[function(e,t,r){t.exports.getGateway=function(r){function n(r){void 0===r._scanRefCount&&(r._scan=r.scan,r._stopScan=r.stopScan,r._scanRefCount=0,r.scan=function(e){r._scanRefCount++,1===r._scanRefCount&&console.log("Scan initiated"),r._scan(e)},r.stopScan=function(e){var t;r._scanRefCount--,0===r._scanRefCount?(console.log("Scan terminated"),r._stopScan(e)):"function"==typeof(t=e)?t():"function"==typeof t.fulfill&&t.fulfill()})}return new Promise(function(t,e){r.getGateway()?(n(r.getGateway()),t(r.getGateway())):r.once("ready",function(e){n(e),t(e)})})}},{}],7:[function(e,t,r){"use strict";var n=e("gatt-ip-js").GATTIP,i=e("./thirdparty"),g=e("./wb-device").BluetoothDevice,_=e("./wb-filters"),b=e("./filter-validation"),a=e("events"),o=e("./task").RetryingTask,u=e("./bluetooth-le-scan").BluetoothLEScan,y=e("./gateway-wrapper").getGateway,w=e("./util");function s(h){var t,v,s=this,c=new a.EventEmitter,r=!1;function e(){v&&(console.log("Retrying connection to gateway..."),v.close(),v=void 0),(v=s.gattip=new n).BluetoothUUID=i.BluetoothUUID,v.once("onclose",function(e){c.removeAllListeners("advertisementreceived"),t&&(console.log("Gateway socket closed. Scheduling retries..."),t.schedule()),r&&(r=!1,c.emit("availabilitychanged",{value:r})),v.removeAllListeners(),v.getGateway()&&v.getGateway().removeAllListeners()}),v.once("ready",function(e){t&&(t.stop(),t.schedule()),r||(r=!0,c.emit("availabilitychanged",{value:r}))}),v.on("error",function(e){console.error("Service Error:",e.message),e.message&&0<=e.message.indexOf("Gateway is not available")||e.stack&&console.error("Error Stack:",e.stack)}),v.open(h)}function m(){t&&t.stop()}!0===h.maintainSocketConnection?(t=new o(15e3,e)).run():e(),this.getAvailability=new Promise(function(e,t){e(r)}),this.requestLEScan=function(a){var o=[];if(a||(a={filters:[],acceptAllAdvertisements:!0}),a.filters||(a.filters=[]),"boolean"!=typeof a.keepRepeatedDevices&&(a.keepRepeatedDevices=!1),"boolean"!=typeof a.acceptAllAdvertisements&&(a.acceptAllAdvertisements=!1),a.filters&&0<a.filters.length)for(var e=0;e<a.filters.length;e++)o.push(new _.BluetoothLEScanFilterInit(a.filters[e]));return y(v).then(function(i){return new Promise(function(e,t){var r,n=b.validateFilters(v,o,a.acceptAllAdvertisements);n.error?t(new TypeError(n.message)):(r=n.isFiltering,i.once("scan",function(){m()}),new u(s,v,r,a,c)._handleScan(e,t))})})},this.requestDevice=function(c){var u,l,f=c.acceptAllDevices,p=c.optionalServices,d=w.hashCode(JSON.stringify(c));if(c.filters&&0<c.filters.length){l=[];for(var e=0;e<c.filters.length;e++)l.push(new _.BluetoothLEScanFilterInit(c.filters[e]))}return y(v).then(function(s){return new Promise(function(r,n){var i,e=b.validateFilters(v,l,f,p);function a(e){var t;if(i){var r=_.filterScan(v,e,l);t=r.peripheral,u=r.filter}else u=void 0;h.returnData?i?t&&h.returnData({peripheral:t}):h.returnData({peripheral:e}):i?t&&(s.removeListener("scan",a),o(t)):o(e)}function o(e){var t;s.removeListener("scan",a),console.log("Found device ",e.name,JSON.stringify(c)),e._wbBluetoothDevice||(e._wbBluetoothDevice={}),e._wbBluetoothDevice[d]||(e._wbBluetoothDevice[d]=new g(v,e,p,u)),u=void 0,t=e._wbBluetoothDevice[d],s.stopScan({fulfill:function(){r(t)},reject:n})}function t(t){try{s.stopScan(function(){console.log("Scan stopped")})}catch(e){console.error("Unable to stop scan. Rejecting with original message",t)}n(t)}e.error?n(new TypeError(e.message)):(i=e.isFiltering,v.on("state",function(e){e||n("Bluetooth is off")}),s.scan({fulfill:function(){m(),h.returnData&&h.returnData({select:o,reject:t}),s.on("scan",a)},reject:n}))})})},this.addEventListener=function(e,t){c.on(e,t)},this.removeEventListener=function(e,t){c.removeListener(e,t)}}t.exports.navigator=void 0,t.exports.init=function(e){e||(e={});var t={bluetooth:new s(e)};return e.token&&(t.bluetooth.referringDevice={dummy:"this is a dummy device",id:e.deviceUUID}),{navigator:t}}},{"./bluetooth-le-scan":2,"./filter-validation":5,"./gateway-wrapper":6,"./task":25,"./thirdparty":26,"./util":27,"./wb-device":31,"./wb-filters":33,events:37,"gatt-ip-js":13}],8:[function(e,t,r){var c=e("./lib/constants.js").C,u=e("./lib/message-helper"),l=e("./lib/event-emitter"),f=e("./descriptor").Descriptor;function n(e,t,r){l.instantiateEmitter(this);var n=this,i=e.peripheral(),a=i.gattip(),o={},s={};u.requireUUID("Characteristic","uuid",t),this.uuid=t,r||(r={}),s=r,this.type="c",this.isNotifying=!1,this.gattip=function(){return a},this.peripheral=function(){return i},this.service=function(){return e},this.getAllDescriptors=function(){return o},this.findDescriptor=function(e){return o[e]},this.addDescriptorWithUUID=function(e){var t=new f(n,e);return o[e]=t},this.addDescriptor=function(e){return o[e.uuid]=e},this.hasProperty=function(e){return s[e]&&s[e].enabled},this.setProperty=function(e,t){return s[e]=t},this.allProperties=function(){return s},this.readValue=function(t){var e=u.populateParams(n);a.request(c.kGetCharacteristicValue,e,t,function(e){u.requireFields("Value",e,[c.kValue],[]),n.value=e[c.kValue],a.fulfill(t,n,n.value)})},this.writeValue=function(t,r){u.requireHexValue("writeValue","value",r);var e=u.populateParams(n);e[c.kValue]=r,a.request(c.kWriteCharacteristicValue,e,t,function(e){n.value=r,a.fulfill(t,n)})},this.enableNotifications=function(t,r){u.requireBooleanValue("enableNotifications","isNotifying",r);var e=u.populateParams(n);e[c.kIsNotifying]=r,a.request(c.kSetValueNotification,e,t,function(e){n.isNotifying=r,a.fulfill(t,n,r)})},this.handleValueNotification=function(e){n.value=e[c.kValue],n.emit("valueChange",n,n.value)},this.respondToReadRequest=function(e,t){u.requireHexValue("respondToReadRequest","value",t);var r=u.populateParams(n);r[c.kValue]=t,e.result=c.kGetCharacteristicValue,a.respond(e,r)},this.respondToWriteRequest=function(e){var t=u.populateParams(n);e.result=c.kWriteCharacteristicValue,a.respond(e,t)},this.respondToChangeNotification=function(e,t){var r=u.populateParams(n);u.requireBooleanValue("respondToChangeNotification","value",t),r[c.kIsNotifying]=t,this.isNotifying=t,e.result=c.kSetValueNotification,a.respond(e,r)},this.indicateValueChange=function(e){u.requireHexValue("writeValue","value",e);var t=u.populateParams(n);t[c.kValue]=e,a.sendIndications(c.kSetValueNotification,t)}}l.makeEmitter(n),t.exports.Characteristic=n},{"./descriptor":9,"./lib/constants.js":14,"./lib/event-emitter":15,"./lib/message-helper":18}],9:[function(e,t,r){var o=e("./lib/constants.js").C,s=e("./lib/message-helper");t.exports.Descriptor=function(e,t){var n=this,r=e.service(),i=r.peripheral(),a=i.gattip();s.requireUUID("Descriptor","uuid",t),this.uuid=t,this.type="d",this.characteristic=function(){return e},this.service=function(){return r},this.peripheral=function(){return i},this.gattip=function(){return a},this.readValue=function(t){var e=s.populateParams(n);a.request(o.kGetDescriptorValue,e,t,function(e){s.requireFields("readValue",e,[o.kValue],[]),n.value=e[o.kValue],a.fulfill(t,n,n.value)})},this.writeValue=function(t,r){var e=s.populateParams(n);s.requireHexValue("writeValue","value",r),a.request(o.kWriteDescriptorValue,e,t,function(e){n.value=r,a.fulfill(t,n)})},this.respondToReadRequest=function(e,t){var r=s.populateParams(n);s.requireHexValue("respondToReadRequest","value",t),r[o.kValue]=t,a.respond(e,r)},this.respondToWriteRequest=function(e){var t=s.populateParams(n);a.respond(e,t)}}},{"./lib/constants.js":14,"./lib/message-helper":18}],10:[function(e,t,r){t.exports.ApplicationError=function(e){this.message="Application Error:"+e,Error.captureStackTrace(this,t.exports.ApplicationError)},t.exports.InternalError=function(e){this.message="Application Error:"+e,Error.captureStackTrace(this,t.exports.InternalError)},t.exports.GatewayError=function(e){"object"==typeof e?(this.message="Gateway Error:",e.message&&(this.message+=" "+e.message),e.code&&(this.message+=" Code:"+e.code),0==this.message.length&&(this.message="Unknown Gateway Error")):this.message=e,Error.captureStackTrace(this,t.exports.GatewayError)}},{}],11:[function(e,t,r){var s=e("./lib/constants").C,c=e("./lib/message-helper"),p=e("./peripheral").Peripheral,d=e("./stream").Stream,h=e("./errors").InternalError,v=e("./errors").ApplicationError,n=e("./lib/event-emitter"),i=e("./errors").GatewayError;function a(u,a){n.instantiateEmitter(this);var l=this,f={},o={};this.isScanning=!1,this.isPoweredOn=function(){return l.state==s.kPoweredOn},this._authenticate=function(t,e,r){var n={};n[s.kDeviceAccessToken]=e,n[s.kGetVersionInfo]=r,u.request(s.kOpen,n,t,function(e){e&&!1===e.isAuthenticated?u.reject(t,new i("Authentication failed")):u.fulfill(t,l)})},this.scan=function(t,e){var r={};e&&("boolean"==typeof e.scanDuplicates&&(r[s.kScanOptionAllowDuplicatesKey]=e.scanDuplicates),"object"==typeof e.services&&(r[s.kServiceUUIDs]=e.services)),u.request(s.kScanForPeripherals,r,t,function(e){l.isScanning=!0,u.fulfill(t,l)})},this.stopScan=function(t){u.request(s.kStopScanning,{},t,function(e){l.isScanning=!1,u.fulfill(t,l)})},this.centralState=function(t){u.request(s.kCentralState,{},t,function(e){l.state=e[s.kState],u.fulfill(t,l)})},this.configure=function(t,e,r){var n={};void 0!==e&&(n[s.kShowPowerAlert]=e),void 0!==r&&(n[s.kIdentifierKey]=r),u.request(s.kConfigure,{},t,function(e){u.fulfill(t,l)})},this.openStream=function(r,e,t){var n={};t||(t={}),"number"==typeof t.speed&&(n[s.kSpeed]=t.speed),"boolean"==typeof t.force&&(n[s.kForce]=t.force);var i=n[s.kObjectId]=e;c.requireFields("objectId",n,[s.kObjectId]),u.request(s.kOpenStream,n,r,function(e){"string"==typeof e[s.kObjectId]&&(i=e[s.kObjectId]);var t=new d(this,i);o[i]=t,u.fulfill(r,t)})},this.closeStream=function(r,e){var t={},n=t[s.kObjectId]=e;c.requireFields("objectId",t,[s.kObjectId]),u.request(s.kCloseStream,t,r,function(e){var t=o[n];delete o[n],u.fulfill(r,t)})},this.handleScanIndication=function(e){var t=e[s.kPeripheralUUID];if(!t)throw new h("Peripheral UUID is not availabvle");if(a&&a.uuids)for(var r=0;r<a.uuids.length;r++){var n=a.uuids[r];if(n&&n.length&&n!=t)return}var i=l.getPeripheral(t);i?i._updateFromScanData(e[s.kPeripheralName],e[s.kRSSIkey],e[s.kCBAdvertisementDataTxPowerLevel],e[s.kCBAdvertisementDataIsConnectable],e[s.kCBAdvertisementDataServiceUUIDsKey],e[s.kCBAdvertisementDataManufacturerDataKey],e[s.kCBAdvertisementDataServiceDataKey],e[s.kAdvertisementDataKey],e[s.kScanRecord]):i=l.addPeripheral(new p(u,t,e[s.kPeripheralName],e[s.kRSSIkey],e[s.kCBAdvertisementDataTxPowerLevel],e[s.kCBAdvertisementDataIsConnectable],e[s.kCBAdvertisementDataServiceUUIDsKey],e[s.kCBAdvertisementDataManufacturerDataKey],e[s.kCBAdvertisementDataServiceDataKey],e[s.kAdvertisementDataKey],e[s.kScanRecord])),l.emit("scan",i)},this.addPeripheralWithValues=function(e,t,r,n,i,a,o,s){if(!e)throw new h("Attempting to add an empty peripheral");var c=l.addPeripheral(new p(u,e,t,r,n,s,i,a,o));return f[e]=c},this.addPeripheral=function(e){if(!e||!e.uuid)throw new h("Attempting to add an empty peripheral");return f[e.uuid]=e},this.addStream=function(e){var t=new d(this,e);return o[e]=t},this.removePeripheral=function(e){if(!e||!e.uuid)throw new h("Attempting to remove an empty peripheral");delete f[e.uuid]},this.getPeripheral=function(e){return f[e]},this.getObject=function(e){return o[e]},this.removeObject=function(e){delete o[e]},this.getPeripheralOrDie=function(e){var t=f[e];if(!t)throw new h("Unable to find peripheral with UUID "+e);return t},this.getObjects=function(e,t,r,n,i){var a={};if(a.peripheral=f[t],a.peripheral){if("p"===e)return a;if(a.service=a.peripheral.findService(r),a.service){if("s"===e)return a;if(a.characteristic=a.service.findCharacteristic(n),a.characteristic){if("c"===e)return a;if(a.descriptor=a.characteristic.findDescriptor(i),a.descriptor){if("d"===e)return a;throw new h('_getObjects: Argument "type" is required')}throw new v('Descriptor "'+i+'" not found in the service table')}throw new v('Characteristic "'+n+'" not found in the service table')}throw new v('Service "'+r+'" not found in the service table')}throw new v("Peripheral with id "+t+" not found")},this.getObjectsFromMessage=function(e,t){if(!t)throw new h("Message parameters are missing");try{return l.getObjects(e,t[s.kPeripheralUUID],t[s.kServiceUUID],t[s.kCharacteristicUUID],t[s.kDescriptorUUID])}catch(e){throw new h(e.message,e.detail)}},this.close=function(){for(var e in Object.keys(f))if(f.hasOwnProperty(e)){var t=f[e];t.removeAllListeners(),t.removeAllChildListenersAndFlush()}f={},l.removeAllListeners()}}n.makeEmitter(a),t.exports.Gateway=a},{"./errors":10,"./lib/constants":14,"./lib/event-emitter":15,"./lib/message-helper":18,"./peripheral":22,"./stream":24}],12:[function(m,e,t){var r=m("./lib/event-emitter"),g=m("./errors").InternalError,_=m("./errors").ApplicationError,b=m("./errors").GatewayError,y=m("./lib/message-handler").MessageHandler,w=m("./lib/message-processor").MessageProcessor,I=m("./gateway").Gateway,k=(m("./lib/message-helper"),m("./lib/server-message-handler").ServerMessageHandler),D={keepalive:!0,dropConnectionOnKeepaliveTimeout:!0,keepaliveInterval:1e4,keepaliveGracePeriod:1e4};function n(){r.instantiateEmitter(this),this.traceEnabled=!1;var o,s,c,u,l,f=this,p=null;function d(){clearTimeout(p),p=setTimeout(function(){f.ping()},29e3)}function h(e){f.emit("error",e)}function v(e,t,r){try{e&&(t=JSON.parse(t)),r(t)}catch(e){h(e)}}this.getGateway=function(){return l},this.ping=function(){l&&l.centralState(function(){})},this.traceMessage=function(e,t){f.traceEnabled&&("object"==typeof e&&(e=JSON.stringify(e)),console.log(t||"",e))},this.getServerMessageHandler=function(){return u||h(new b("Server Message Handler is not Ready")),u},this.fulfill=function(e,t,r,n,i,a){"object"==typeof e&&"function"==typeof e.fulfill?e.fulfill(t,r,n,i,a):"function"==typeof e&&e(t,r,n,i,a)},this.reject=function(e,t){"object"==typeof e&&"function"==typeof e.reject?e.reject(t):h(t)},this.open=function(e){var t=new I(this,e.scanFilters);function r(e){e.isServer?(s.on("request",function(e){f.traceMessage(e,"<req:"),v(!1,e,u.processMessage)}),s.on("indication",function(e){h(new _("Received an indication on a server stream:"+JSON.stringify(e)))}),l=t,f.emit("ready",t)):e.isPassThrough?n():t.configure(function(){t.centralState(function(){if(t.isPoweredOn())t.isPoweredOn()&&(d(),n());else{console.log("Bluetooth not power on :("),f.emit("state",t.isPoweredOn());var e=setInterval(function(){t.centralState(function(){t.isPoweredOn()&&(f.emit("state",t.isPoweredOn()),clearInterval(e),d(),n())})},500)}})})}function n(){s.on("indication",function(e){f.traceMessage(e,"<ind:"),v(!1,e,c.handleIndication)}),s.on("request",function(e){"af"===e.method?(f.traceMessage(e,"<req:"),delete e.method,o.send(JSON.stringify(e))):h(new g("Received a request on a client stream:"+JSON.stringify(e)))}),l=t,f.emit("ready",t)}function i(e){e.token?t._authenticate(function(){r(e)},e.token,e.version):r(e)}if(s=new w(this),c=new y(this,t),u=new k(this,t),!0===e.trace&&(f.traceEnabled=!0),e.url){var a;a="object"==typeof window?window.WebSocket:m("websocket").w3cwebsocket,(o=new a(e.url,void 0,void 0,void 0,void 0,D)).onopen=function(){i(e)},o.onclose=function(e){o=void 0,clearTimeout(p),f.emit("onclose",e),setTimeout(f.close,100)},o.onerror=function(e){f.emit("onerror",e)}}else{if(!e.stream)throw new _("URL or stream implementing a socket interface is required");o=e.stream,i(e)}o.onmessage=function(e){d(),v(!0,e.data,s.onMessageReceived)},s.on("response",function(e,t){f.traceMessage(e,"<rsp:");try{e.error?f.reject(t.cb,new b(e.error)):t.handler?t.handler(e.params):f.fulfill(t.cb)}catch(e){f.reject(t.cb,e)}}),s.on("error",function(e){f.emit("error",e)})},this.close=function(){clearTimeout(p),f.removeAllListeners(),o&&o.close(),s&&(s.flushRequests(),s.removeAllListeners()),l&&l.close()},this.flushRequests=function(e){s.flushRequests(e)},this.getCommunicationStream=function(){return o},this.request=function(e,t,r,n){d();var i=c.createUserContext(e,t,r,n),a=i.originalMessage;s.register(a,i),f.traceMessage(a,">req:"),o?o.send(JSON.stringify(a)):f.reject(r,new b("Stream closed"))},this.respond=function(e,t){var r=c.wrapResponse(e,t);if(f.traceMessage(r,">rsp:"),!o)throw new b("Stream closed");o.send(JSON.stringify(r))},this.sendIndications=function(e,t){var r={params:t,jsonrpc:"2.0"};if(r.result=e,r.params=t,f.traceMessage(r,">rsp:"),!o)throw new b("Stream closed");o.send(JSON.stringify(r))},this.sendError=function(e){if(e.jsonrpc="2.0",f.traceMessage(e,">rsp:"),!o)throw new b("Stream closed");o.send(JSON.stringify(e))}}r.makeEmitter(n),e.exports.GATTIP=n},{"./errors":10,"./gateway":11,"./lib/event-emitter":15,"./lib/message-handler":17,"./lib/message-helper":18,"./lib/message-processor":19,"./lib/server-message-handler":20,websocket:36}],13:[function(e,t,r){t.exports.GATTIP=e("./gattip").GATTIP,t.exports.C=e("./lib/constants").C},{"./gattip":12,"./lib/constants":14}],14:[function(e,t,r){t.exports.C={DEFAULT_MESSAGE_TIMEOUT_MS:61e3,MAX_PENDING_MESSAGES:200,NUM_CONNECT_ATTEMPTS:3,kMessageId:"id",kSessionId:"session_id",kObjectId:"oid",kAuthenticate:"aut",kOpen:"opn",kDeviceAccessToken:"dat",kGetVersionInfo:"vif",kOpenStream:"ops",kCloseStream:"cls",kStreamClosedIndication:"cis",kWriteStreamData:"wsd",kStreamDataIndication:"sdi",kVal:"val",kSpeed:"spd",kForce:"frc",kError:"error",kCode:"code",kMessageField:"message",kMethod:"method",kResult:"result",kIdField:"id",kConfigure:"aa",kScanForPeripherals:"ab",kStopScanning:"ac",kConnect:"ad",kDisconnect:"ae",kCentralState:"af",kGetConnectedPeripherals:"ag",kGetPerhipheralsWithServices:"ah",kGetPerhipheralsWithIdentifiers:"ai",kGetServices:"ak",kGetIncludedServices:"al",kGetCharacteristics:"am",kGetDescriptors:"an",kGetCharacteristicValue:"ao",kGetDescriptorValue:"ap",kWriteCharacteristicValue:"aq",kWriteDescriptorValue:"ar",kSetValueNotification:"as",kGetPeripheralState:"at",kGetRSSI:"au",kInvalidatedServices:"av",kPeripheralNameUpdate:"aw",kMessage:"zz",kCentralUUID:"ba",kPeripheralUUID:"bb",kPeripheralName:"bc",kPeripheralUUIDs:"bd",kServiceUUID:"be",kServiceUUIDs:"bf",kPeripherals:"bg",kIncludedServiceUUIDs:"bh",kCharacteristicUUID:"bi",kCharacteristicUUIDs:"bj",kDescriptorUUID:"bk",kServices:"bl",kCharacteristics:"bm",kDescriptors:"bn",kProperties:"bo",kValue:"bp",kState:"bq",kStateInfo:"br",kStateField:"bs",kWriteType:"bt",kRSSIkey:"bu",kIsPrimaryKey:"bv",kIsBroadcasted:"bw",kIsNotifying:"bx",kShowPowerAlert:"by",kIdentifierKey:"bz",kScanOptionAllowDuplicatesKey:"b0",kScanOptionSolicitedServiceUUIDs:"b1",kAdvertisementDataKey:"b2",kCBAdvertisementDataManufacturerDataKey:"mfr",kCBAdvertisementDataServiceUUIDsKey:"suu",kCBAdvertisementDataServiceDataKey:"sdt",kCBAdvertisementDataOverflowServiceUUIDsKey:"b6",kCBAdvertisementDataSolicitedServiceUUIDsKey:"b7",kCBAdvertisementDataIsConnectable:"cbl",kCBAdvertisementDataTxPowerLevel:"txp",kPeripheralBtAddress:"c1",kRawAdvertisementData:"c2",kScanRecord:"c3",kCBCentralManagerRestoredStatePeripheralsKey:"da",kCBCentralManagerRestoredStateScanServicesKey:"db",kWriteWithResponse:"cc",kWriteWithoutResponse:"cd",kNotifyOnConnection:"ce",kNotifyOnDisconnection:"cf",kNotifyOnNotification:"cg",kDisconnected:"ch",kConnecting:"ci",kConnected:"cj",kUnknown:"ck",kResetting:"cl",kUnsupported:"cm",kUnauthorized:"cn",kPoweredOff:"co",kPoweredOn:"cp",kErrorPeripheralNotFound:"-32001",kErrorServiceNotFound:"-32002",kErrorCharacteristicNotFound:"-32003",kErrorDescriptorNotFound:"-32004",kErrorPeripheralStateIsNotValid:"-32005",kErrorNoServiceSpecified:"-32006",kErrorNoPeripheralIdentiferSpecified:"-32007",kErrorStateRestorationNotValid:"-32008",kInvalidRequest:"-32600",kMethodNotFound:"-32601",kInvalidParams:"-32602",kError32603:"-32603",kParseError:"-32700",kGAP_ADTYPE_FLAGS:"01",kGAP_ADTYPE_INCOMPLETE_16BIT_SERVICEUUID:"02",kGAP_ADTYPE_COMPLETE_16BIT_SERVICEUUID:"03",kGAP_ADTYPE_INCOMPLETE_32BIT_SERVICEUUID:"04",kGAP_ADTYPE_COMPLETE_32BIT_SERVICEUUID:"05",kGAP_ADTYPE_INCOMPLETE_128BIT_SERVICEUUID:"06",kGAP_ADTYPE_COMPLETE_128BIT_SERVICEUUID:"07",kGAP_ADTYPE_POWER_LEVEL:"0A",kGAP_ADTYPE_MANUFACTURER_SPECIFIC:"FF",kGAP_ADTYPE_16BIT_SERVICE_DATA:"16",id:1,authenticate:"authenticate",AllProperties:["Broadcast","Read","WriteWithoutResponse","Write","Notify","Indicate","AuthenticatedSignedWrites","ExtendedProperties","NotifyEncryptionRequired","IndicateEncryptionRequired"]}},{}],15:[function(e,t,r){var n=e("events"),i=e("util");t.exports.makeEmitter=function(e){i.inherits(e,n)},t.exports.instantiateEmitter=function(e){n.call(e)}},{events:37,util:41}],16:[function(e,t,r){var h=e("./constants").C;function v(e,t){var r=parseInt(t[0],16);if(2<r){for(var n=t[3]+t[2],i="",a=4;a<=r;a++)i+=t[a];e.manufacturerData[n]=i}t.splice(0,r+1)}function m(e,t){for(var r=parseInt(t[0],16),n="",i=r;2<=i;i--)n+=t[i];e.serviceUUIDs=n,t.splice(0,r+1)}function g(e,t){for(var r=parseInt(t[0],16),n="",i=r;2<=i;i--)n+=t[i],14!=i&&12!=i&&10!=i&&8!=i||(n+="-");e.serviceUUIDs=n,t.splice(0,r+1)}function _(e,t){for(var r=parseInt(t[0],16),n="",i=3;2<=i;i--)n+=t[i];"FEAA"==n&&(0===parseInt(t[4],16)?function(e,t){e.frameType="UID",e.nameSpace="",e.instanceID="",e.txPowerLevel=parseInt(t[5],16);for(var r=6;r<16;r++)e.nameSpace+=t[r];for(var n=16;n<22;n++)e.instanceID+=t[n];e.reserved=t[22],e.reserved+=t[23]}(e):16==parseInt(t[4],16)?function(e,t){for(var r in e.frameType="URL",e.txPowerLevel=parseInt(t[5]),h.AllProtocols)t[6]==r&&(e.url=h.AllProtocols[r]);for(var n=7;n<advArrayLength;n++)e.url+=String.fromCharCode(parseInt(t[n],16));for(var i in h.AllDomains)t[advArrayLength]==i&&(e.url+=h.AllDomains[i])}(e):32==parseInt(t[4],16)&&function(e,t){e.frameType="TLM",e.advPacketCount="",e.timeInterval="",e.batteryVoltage="",e.eddyVersion=parseInt(t[5],16);for(var r=6;r<8;r++)e.batteryVoltage+=t[r];e.batteryVoltage=parseInt(e.batteryVoltage,16),e.temperature=Math.ceil(parseInt(t[8],16)),e.temperature+=".";var n=Math.ceil(1/256*parseInt(t[9],16));2<n.length?e.temperature+=n.toString().substring(0,2):e.temperature+=n;for(var i=10;i<14;i++)e.advPacketCount+=t[i];e.advPacketCount=parseInt(e.advPacketCount,16);for(var a=14;a<18;a++)e.timeInterval+=t[a];if(e.timeInterval=Math.ceil(.1*parseInt(e.timeInterval,16)),e.timePeriod="",60<=e.timeInterval){var o=Math.floor(e.timeInterval/86400);0<o&&(e.timePeriod+=o<10?o+"day ":o+"days ",e.timeInterval-=24*o*60*60);var s=Math.floor(e.timeInterval/3600);0<s?(e.timePeriod+=s<10?"0"+s+":":s+":",e.timeInterval-=60*s*60):e.timePeriod+="00:";var c=Math.floor(e.timeInterval/60);e.timeInterval=(0<c?(e.timePeriod+=c<10?"0"+c+":":c+":",e.timeInterval-=60*c,e.timePeriod+=e.timeInterval<10?"0"+e.timeInterval:e.timeInterval,e.timePeriod+=" secs"):e.timePeriod+="00:"+e.timeInterval,0)}else 0<e.timeInterval&&e.timeInterval<60&&(e.timePeriod+=e.timeInterval<10?"00:00:0"+e.timeInterval:"00:00:"+e.timeInterval,e.timePeriod+=" secs")}(e)),t.splice(0,r+1)}t.exports.parseAdvArray=function(e,t){e.advdata||(e.advdata={});var r=e.advdata;if(r.manufacturerData||(r.manufacturerData={}),r.serviceUUIDs||(r.serviceUUIDs=[]),!t)return[];var n,i,a,o,s,c,u=[];if(t.length%2==0)for(var l=0;l<t.length;l+=2)u[l/2]=t.charAt(l)+t.charAt(l+1);else for(var f=0;f<t.length;f++)u[f]=t.charAt(2*f)+t.charAt(2*f+1);for(;;){var p=u[1];if(p==h.kGAP_ADTYPE_FLAGS)o=r,s=u,void 0,c=parseInt(s[0],16),1<=parseInt(s[2],16)?o.connectable="true":o.connectable="false",s.splice(0,c+1);else if(p==h.kGAP_ADTYPE_POWER_LEVEL)n=r,i=u,void 0,a=parseInt(i[0],16),n.txPowerLevel=parseInt(i[2]),i.splice(0,a+1);else if(p==h.kGAP_ADTYPE_INCOMPLETE_16BIT_SERVICEUUID||p==h.kGAP_ADTYPE_COMPLETE_16BIT_SERVICEUUID)m(r,u);else if(p==h.kGAP_ADTYPE_INCOMPLETE_32BIT_SERVICEUUID||p==h.kGAP_ADTYPE_COMPLETE_32BIT_SERVICEUUID)m(r,u);else if(p==h.kGAP_ADTYPE_INCOMPLETE_128BIT_SERVICEUUID||p==h.kGAP_ADTYPE_COMPLETE_128BIT_SERVICEUUID)g(r,u);else if(p==h.kGAP_ADTYPE_MANUFACTURER_SPECIFIC)v(r,u);else if(p==h.kGAP_ADTYPE_16BIT_SERVICE_DATA)_(r,u);else if("00"==p)u.splice(0,1);else{var d=parseInt(u[0],16);u.splice(0,d+1)}if(0===u.length)break}}},{"./constants":14}],17:[function(e,t,r){var n=e("./constants").C,i=e("./message-helper"),a=e("./../errors").InternalError,o=e("./../errors").ApplicationError;t.exports.MessageHandler=function(e,r){this.createUserContext=function(e,t,r,n){return{originalMessage:{method:e,params:t,jsonrpc:"2.0"},cb:r,handler:n}},this.wrapResponse=function(e,t){var r={params:t,jsonrpc:"2.0"};return i.requireAndPopulateFieldsFromCookie("wrapResponse",e,r),r},this.handleIndication=function(e){if(e.error)throw new o(JSON.stringify(e));var t=e.params;switch(e.result){case n.kScanForPeripherals:r.handleScanIndication(t);break;case n.kDisconnect:!function(){i.requireFields("Disconnect indication",t,[n.kPeripheralUUID]);var e=r.getPeripheral(t[n.kPeripheralUUID]);e?e.handleDisconnectIndication(e):console.warn("Received disconnect indication for an unknown peripheral with UUID",t[n.kPeripheralUUID])}();break;case n.kSetValueNotification:i.requireFields("Disconnect indication",t,[n.kPeripheralUUID]),r.getPeripheral(t[n.kPeripheralUUID])?(i.requireFields("Value notification",t,[n.kPeripheralUUID,n.kServiceUUID,n.kCharacteristicUUID,n.kValue]),r.getObjectsFromMessage("c",e.params).characteristic.handleValueNotification(t)):console.warn("Received value notification for an unknown peripheral with UUID",t[n.kPeripheralUUID]);break;case n.kStreamDataIndication:!function(){i.requireFields("Object ID for stream data",t,[n.kObjectId]);var e=r.getObject(t[n.kObjectId]);e?e.handleDataIndication(t):console.warn("Received stream data indication for unknown stream",t[n.kObjectId])}();break;case n.kStreamClosedIndication:!function(){i.requireFields("Object ID for stream close",t,[n.kObjectId]);var e=r.getObject(t[n.kObjectId]);e?e.handleDataIndication(t):console.warn("Received stream closed indication for unknown stream",t[n.kObjectId])}();break;default:!function(){throw new a("Unknown indication received from the gateway:",JSON.stringify(e))}()}}}},{"./../errors":10,"./constants":14,"./message-helper":18}],18:[function(e,i,t){var c=e("./constants").C,s={},u=e("./../errors").InternalError,l=e("./../errors").ApplicationError;for(var r in c){var n=c[r];0==r.indexOf("k")&&(r=r.substring(1,r.length),s[n]=r)}i.exports.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return JSON.stringify(e)===JSON.stringify({})},i.exports.arrayAsHex=function(e,t){var r=t?"0x":"";for(var n in e){var i=(255&e[n]).toString(16);1==i.length&&(i="0"+i),r+=i}return r},i.exports.toString=function(e){return function e(t){var r="";if("object"==typeof t){if(Array.isArray(t))for(var n in t)0!=n&&(r+=" ,"),r+=t[n];for(var i in t)if(t.hasOwnProperty(i)){var a=t[i],o=s[i];o||(o=i),"object"==typeof a?Array.isArray(a)?r+=" "+o+":["+e(a)+"]":r+=" "+o+":{"+e(a)+"}":r+=" "+o+"="+a}}return r}(e.params).trim()},i.exports.requireAndAssignParameters=function(e,t,r,n){i.exports.requireFields(e+" call parameters ",t,r,n)},i.exports.requireBooleanValue=function(e,t,r){if("boolean"!=typeof r)throw new l(e+" missing parameter "+t)},i.exports.requireHexValue=function(e,t,r){if("string"!=typeof r)throw new l(e+" missing parameter "+t);if(0<r.length&&(r.length%2!=0||!/^[0-9a-fA-F]+$/.test(r)))throw new l(e+" value "+t+" is not a valid hex string")},i.exports.requireUUID=function(e,t,r){if("string"!=typeof r)throw new l(e+" missing parameter "+t);if(r.length<4||!/^[0-9A-F-]+$/.test(r))throw new l(e+" value "+t+" is not a valid UUID")},i.exports.requireHexValues=function(e,t,r){var n=[];if(!Array.isArray(t)||!Array.isArray(r))throw new u("Illegal use of requireHexValues");for(var i=0;i<t.length;i++){var a=t[i],o=r[i];("string"!=typeof o||o.length<2||o.length%2!=0||!/^#[0-9A-F]$/i.test(o))&&n.push(a)}if(n)throw new l(e+" missing parameters "+n)},i.exports.requireFields=function(e,t,r,n){var i=[];if(n||(n={}),!t)throw new u(e+"Object is undefined");for(var a=0;a<r.length;a++){var o=r[a];null==typeof t[o]&&(null==typeof n[a]?i.push(r):t[o]=n[a])}if(i.length)throw new u(e+" missing "+i)},i.exports.requireAndPopulateFieldsFromCookie=function(e,t,r){if(!t)throw new l('Error: "'+e+" is missing the cookie");if(!t.original.id)throw new l('Error: "'+e+" is missing the cookie ID");if(!t.original.session_id)throw new l('Error: "'+e+" is missing the cookie session ID");if(!t.original.method)throw new l('Error: "'+e+" is missing the cookie request");r[c.kMessageId]=t.original.id,r[c.kSessionId]=t.original.session_id,r.result=t.result},i.exports.populateParams=function(e,n){if(n||(n={}),!e)throw new u("populateParams: service object is undefined");var t,r,i,a,o=23132;switch(e.type){case"d":o=4,a=e;break;case"c":o=3,i=e;break;case"s":o=2,r=e;break;case"p":o=1,t=e;break;default:throw new u('type must be one of: "s", "c" or "d"')}function s(e,t){o--;var r=t.uuid;if(!r)throw new u('UUID for object of type "'+t.type+'" is missing');n[e]=r}if(a&&(s(c.kDescriptorUUID,a),i=a.characteristic()),i&&(s(c.kCharacteristicUUID,i),r=i.service()),r&&(s(c.kServiceUUID,r),t=i.peripheral()),t&&s(c.kPeripheralUUID,t),0!=o)throw new u("Expected "+o+" more parts when constructing params of "+e.type);return n}},{"./../errors":10,"./constants":14}],19:[function(e,t,r){var n=e("./event-emitter"),o=e("./constants").C,s=e("./../errors").ApplicationError,a=1,c=!1,u=!1;function l(e,t,r,n){this.msg=t,this.userContext=r,void 0===t.id&&(t.id=Number(a++).toString()),this.id=t.id,n||(n=o.DEFAULT_MESSAGE_TIMEOUT_MS);var i=this;this.timeout=setTimeout(function(){delete i.timeout,console.warn("Timeout occurred for message",JSON.stringify(t)),e.emit("error",new s("Timed out : "+JSON.stringify(t)),i.userContext.cb)},n)}function i(){n.instantiateEmitter(this);var i=this,a={};this.register=function(e,t,r){if(Object.keys(a).length>o.MAX_PENDING_MESSAGES)throw new s("Message queue is full",e);var n=new l(i,e,t,r);return(a[n.id]=n).msg},this.hasMessage=function(e){return!!a[""+e]},this.onMessageReceived=function(e){var t;if(e.params&&e.params.id&&(console.warn("HACK ALERT: ID is in params!?!"),e.id=e.params.id),e.id&&(t=a[""+e.id]),!t){if(e.id)return e.result==o.kScanForPeripherals&&e.params&&e.params.bb?(u||(u=!0,console.warn("HACK ALERT: Scan response has an ID")),void i.emit("indication",e)):void i.emit("request",e);if(e.result!=o.kMessage)return void i.emit("indication",e);c||(c=!0,console.warn("HACK ALERT: Hacking the authenticate message")),e.id="1",t=a[1]}t.timeout&&clearTimeout(t.timeout),delete a[e.id],i.emit("response",e,t.userContext,t.msg)},this.flushRequests=function(e){for(var t in a)if(a.hasOwnProperty(t)){var r=a[t];e&&!e(r.userContext)||(r.timeout&&clearTimeout(r.timeout),delete a[t])}}}n.makeEmitter(i),t.exports.MessageProcessor=i},{"./../errors":10,"./constants":14,"./event-emitter":15}],20:[function(e,t,r){var _=e("./constants.js").C,n=e("./event-emitter"),b=e("./message-helper");function i(g,u){n.instantiateEmitter(this);var l=this;this.processMessage=function(e){var t;if(void 0!==e&&e)if(e.error)console.warn("Error in the Request",mesg.error);else{if(e.result&&(e.result==_.kMessage||e.result==_.kAuthenticate)){var r=!1;return e.error||"object"!=typeof e.params||!0!==e.params[_.kAuthenticate]||(r=!0),void l.emit("authenticated",r)}if(e.method&&e.method==_.kAuthenticate){console.log("Client requested to authenticate with us. Allowing the client");var n={};n[_.kAuthenticate]=!0;var i={};return i.result=_.kAuthenticate,i.params=n,i[_.kIdField]=e[_.kIdField],i=JSON.stringify(i),void l.send(i)}var o={original:e},s=e.params;switch(e.method){case _.kConfigure:l.emit("configure",o,s[_.kShowPowerAlert],s[_.kIdentifierKey]);break;case _.kScanForPeripherals:l.emit("scan",o,s[_.kScanOptionAllowDuplicatesKey],s[_.kServiceUUIDs]);break;case _.kStopScanning:l.emit("stopScan",o);break;case _.kCentralState:l.emit("getCentralState",o);break;case _.kConnect:try{t=c("p"),l.emit("connect",o,t.peripheral.uuid)}catch(e){console.error(e)}break;case _.kDisconnect:try{t=c("p"),l.emit("disconnect",o,t.peripheral.uuid)}catch(e){console.error(e)}break;case _.kGetCharacteristicValue:try{t=c("c"),l.emit("readCharacteristic",o,t.peripheral.uuid,t.service.uuid,t.characteristic.uuid)}catch(e){console.error(e)}break;case _.kWriteCharacteristicValue:try{t=c("c"),l.emit("writeCharacteristic",o,t.peripheral.uuid,t.service.uuid,t.characteristic.uuid,s[_.kValue])}catch(e){console.error(e)}break;case _.kSetValueNotification:try{t=c("c"),l.emit("enableNotifications",o,t.peripheral.uuid,t.service.uuid,t.characteristic.uuid,s[_.kIsNotifying])}catch(e){console.error(e)}break;case _.kGetDescriptorValue:try{t=c("d"),l.emit("readDescriptor",o,t.peripheral.uuid,t.service.uuid,t.characteristic.uuid,t.descriptor.uuid)}catch(e){console.error(e)}break;case _.kWriteDescriptorValue:try{t=c("d"),l.emit("writeDescriptor",o,t.peripheral.uuid,t.service.uuid,t.characteristic.uuid,t.descriptor.uuid,e.params[_.kValue])}catch(e){console.error(e)}break;case _.kOpenStream:try{l.emit("openStream",o,s[_.kObjectId],{speed:s[_.kSpeed],force:s[_.kForce]})}catch(e){console.error(e)}break;case _.kCloseStream:try{t=a(),l.emit("closeStream",o,t)}catch(e){console.error(e)}break;case _.kWriteStreamData:try{t=a(),l.emit("writeStreamData",o,t,s[_.kVal])}catch(e){console.error(e)}break;default:return console.log("invalid request: "+e.method),void l.sendErrorResponse(o,_.kInvalidRequest,"Request not handled by server")}}else console.warn("Got unknown message from client",mesg.data);function a(){var e,t=s[_.kObjectId];if("string"!=typeof t)throw l.sendErrorResponse(o,400,"Object ID is required"),new Error("Object ID is required");if("object"!=typeof(e=u.getObject(t)))throw l.sendErrorResponse(o,404,"Object with ID "+t+" not found"),new Error("Object with ID "+t+" not found");return e}function c(e){var t=s[_.kPeripheralUUID],r={};if(r.peripheral=u.getPeripheral(t),r.peripheral&&r.peripheral.uuid){if("p"===e)return r;var n=s[_.kServiceUUID];if(r.service=r.peripheral.findService(n),r.service&&r.service.uuid){if("s"===e)return r;var i=s[_.kCharacteristicUUID];if(r.characteristic=r.service.findCharacteristic(i),r.characteristic&&r.characteristic.uuid){if("c"===e)return r;var a=s[_.kDescriptorUUID];if(r.descriptor=r.characteristic.findDescriptor(a),r.descriptor&&r.descriptor.uuid)return r;throw l.sendErrorResponse(o,404,"Descriptor not found in the service database"),new Error("Descriptor not found")}throw l.sendErrorResponse(o,404,"Characteristic not found in the service database"),new Error("Characteristic not found")}throw l.sendErrorResponse(o,404,"Service not found in the service database"),new Error("Service not found")}throw l.sendErrorResponse(o,404,"Peripheral not found in the service database"),new Error("Peripheral not found")}},l.sendErrorResponse=function(e,t,r){var n={},i={};i[_.kCode]=t,i[_.kMessageField]=r,n[_.kError]=i,e&&e.original&&(n.result=e.original.method,n[_.kMessageId]=e.original.id,n[_.kSessionId]=e.original.session_id),g.sendError(n)},l.configureResponse=function(e){e.result=_.kConfigure,g.respond(e,{})},l.centralStateResponse=function(e,t){var r={};r[_.kState]=t,e.result=_.kCentralState,g.respond(e,r)},l.stopScanResponse=function(e){e.result=_.kStopScanning,g.respond(e,{})},l.disconnectResponse=function(e,t){var r={};r[_.kPeripheralUUID]=t.uuid,r[_.kPeripheralName]=t.name,e.result=_.kDisconnect,g.respond(e,r)},l.disconnectIndication=function(e){var t={};t[_.kPeripheralUUID]=e.uuid,t[_.kPeripheralName]=e.name,g.sendIndications(_.kDisconnect,t)},l.scanResponse=function(e){e.result=_.kScanForPeripherals,g.respond(e,{})},l.scanIndication=function(e,t,r,n,i,a,o,s){var c,u,l={};if(!b.isEmpty(a))for(var f in c={},a)if(a.hasOwnProperty(f)){var p=f.toUpperCase(),d=a[f];c[p]="string"==typeof d?d.toUpperCase():b.arrayAsHex(d).toUpperCase()}if(!b.isEmpty(o))for(var h in u={},o)if(o.hasOwnProperty(h)){var v=h.toUpperCase(),m=o[h];u[v]="string"==typeof m?m.toUpperCase():b.arrayAsHex(m).toUpperCase()}l[_.kPeripheralName]=t,l[_.kPeripheralUUID]=e,l[_.kRSSIkey]=r,l[_.kCBAdvertisementDataTxPowerLevel]=n,l[_.kCBAdvertisementDataIsConnectable]=s,l[_.kCBAdvertisementDataServiceUUIDsKey]=i&&0<i.length?i:void 0,l[_.kCBAdvertisementDataManufacturerDataKey]=c,l[_.kCBAdvertisementDataServiceDataKey]=u,g.sendIndications(_.kScanForPeripherals,l)},l.openStreamResponse=function(e,t){var r={};r[_.kObjectId]=t,e.result=_.kOpenStream,g.respond(e,r)},l.closeStreamResponse=function(e,t){var r={};r[_.kObjectId]=t,e.result=_.kCloseStream,g.respond(e,r)}}this.GATM_SECURITY_PROPERTIES_NO_SECURITY=0,this.GATM_SECURITY_PROPERTIES_UNAUTHENTICATED_ENCRYPTION_WRITE=1,this.GATM_SECURITY_PROPERTIES_AUTHENTICATED_ENCRYPTION_WRITE=2,this.GATM_SECURITY_PROPERTIES_UNAUTHENTICATED_ENCRYPTION_READ=4,this.GATM_SECURITY_PROPERTIES_AUTHENTICATED_ENCRYPTION_READ=8,this.GATM_SECURITY_PROPERTIES_UNAUTHENTICATED_SIGNED_WRITES=16,this.GATM_SECURITY_PROPERTIES_AUTHENTICATED_SIGNED_WRITES=32,this.GATM_CHARACTERISTIC_PROPERTIES_BROADCAST=1,this.GATM_CHARACTERISTIC_PROPERTIES_READ=2,this.GATM_CHARACTERISTIC_PROPERTIES_WRITE_WO_RESP=4,this.GATM_CHARACTERISTIC_PROPERTIES_WRITE=8,this.GATM_CHARACTERISTIC_PROPERTIES_NOTIFY=16,this.GATM_CHARACTERISTIC_PROPERTIES_INDICATE=32,this.GATM_CHARACTERISTIC_PROPERTIES_AUTHENTICATED_SIGNED_WRITES=64,this.GATM_CHARACTERISTIC_PROPERTIES_EXT_PROPERTIES=128,this.GATM_DESCRIPTOR_PROPERTIES_READ=1,this.GATM_DESCRIPTOR_PROPERTIES_WRITE=2,n.makeEmitter(i),t.exports.ServerMessageHandler=i},{"./constants.js":14,"./event-emitter":15,"./message-helper":18}],21:[function(e,t,r){var h=e("./constants").C,o=e("./../service").Service,v=e("./../characteristic").Characteristic,m=e("./../descriptor").Descriptor;function s(e,t){var r=t[h.kCharacteristicUUID],n=e.findCharacteristic(r);n||(n=new v(e,r),e.addCharacteristic(n)),n.value=t[h.kValue];var i=t[h.kProperties];if("object"==typeof i)for(var a in i)n.setProperty(a,{enabled:i[a].enabled,name:i[a].name});else for(var o in h.AllProperties)n.setProperty([h.AllProperties[o]],{enabled:i>>o&1,name:h.AllProperties[o]});n.isNotifying=!1;var s,c,u,l,f=t[h.kDescriptors];if(f)for(var p in f){var d=f[p];s=n,l=void 0,u=(c=d)[h.kDescriptorUUID],(l=s.findDescriptor(u))||(l=new m(s,u),s.addDescriptor(l)),l.value=c[h.kValue]}}function i(e,t){var r=t[h.kServiceUUID],n=e.findService(r);n||(n=new o(e,r),e.addService(n));var i=t[h.kCharacteristics];if(i)for(var a in i){s(n,i[a])}}function a(e){var t={};if(e&&e.getAllDescriptors())for(var r in e.getAllDescriptors()){var n={};n[h.kDescriptorUUID]=r,n[h.kValue]=e.findDescriptor(r).value,n[h.kProperties]=e.findDescriptor(r).properties,n[h.kIsNotifying]=e.findDescriptor(r).isNotifying,t[r]=n}return t}function c(e){var t={};if(e&&e.getAllCharacteristics())for(var r in e.getAllCharacteristics()){var n={};n[h.kCharacteristicUUID]=r,n[h.kValue]=e.findCharacteristic(r).value,n[h.kProperties]=e.findCharacteristic(r).allProperties(),n[h.kIsNotifying]=e.findCharacteristic(r).isNotifying,n[h.kDescriptors]=a(e.findCharacteristic(r)),t[r]=n}return t}t.exports.parseServiceRecord=function(e,t){var r=t[h.kServices];if(r)for(var n in r){i(e,r[n])}},t.exports.getServiceJsonFromPeripheralObject=function(e){var t={};if(e&&e.getAllServices())for(var r in e.getAllServices()){var n={};n[h.kServiceUUID]=r,n[h.kIsPrimaryKey]=e.findService(r).isPrimary,n[h.kCharacteristics]=c(e.findService(r)),t[r]=n}return t}},{"./../characteristic":8,"./../descriptor":9,"./../service":23,"./constants":14}],22:[function(e,t,r){var l=e("./lib/constants.js").C,b=e("./lib/message-helper"),y=e("./lib/message-advdata-parser"),f=e("./lib/event-emitter"),p=e("./lib/service-table"),d=e("./service").Service;function w(e,t){return-1==e.indexOf(t)&&(e.push(t),!0)}function n(a,n,e,t,r,i,o,s,c){f.instantiateEmitter(this);var v=this;this.type="p",this.uuid=n,this.isConnected=!1;var u={},m={},g={},_=[];this._updateFromScanData=function(e,t,r,n,i,a,o,s,c){this.name=e,this.rssi=t,this.txPowerLevel=r,this.connectable=n;if(a)for(var u in a){var l=u.toUpperCase();m[l]=a[u].toUpperCase()}if(o)for(var f in o)g[f]=o[f];if(i)for(var p=0;p<i.length;p++)w(_,i[p]);if(s){if(y.parseAdvArray(v,s.c2),v.advdata.connectable&&(v.connectable="true"===v.advdata.connectable),v.advdata.txPowerLevel&&(this.txPowerLevel=v.advdata.txPowerLevel),v.advdata.manufacturerData&&!b.isEmpty(v.advdata.manufacturerData))for(var d in v.advdata.manufacturerData){var h=d.toUpperCase();m[h]=v.advdata.manufacturerData[d].toUpperCase()}v.advdata.serviceUUIDs&&0<v.advdata.serviceUUIDs.length&&w(_,v.advdata.serviceUUIDs)}},this.findService=function(e){return u[e]},this.getMfrData=function(e){return m[e]},this.getSvcData=function(e){return g[e]},this.hasAdvertisedServiceUUID=function(e){return 0<=_.indexOf(e)},this.getAllServices=function(){return u},this.getAllMfrData=function(){return m},this.getAllSvcData=function(){return g},this.getAllAdvertisedS