Socket
Socket
Sign inDemoInstall

webbluetooth

Package Overview
Dependencies
Maintainers
1
Versions
58
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

webbluetooth - npm Package Compare versions

Comparing version 1.3.1-next.b464a24.0 to 2.0.0

src/events.ts

2

dist/webbluetooth.esm.js

@@ -1,2 +0,2 @@

import{on as e,state as t,once as r,stopScanning as i,startScanning as n}from"@abandonware/noble";var s,a,o;function c(){}function _(){_.init.call(this)}function d(e){return void 0===e._maxListeners?_.defaultMaxListeners:e._maxListeners}function u(e,t,r){if(t)e.call(r);else for(var i=e.length,n=w(e,i),s=0;s<i;++s)n[s].call(r)}function l(e,t,r,i){if(t)e.call(r,i);else for(var n=e.length,s=w(e,n),a=0;a<n;++a)s[a].call(r,i)}function h(e,t,r,i,n){if(t)e.call(r,i,n);else for(var s=e.length,a=w(e,s),o=0;o<s;++o)a[o].call(r,i,n)}function f(e,t,r,i,n,s){if(t)e.call(r,i,n,s);else for(var a=e.length,o=w(e,a),c=0;c<a;++c)o[c].call(r,i,n,s)}function p(e,t,r,i){if(t)e.apply(r,i);else for(var n=e.length,s=w(e,n),a=0;a<n;++a)s[a].apply(r,i)}function m(e,t,r,i){var n,s,a,o;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),a=s[t]):(s=e._events=new c,e._eventsCount=0),a){if("function"==typeof a?a=s[t]=i?[r,a]:[a,r]:i?a.unshift(r):a.push(r),!a.warned&&(n=d(e))&&n>0&&a.length>n){a.warned=!0;var _=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");_.name="MaxListenersExceededWarning",_.emitter=e,_.type=t,_.count=a.length,o=_,"function"==typeof console.warn?console.warn(o):console.log(o)}}else a=s[t]=r,++e._eventsCount;return e}function v(e,t,r){var i=!1;function n(){e.removeListener(t,n),i||(i=!0,r.apply(e,arguments))}return n.listener=r,n}function g(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function w(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}c.prototype=Object.create(null),_.EventEmitter=_,_.usingDomains=!1,_.prototype.domain=void 0,_.prototype._events=void 0,_.prototype._maxListeners=void 0,_.defaultMaxListeners=10,_.init=function(){this.domain=null,_.usingDomains&&(void 0).active&&(void 0).Domain,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new c,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},_.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},_.prototype.getMaxListeners=function(){return d(this)},_.prototype.emit=function(e){var t,r,i,n,s,a,o,c="error"===e;if(a=this._events)c=c&&null==a.error;else if(!c)return!1;if(o=this.domain,c){if(t=arguments[1],!o){if(t instanceof Error)throw t;var _=new Error('Uncaught, unspecified "error" event. ('+t+")");throw _.context=t,_}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=o,t.domainThrown=!1,o.emit("error",t),!1}if(!(r=a[e]))return!1;var d="function"==typeof r;switch(i=arguments.length){case 1:u(r,d,this);break;case 2:l(r,d,this,arguments[1]);break;case 3:h(r,d,this,arguments[1],arguments[2]);break;case 4:f(r,d,this,arguments[1],arguments[2],arguments[3]);break;default:for(n=new Array(i-1),s=1;s<i;s++)n[s-1]=arguments[s];p(r,d,this,n)}return!0},_.prototype.addListener=function(e,t){return m(this,e,t,!1)},_.prototype.on=_.prototype.addListener,_.prototype.prependListener=function(e,t){return m(this,e,t,!0)},_.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,v(this,e,t)),this},_.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,v(this,e,t)),this},_.prototype.removeListener=function(e,t){var r,i,n,s,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new c:(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(n=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){a=r[s].listener,n=s;break}if(n<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new c,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,n=e.length;i<n;r+=1,i+=1)e[r]=e[i];e.pop()}(r,n);i.removeListener&&this.emit("removeListener",e,a||t)}return this},_.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new c,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new c:delete r[e]),this;if(0===arguments.length){for(var i,n=Object.keys(r),s=0;s<n.length;++s)"removeListener"!==(i=n[s])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new c,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},_.prototype.listeners=function(e){var t,r=this._events;return r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[]},_.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},_.prototype.listenerCount=g,_.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class y extends _{addEventListener(e,t){return super.addListener(e,t)}removeEventListener(e,t){return super.removeListener(e,t)}dispatchEvent(e,t){return super.emit(e,{type:e,target:this,value:t})}}function b(e){return"number"==typeof e&&(e=e.toString(16)),(e=e.toLowerCase()).length<=8&&(e=("00000000"+e).slice(-8)+"-0000-1000-8000-00805f9b34fb"),32===e.length&&(e=e.match(/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/).splice(1).join("-")),e}function E(e){return"string"==typeof e&&s[e]&&(e=s[e]),b(e)}function D(e){return"string"==typeof e&&a[e]&&(e=a[e]),b(e)}function x(e){return"string"==typeof e&&o[e]&&(e=o[e]),b(e)}!function(e){e[e.alert_notification=6161]="alert_notification",e[e.automation_io=6165]="automation_io",e[e.battery_service=6159]="battery_service",e[e.blood_pressure=6160]="blood_pressure",e[e.body_composition=6171]="body_composition",e[e.bond_management=6174]="bond_management",e[e.continuous_glucose_monitoring=6175]="continuous_glucose_monitoring",e[e.current_time=6149]="current_time",e[e.cycling_power=6168]="cycling_power",e[e.cycling_speed_and_cadence=6166]="cycling_speed_and_cadence",e[e.device_information=6154]="device_information",e[e.environmental_sensing=6170]="environmental_sensing",e[e.generic_access=6144]="generic_access",e[e.generic_attribute=6145]="generic_attribute",e[e.glucose=6152]="glucose",e[e.health_thermometer=6153]="health_thermometer",e[e.heart_rate=6157]="heart_rate",e[e.human_interface_device=6162]="human_interface_device",e[e.immediate_alert=6146]="immediate_alert",e[e.indoor_positioning=6177]="indoor_positioning",e[e.internet_protocol_support=6176]="internet_protocol_support",e[e.link_loss=6147]="link_loss",e[e.location_and_navigation=6169]="location_and_navigation",e[e.next_dst_change=6151]="next_dst_change",e[e.phone_alert_status=6158]="phone_alert_status",e[e.pulse_oximeter=6178]="pulse_oximeter",e[e.reference_time_update=6150]="reference_time_update",e[e.running_speed_and_cadence=6164]="running_speed_and_cadence",e[e.scan_parameters=6163]="scan_parameters",e[e.tx_power=6148]="tx_power",e[e.user_data=6172]="user_data",e[e.weight_scale=6173]="weight_scale"}(s||(s={})),function(e){e[e.aerobic_heart_rate_lower_limit=10878]="aerobic_heart_rate_lower_limit",e[e.aerobic_heart_rate_upper_limit=10884]="aerobic_heart_rate_upper_limit",e[e.aerobic_threshold=10879]="aerobic_threshold",e[e.age=10880]="age",e[e.aggregate=10842]="aggregate",e[e.alert_category_id=10819]="alert_category_id",e[e.alert_category_id_bit_mask=10818]="alert_category_id_bit_mask",e[e.alert_level=10758]="alert_level",e[e.alert_notification_control_point=10820]="alert_notification_control_point",e[e.alert_status=10815]="alert_status",e[e.altitude=10931]="altitude",e[e.anaerobic_heart_rate_lower_limit=10881]="anaerobic_heart_rate_lower_limit",e[e.anaerobic_heart_rate_upper_limit=10882]="anaerobic_heart_rate_upper_limit",e[e.anaerobic_threshold=10883]="anaerobic_threshold",e[e.analog=10840]="analog",e[e.apparent_wind_direction=10867]="apparent_wind_direction",e[e.apparent_wind_speed=10866]="apparent_wind_speed",e[e["gap.appearance"]=10753]="gap.appearance",e[e.barometric_pressure_trend=10915]="barometric_pressure_trend",e[e.battery_level=10777]="battery_level",e[e.blood_pressure_feature=10825]="blood_pressure_feature",e[e.blood_pressure_measurement=10805]="blood_pressure_measurement",e[e.body_composition_feature=10907]="body_composition_feature",e[e.body_composition_measurement=10908]="body_composition_measurement",e[e.body_sensor_location=10808]="body_sensor_location",e[e.bond_management_control_point=10916]="bond_management_control_point",e[e.bond_management_feature=10917]="bond_management_feature",e[e.boot_keyboard_input_report=10786]="boot_keyboard_input_report",e[e.boot_keyboard_output_report=10802]="boot_keyboard_output_report",e[e.boot_mouse_input_report=10803]="boot_mouse_input_report",e[e["gap.central_address_resolution_support"]=10918]="gap.central_address_resolution_support",e[e.cgm_feature=10920]="cgm_feature",e[e.cgm_measurement=10919]="cgm_measurement",e[e.cgm_session_run_time=10923]="cgm_session_run_time",e[e.cgm_session_start_time=10922]="cgm_session_start_time",e[e.cgm_specific_ops_control_point=10924]="cgm_specific_ops_control_point",e[e.cgm_status=10921]="cgm_status",e[e.csc_feature=10844]="csc_feature",e[e.csc_measurement=10843]="csc_measurement",e[e.current_time=10795]="current_time",e[e.cycling_power_control_point=10854]="cycling_power_control_point",e[e.cycling_power_feature=10853]="cycling_power_feature",e[e.cycling_power_measurement=10851]="cycling_power_measurement",e[e.cycling_power_vector=10852]="cycling_power_vector",e[e.database_change_increment=10905]="database_change_increment",e[e.date_of_birth=10885]="date_of_birth",e[e.date_of_threshold_assessment=10886]="date_of_threshold_assessment",e[e.date_time=10760]="date_time",e[e.day_date_time=10762]="day_date_time",e[e.day_of_week=10761]="day_of_week",e[e.descriptor_value_changed=10877]="descriptor_value_changed",e[e["gap.device_name"]=10752]="gap.device_name",e[e.dew_point=10875]="dew_point",e[e.digital=10838]="digital",e[e.dst_offset=10765]="dst_offset",e[e.elevation=10860]="elevation",e[e.email_address=10887]="email_address",e[e.exact_time_256=10764]="exact_time_256",e[e.fat_burn_heart_rate_lower_limit=10888]="fat_burn_heart_rate_lower_limit",e[e.fat_burn_heart_rate_upper_limit=10889]="fat_burn_heart_rate_upper_limit",e[e.firmware_revision_string=10790]="firmware_revision_string",e[e.first_name=10890]="first_name",e[e.five_zone_heart_rate_limits=10891]="five_zone_heart_rate_limits",e[e.floor_number=10930]="floor_number",e[e.gender=10892]="gender",e[e.glucose_feature=10833]="glucose_feature",e[e.glucose_measurement=10776]="glucose_measurement",e[e.glucose_measurement_context=10804]="glucose_measurement_context",e[e.gust_factor=10868]="gust_factor",e[e.hardware_revision_string=10791]="hardware_revision_string",e[e.heart_rate_control_point=10809]="heart_rate_control_point",e[e.heart_rate_max=10893]="heart_rate_max",e[e.heart_rate_measurement=10807]="heart_rate_measurement",e[e.heat_index=10874]="heat_index",e[e.height=10894]="height",e[e.hid_control_point=10828]="hid_control_point",e[e.hid_information=10826]="hid_information",e[e.hip_circumference=10895]="hip_circumference",e[e.humidity=10863]="humidity",e[e["ieee_11073-20601_regulatory_certification_data_list"]=10794]="ieee_11073-20601_regulatory_certification_data_list",e[e.indoor_positioning_configuration=10925]="indoor_positioning_configuration",e[e.intermediate_blood_pressure=10806]="intermediate_blood_pressure",e[e.intermediate_temperature=10782]="intermediate_temperature",e[e.irradiance=10871]="irradiance",e[e.language=10914]="language",e[e.last_name=10896]="last_name",e[e.latitude=10926]="latitude",e[e.ln_control_point=10859]="ln_control_point",e[e.ln_feature=10858]="ln_feature",e[e["local_east_coordinate.xml"]=10929]="local_east_coordinate.xml",e[e.local_north_coordinate=10928]="local_north_coordinate",e[e.local_time_information=10767]="local_time_information",e[e.location_and_speed=10855]="location_and_speed",e[e.location_name=10933]="location_name",e[e.longitude=10927]="longitude",e[e.magnetic_declination=10796]="magnetic_declination",e[e.magnetic_flux_density_2D=10912]="magnetic_flux_density_2D",e[e.magnetic_flux_density_3D=10913]="magnetic_flux_density_3D",e[e.manufacturer_name_string=10793]="manufacturer_name_string",e[e.maximum_recommended_heart_rate=10897]="maximum_recommended_heart_rate",e[e.measurement_interval=10785]="measurement_interval",e[e.model_number_string=10788]="model_number_string",e[e.navigation=10856]="navigation",e[e.new_alert=10822]="new_alert",e[e["gap.peripheral_preferred_connection_parameters"]=10756]="gap.peripheral_preferred_connection_parameters",e[e["gap.peripheral_privacy_flag"]=10754]="gap.peripheral_privacy_flag",e[e.plx_continuous_measurement=10847]="plx_continuous_measurement",e[e.plx_features=10848]="plx_features",e[e.plx_spot_check_measurement=10846]="plx_spot_check_measurement",e[e.pnp_id=10832]="pnp_id",e[e.pollen_concentration=10869]="pollen_concentration",e[e.position_quality=10857]="position_quality",e[e.pressure=10861]="pressure",e[e.protocol_mode=10830]="protocol_mode",e[e.rainfall=10872]="rainfall",e[e["gap.reconnection_address"]=10755]="gap.reconnection_address",e[e.record_access_control_point=10834]="record_access_control_point",e[e.reference_time_information=10772]="reference_time_information",e[e.report=10829]="report",e[e.report_map=10827]="report_map",e[e.resting_heart_rate=10898]="resting_heart_rate",e[e.ringer_control_point=10816]="ringer_control_point",e[e.ringer_setting=10817]="ringer_setting",e[e.rsc_feature=10836]="rsc_feature",e[e.rsc_measurement=10835]="rsc_measurement",e[e.sc_control_point=10837]="sc_control_point",e[e.scan_interval_window=10831]="scan_interval_window",e[e.scan_refresh=10801]="scan_refresh",e[e.sensor_location=10845]="sensor_location",e[e.serial_number_string=10789]="serial_number_string",e[e["gatt.service_changed"]=10757]="gatt.service_changed",e[e.software_revision_string=10792]="software_revision_string",e[e.sport_type_for_aerobic_and_anaerobic_thresholds=10899]="sport_type_for_aerobic_and_anaerobic_thresholds",e[e.supported_new_alert_category=10823]="supported_new_alert_category",e[e.supported_unread_alert_category=10824]="supported_unread_alert_category",e[e.system_id=10787]="system_id",e[e.temperature=10862]="temperature",e[e.temperature_measurement=10780]="temperature_measurement",e[e.temperature_type=10781]="temperature_type",e[e.three_zone_heart_rate_limits=10900]="three_zone_heart_rate_limits",e[e.time_accuracy=10770]="time_accuracy",e[e.time_source=10771]="time_source",e[e.time_update_control_point=10774]="time_update_control_point",e[e.time_update_state=10775]="time_update_state",e[e.time_with_dst=10769]="time_with_dst",e[e.time_zone=10766]="time_zone",e[e.true_wind_direction=10865]="true_wind_direction",e[e.true_wind_speed=10864]="true_wind_speed",e[e.two_zone_heart_rate_limit=10901]="two_zone_heart_rate_limit",e[e.tx_power_level=10759]="tx_power_level",e[e.uncertainty=10932]="uncertainty",e[e.unread_alert_status=10821]="unread_alert_status",e[e.user_control_point=10911]="user_control_point",e[e.user_index=10906]="user_index",e[e.uv_index=10870]="uv_index",e[e.vo2_max=10902]="vo2_max",e[e.waist_circumference=10903]="waist_circumference",e[e.weight=10904]="weight",e[e.weight_measurement=10909]="weight_measurement",e[e.weight_scale_feature=10910]="weight_scale_feature",e[e.wind_chill=10873]="wind_chill"}(a||(a={})),function(e){e[e["gatt.characteristic_extended_properties"]=10496]="gatt.characteristic_extended_properties",e[e["gatt.characteristic_user_description"]=10497]="gatt.characteristic_user_description",e[e["gatt.client_characteristic_configuration"]=10498]="gatt.client_characteristic_configuration",e[e["gatt.server_characteristic_configuration"]=10499]="gatt.server_characteristic_configuration",e[e["gatt.characteristic_presentation_format"]=10500]="gatt.characteristic_presentation_format",e[e["gatt.characteristic_aggregate_format"]=10501]="gatt.characteristic_aggregate_format",e[e.valid_range=10502]="valid_range",e[e.external_report_reference=10503]="external_report_reference",e[e.report_reference=10504]="report_reference",e[e.number_of_digitals=10505]="number_of_digitals",e[e.value_trigger_setting=10506]="value_trigger_setting",e[e.es_configuration=10507]="es_configuration",e[e.es_measurement=10508]="es_measurement",e[e.es_trigger_setting=10509]="es_trigger_setting",e[e.time_trigger_setting=10510]="time_trigger_setting"}(o||(o={}));class N extends _{constructor(){super(),this.deviceHandles={},this.serviceHandles={},this.characteristicHandles={},this.descriptorHandles={},this.charNotifies={},this.discoverFn=null,this.initialised=!1,this.enabled=!1,this.os="browser",this.enabled=this.state,e("stateChange",()=>{this.enabled!==this.state&&(this.enabled=this.state,this.emit(N.EVENT_ENABLED,this.enabled))})}get state(){return"poweredOn"===t}init(t){if(this.initialised)return t();e("discover",e=>{this.discoverFn&&this.discoverFn(e)}),this.initialised=!0,t()}checkForError(e,t,r){return function(i){if(i)e(i);else if("function"==typeof t){const e=[].slice.call(arguments,1);null===r?t.apply(this,e):setTimeout(()=>t.apply(this,e),r)}}}bufferToDataView(e){const t=new Uint8Array(e).buffer;return new DataView(t)}dataViewToBuffer(e){const t=new Uint8Array(e.buffer);return new Buffer(t)}validDevice(e,t){if(0===t.length)return!0;if(!e.advertisement.serviceUuids)return!1;const r=e.advertisement.serviceUuids.map(e=>b(e));return t.some(e=>r.indexOf(e)>=0)}deviceToBluetoothDevice(e){const t=e.address&&"unknown"!==e.address?e.address:e.id,r=[];e.advertisement.serviceUuids&&e.advertisement.serviceUuids.forEach(e=>{r.push(b(e))});const i=new Map;if(e.advertisement.manufacturerData){const t=e.advertisement.manufacturerData.readUInt16LE(0),r=e.advertisement.manufacturerData.slice(2);i.set(("0000"+t.toString(16)).slice(-4),this.bufferToDataView(r))}const n=new Map;return e.advertisement.serviceData&&e.advertisement.serviceData.forEach(e=>{n.set(b(e.uuid),this.bufferToDataView(e.data))}),{id:t,name:e.advertisement.localName,_serviceUUIDs:r,adData:{rssi:e.rssi,txPower:e.advertisement.txPowerLevel,serviceData:n,manufacturerData:i}}}getEnabled(e){function i(){e(this.state)}"unknown"===t||"poweredOff"===t?r("stateChange",i.bind(this)):i.call(this)}startScan(e,i,s,a){this.discoverFn=t=>{if(this.validDevice(t,e)){const e=this.deviceToBluetoothDevice(t);this.deviceHandles[e.id]||(this.deviceHandles[e.id]=t,i(e))}},this.init(()=>{function e(){!0===this.state?n([],!0,this.checkForError(a,s)):a("adapter not enabled")}this.deviceHandles={},"unknown"===t||"poweredOff"===t?r("stateChange",e.bind(this)):e.call(this)})}stopScan(e){this.discoverFn=null,i()}connect(e,t,r,i){const n=this.deviceHandles[e];n.removeAllListeners("connect"),n.removeAllListeners("disconnect"),n.once("connect",t),n.once("disconnect",()=>{this.serviceHandles={},this.characteristicHandles={},this.descriptorHandles={},this.charNotifies={},r()}),n.connect(this.checkForError(i))}disconnect(e,t){this.deviceHandles[e].disconnect(this.checkForError(t))}discoverServices(e,t,r,i){this.deviceHandles[e].discoverServices([],this.checkForError(i,e=>{const i=[];e.forEach(e=>{const r=b(e.uuid);(0===t.length||t.indexOf(r)>=0)&&(this.serviceHandles[r]||(this.serviceHandles[r]=e),i.push({uuid:r,primary:!0}))}),r(i)}))}discoverIncludedServices(e,t,r,i){this.serviceHandles[e].discoverIncludedServices([],this.checkForError(i,e=>{const i=[];e.forEach(e=>{const r=b(e.uuid);(0===t.length||t.indexOf(r)>=0)&&(this.serviceHandles[r]||(this.serviceHandles[r]=e),i.push({uuid:r,primary:!1}))},this),r(i)}))}discoverCharacteristics(e,t,r,i){this.serviceHandles[e].discoverCharacteristics([],this.checkForError(i,e=>{const i=[];e.forEach(e=>{const r=b(e.uuid);(0===t.length||t.indexOf(r)>=0)&&(this.characteristicHandles[r]||(this.characteristicHandles[r]=e),i.push({uuid:r,properties:{broadcast:e.properties.indexOf("broadcast")>=0,read:e.properties.indexOf("read")>=0,writeWithoutResponse:e.properties.indexOf("writeWithoutResponse")>=0,write:e.properties.indexOf("write")>=0,notify:e.properties.indexOf("notify")>=0,indicate:e.properties.indexOf("indicate")>=0,authenticatedSignedWrites:e.properties.indexOf("authenticatedSignedWrites")>=0,reliableWrite:e.properties.indexOf("reliableWrite")>=0,writableAuxiliaries:e.properties.indexOf("writableAuxiliaries")>=0}}),e.on("data",(e,t)=>{if(!0===t&&"function"==typeof this.charNotifies[r]){const t=this.bufferToDataView(e);this.charNotifies[r](t)}}))},this),r(i)}))}discoverDescriptors(e,t,r,i){const n=this.characteristicHandles[e];n.discoverDescriptors(this.checkForError(i,e=>{const i=[];e.forEach(e=>{const r=b(e.uuid);if(0===t.length||t.indexOf(r)>=0){const t=n.uuid+"-"+e.uuid;this.descriptorHandles[t]||(this.descriptorHandles[t]=e),i.push({uuid:r})}},this),r(i)}))}readCharacteristic(e,t,r){this.characteristicHandles[e].read(this.checkForError(r,e=>{const r=this.bufferToDataView(e);t(r)}))}writeCharacteristic(e,t,r,i){const n=this.dataViewToBuffer(t),s=this.characteristicHandles[e],a=s.properties.indexOf("writeWithoutResponse")>=0||s.properties.indexOf("authenticatedSignedWrites")>=0,o="darwin"!==this.os&&a?25:null;s.write(n,a,this.checkForError(i,r,o))}enableNotify(e,t,r,i){if(this.charNotifies[e])return this.charNotifies[e]=t,r();this.characteristicHandles[e].once("notify",n=>{if(!0!==n)return i("notify failed to enable");this.charNotifies[e]=t,r()}),this.characteristicHandles[e].notify(!0,this.checkForError(i))}disableNotify(e,t,r){if(!this.charNotifies[e])return t();this.characteristicHandles[e].once("notify",i=>{if(!1!==i)return r("notify failed to disable");this.charNotifies[e]&&delete this.charNotifies[e],t()}),this.characteristicHandles[e].notify(!1,this.checkForError(r))}readDescriptor(e,t,r){this.descriptorHandles[e].readValue(this.checkForError(r,e=>{const r=this.bufferToDataView(e);t(r)}))}writeDescriptor(e,t,r,i){const n=this.dataViewToBuffer(t);this.descriptorHandles[e].writeValue(n,this.checkForError(i,r))}}N.EVENT_ENABLED="enabledchanged";const T=new N;class V{constructor(e){this.characteristic=null,this.uuid=null,this._value=null,this.handle=null,this.characteristic=e.characteristic,this.uuid=e.uuid,this._value=e.value,this.handle=`${this.characteristic.uuid}-${this.uuid}`}get value(){return this._value}readValue(){return new Promise((e,t)=>{if(!this.characteristic.service.device.gatt.connected)return t("readValue error: device not connected");T.readDescriptor(this.handle,t=>{this._value=t,e(t)},e=>{t(`readValue error: ${e}`)})})}writeValue(e){return new Promise((t,r)=>{if(!this.characteristic.service.device.gatt.connected)return r("writeValue error: device not connected");const i=function(e){return void 0!==e.buffer}(e)?e.buffer:e,n=new DataView(i);T.writeDescriptor(this.handle,n,()=>{this._value=n,t()},e=>{r(`writeValue error: ${e}`)})})}}class L extends y{constructor(e){super(),this.service=null,this.uuid=null,this._value=null,this.handle=null,this.descriptors=null,this.service=e.service,this.uuid=e.uuid,this.properties=e.properties,this._value=e.value,this.handle=this.uuid}get value(){return this._value}setValue(e,t){this._value=e,t&&(this.dispatchEvent(L.EVENT_CHANGED,e),this.service.dispatchEvent(L.EVENT_CHANGED,e),this.service.device.dispatchEvent(L.EVENT_CHANGED,e),this.service.device._bluetooth.dispatchEvent(L.EVENT_CHANGED,e))}getDescriptor(e){return new Promise((t,r)=>this.service.device.gatt.connected?e?void this.getDescriptors(e).then(e=>{if(1!==e.length)return r("getDescriptor error: descriptor not found");t(e[0])}).catch(e=>{r(`getDescriptor error: ${e}`)}):r("getDescriptor error: no descriptor specified"):r("getDescriptor error: device not connected"))}getDescriptors(e){return new Promise((t,r)=>{if(!this.service.device.gatt.connected)return r("getDescriptors error: device not connected");function i(){if(!e)return t(this.descriptors);const i=this.descriptors.filter(t=>t.uuid===x(e));if(1!==i.length)return r("getDescriptors error: descriptor not found");t(i)}if(this.descriptors)return i.call(this);T.discoverDescriptors(this.handle,[],e=>{this.descriptors=e.map(e=>(Object.assign(e,{characteristic:this}),new V(e))),i.call(this)},e=>{r(`getDescriptors error: ${e}`)})})}readValue(){return new Promise((e,t)=>{if(!this.service.device.gatt.connected)return t("readValue error: device not connected");T.readCharacteristic(this.handle,t=>{this.setValue(t,!0),e(t)},e=>{t(`readValue error: ${e}`)})})}writeValue(e){return new Promise((t,r)=>{if(!this.service.device.gatt.connected)return r("writeValue error: device not connected");const i=function(e){return void 0!==e.buffer}(e)?e.buffer:e,n=new DataView(i);T.writeCharacteristic(this.handle,n,()=>{this.setValue(n),t()},e=>{r(`writeValue error: ${e}`)})})}startNotifications(){return new Promise((e,t)=>{if(!this.service.device.gatt.connected)return t("startNotifications error: device not connected");T.enableNotify(this.handle,e=>{this.setValue(e,!0)},()=>{e(this)},e=>{t(`startNotifications error: ${e}`)})})}stopNotifications(){return new Promise((e,t)=>{if(!this.service.device.gatt.connected)return t("stopNotifications error: device not connected");T.disableNotify(this.handle,()=>{e(this)},e=>{t(`stopNotifications error: ${e}`)})})}}L.EVENT_CHANGED="characteristicvaluechanged";class C extends y{constructor(e){super(),this.device=null,this.uuid=null,this.isPrimary=!1,this.handle=null,this.services=null,this.characteristics=null,this.device=e.device,this.uuid=e.uuid,this.isPrimary=e.isPrimary,this.handle=this.uuid,this.dispatchEvent(C.EVENT_ADDED),this.device.dispatchEvent(C.EVENT_ADDED),this.device._bluetooth.dispatchEvent(C.EVENT_ADDED)}getCharacteristic(e){return new Promise((t,r)=>this.device.gatt.connected?e?void this.getCharacteristics(e).then(e=>{if(1!==e.length)return r("getCharacteristic error: characteristic not found");t(e[0])}).catch(e=>{r(`getCharacteristic error: ${e}`)}):r("getCharacteristic error: no characteristic specified"):r("getCharacteristic error: device not connected"))}getCharacteristics(e){return new Promise((t,r)=>{if(!this.device.gatt.connected)return r("getCharacteristics error: device not connected");function i(){if(!e)return t(this.characteristics);e=D(e);const i=this.characteristics.filter(t=>t.uuid===e);if(1!==i.length)return r("getCharacteristics error: characteristic not found");t(i)}if(this.characteristics)return i.call(this);T.discoverCharacteristics(this.handle,[],e=>{this.characteristics=e.map(e=>(Object.assign(e,{service:this}),new L(e))),i.call(this)},e=>{r(`getCharacteristics error: ${e}`)})})}getIncludedService(e){return new Promise((t,r)=>this.device.gatt.connected?e?void this.getIncludedServices(e).then(e=>{if(1!==e.length)return r("getIncludedService error: service not found");t(e[0])}).catch(e=>{r(`getIncludedService error: ${e}`)}):r("getIncludedService error: no service specified"):r("getIncludedService error: device not connected"))}getIncludedServices(e){return new Promise((t,r)=>{if(!this.device.gatt.connected)return r("getIncludedServices error: device not connected");function i(){if(!e)return t(this.services);const i=this.services.filter(t=>t.uuid===E(e));if(1!==i.length)return r("getIncludedServices error: service not found");t(i)}if(this.services)return i.call(this);T.discoverIncludedServices(this.handle,this.device._allowedServices,e=>{this.services=e.map(e=>(Object.assign(e,{device:this.device}),new C(e))),i.call(this)},e=>{r(`getIncludedServices error: ${e}`)})})}}C.EVENT_ADDED="serviceadded",C.EVENT_CHANGED="servicechanged",C.EVENT_REMOVED="serviceremoved";class S{constructor(e){this.device=null,this._connected=!1,this.handle=null,this.services=null,this.device=e,this.handle=this.device.id}get connected(){return this._connected}connect(){return new Promise((e,t)=>{if(this.connected)return t("connect error: device already connected");T.connect(this.handle,()=>{this._connected=!0,e(this)},()=>{this.services=null,this._connected=!1,this.device.dispatchEvent(P.EVENT_DISCONNECTED),this.device._bluetooth.dispatchEvent(P.EVENT_DISCONNECTED)},e=>{t(`connect Error: ${e}`)})})}disconnect(){T.disconnect(this.handle),this._connected=!1}getPrimaryService(e){return new Promise((t,r)=>this.connected?e?void this.getPrimaryServices(e).then(e=>{if(1!==e.length)return r("getPrimaryService error: service not found");t(e[0])}).catch(e=>{r(`getPrimaryService error: ${e}`)}):r("getPrimaryService error: no service specified"):r("getPrimaryService error: device not connected"))}getPrimaryServices(e){return new Promise((t,r)=>{if(!this.connected)return r("getPrimaryServices error: device not connected");function i(){if(!e)return t(this.services);const i=this.services.filter(t=>t.uuid===E(e));if(1!==i.length)return r("getPrimaryServices error: service not found");t(i)}if(this.services)return i.call(this);T.discoverServices(this.handle,this.device._allowedServices,e=>{this.services=e.map(e=>(Object.assign(e,{device:this.device}),new C(e))),i.call(this)},e=>{r(`getPrimaryServices error: ${e}`)})})}}class P extends y{constructor(e){super(),this.id=null,this.name=null,this.gatt=null,this.watchingAdvertisements=!1,this._bluetooth=null,this._allowedServices=[],this._serviceUUIDs=[],this.id=e.id,this.name=e.name,this.gatt=e.gatt,this.watchAdvertisements=e.watchAdvertisements,this.adData=e.adData,this._bluetooth=e._bluetooth,this._allowedServices=e._allowedServices,this._serviceUUIDs=e._serviceUUIDs,this.name||(this.name=`Unknown or Unsupported Device (${this.id})`),this.gatt||(this.gatt=new S(this))}watchAdvertisements(){return new Promise((e,t)=>{t("watchAdvertisements error: method not implemented")})}unwatchAdvertisements(){return new Promise((e,t)=>{t("unwatchAdvertisements error: method not implemented")})}}P.EVENT_DISCONNECTED="gattserverdisconnected",P.EVENT_ADVERT="advertisementreceived";class A extends y{constructor(e){super(),this.deviceFound=null,this.scanTime=10240,this.scanner=null,e=e||{},this.referringDevice=e.referringDevice,this.deviceFound=e.deviceFound,e.scanTime&&(this.scanTime=1e3*e.scanTime),T.on(N.EVENT_ENABLED,e=>{this.dispatchEvent(A.EVENT_AVAILABILITY,e)})}filterDevice(e,t,r){let i=!1;return e.filters.forEach(e=>{if(!e.name||e.name===t.name){if(e.namePrefix){if(!t.name||e.namePrefix.length>t.name.length)return;if(e.namePrefix!==t.name.substr(0,e.namePrefix.length))return}if(e.services){const i=e.services.map(E);if(!i.every(e=>t._serviceUUIDs.indexOf(e)>-1))return;r=r.concat(i)}i=!0}}),!!i&&t}getAvailability(){return new Promise((e,t)=>{T.getEnabled(t=>{e(t)})})}requestDevice(e){return new Promise((t,r)=>{if(e=e||{},null!==this.scanner)return r("requestDevice error: request in progress");if(!e.acceptAllDevices&&!this.deviceFound){if(!e.filters||0===e.filters.length)return r(new TypeError("requestDevice error: no filters specified"));if(e.filters.some(e=>0===Object.keys(e).length))return r(new TypeError("requestDevice error: empty filter specified"));if(e.filters.some(e=>void 0!==e.namePrefix&&""===e.namePrefix))return r(new TypeError("requestDevice error: empty namePrefix specified"))}let i=[];e.filters&&e.filters.forEach(e=>{e.services&&(i=i.concat(e.services.map(E)))}),i=i.filter((e,t,r)=>r.indexOf(e)===t);let n=!1;T.startScan(i,r=>{let i=[];function s(e){this.cancelRequest().then(()=>{t(e)})}if(e.filters&&(r=this.filterDevice(e,r,i)),r){n=!0,e.optionalServices&&(i=i.concat(e.optionalServices.map(E)));const t=i.filter((e,t,r)=>r.indexOf(e)===t);Object.assign(r,{_bluetooth:this,_allowedServices:t});const o=new P(r);function a(){s.call(this,o)}this.deviceFound&&!0!==this.deviceFound(o,a.bind(this))||s.call(this,o)}},()=>{this.scanner=setTimeout(()=>{this.cancelRequest().then(()=>{n||r("requestDevice error: no devices found")})},this.scanTime)},e=>r(`requestDevice error: ${e}`))})}cancelRequest(){return new Promise((e,t)=>{this.scanner&&(clearTimeout(this.scanner),this.scanner=null,T.stopScan()),e()})}}A.EVENT_AVAILABILITY="availabilitychanged";const k=new A;export{A as Bluetooth,P as BluetoothDevice,L as BluetoothRemoteGATTCharacteristic,V as BluetoothRemoteGATTDescriptor,S as BluetoothRemoteGATTServer,C as BluetoothRemoteGATTService,k as bluetooth,a as bluetoothCharacteristics,o as bluetoothDescriptors,s as bluetoothServices,b as getCanonicalUUID,D as getCharacteristicUUID,x as getDescriptorUUID,E as getServiceUUID};
import{on as e,state as t,once as i,stopScanning as r,startScanning as n}from"@abandonware/noble";var s,a,c;function o(){}function d(){d.init.call(this)}function h(e){return void 0===e._maxListeners?d.defaultMaxListeners:e._maxListeners}function _(e,t,i){if(t)e.call(i);else for(var r=e.length,n=w(e,r),s=0;s<r;++s)n[s].call(i)}function l(e,t,i,r){if(t)e.call(i,r);else for(var n=e.length,s=w(e,n),a=0;a<n;++a)s[a].call(i,r)}function u(e,t,i,r,n){if(t)e.call(i,r,n);else for(var s=e.length,a=w(e,s),c=0;c<s;++c)a[c].call(i,r,n)}function v(e,t,i,r,n,s){if(t)e.call(i,r,n,s);else for(var a=e.length,c=w(e,a),o=0;o<a;++o)c[o].call(i,r,n,s)}function m(e,t,i,r){if(t)e.apply(i,r);else for(var n=e.length,s=w(e,n),a=0;a<n;++a)s[a].apply(i,r)}function f(e,t,i,r){var n,s,a,c;if("function"!=typeof i)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),a=s[t]):(s=e._events=new o,e._eventsCount=0),a){if("function"==typeof a?a=s[t]=r?[i,a]:[a,i]:r?a.unshift(i):a.push(i),!a.warned&&(n=h(e))&&n>0&&a.length>n){a.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=a.length,c=d,"function"==typeof console.warn?console.warn(c):console.log(c)}}else a=s[t]=i,++e._eventsCount;return e}function p(e,t,i){var r=!1;function n(){e.removeListener(t,n),r||(r=!0,i.apply(e,arguments))}return n.listener=i,n}function g(e){var t=this._events;if(t){var i=t[e];if("function"==typeof i)return 1;if(i)return i.length}return 0}function w(e,t){for(var i=new Array(t);t--;)i[t]=e[t];return i}o.prototype=Object.create(null),d.EventEmitter=d,d.usingDomains=!1,d.prototype.domain=void 0,d.prototype._events=void 0,d.prototype._maxListeners=void 0,d.defaultMaxListeners=10,d.init=function(){this.domain=null,d.usingDomains&&(void 0).active&&(void 0).Domain,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new o,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},d.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},d.prototype.getMaxListeners=function(){return h(this)},d.prototype.emit=function(e){var t,i,r,n,s,a,c,o="error"===e;if(a=this._events)o=o&&null==a.error;else if(!o)return!1;if(c=this.domain,o){if(t=arguments[1],!c){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=c,t.domainThrown=!1,c.emit("error",t),!1}if(!(i=a[e]))return!1;var h="function"==typeof i;switch(r=arguments.length){case 1:_(i,h,this);break;case 2:l(i,h,this,arguments[1]);break;case 3:u(i,h,this,arguments[1],arguments[2]);break;case 4:v(i,h,this,arguments[1],arguments[2],arguments[3]);break;default:for(n=new Array(r-1),s=1;s<r;s++)n[s-1]=arguments[s];m(i,h,this,n)}return!0},d.prototype.addListener=function(e,t){return f(this,e,t,!1)},d.prototype.on=d.prototype.addListener,d.prototype.prependListener=function(e,t){return f(this,e,t,!0)},d.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,p(this,e,t)),this},d.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,p(this,e,t)),this},d.prototype.removeListener=function(e,t){var i,r,n,s,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(r=this._events))return this;if(!(i=r[e]))return this;if(i===t||i.listener&&i.listener===t)0==--this._eventsCount?this._events=new o:(delete r[e],r.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(n=-1,s=i.length;s-- >0;)if(i[s]===t||i[s].listener&&i[s].listener===t){a=i[s].listener,n=s;break}if(n<0)return this;if(1===i.length){if(i[0]=void 0,0==--this._eventsCount)return this._events=new o,this;delete r[e]}else!function(e,t){for(var i=t,r=i+1,n=e.length;r<n;i+=1,r+=1)e[i]=e[r];e.pop()}(i,n);r.removeListener&&this.emit("removeListener",e,a||t)}return this},d.prototype.removeAllListeners=function(e){var t,i;if(!(i=this._events))return this;if(!i.removeListener)return 0===arguments.length?(this._events=new o,this._eventsCount=0):i[e]&&(0==--this._eventsCount?this._events=new o:delete i[e]),this;if(0===arguments.length){for(var r,n=Object.keys(i),s=0;s<n.length;++s)"removeListener"!==(r=n[s])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=new o,this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},d.prototype.listeners=function(e){var t,i=this._events;return i&&(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(t):[]},d.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},d.prototype.listenerCount=g,d.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class b extends d{constructor(){super(...arguments),this.isEventListenerObject=e=>void 0!==e.handleEvent}addEventListener(e,t){if(t){const i=this.isEventListenerObject(t)?t.handleEvent:t;super.addListener(e,i)}}removeEventListener(e,t){if(t){const i=this.isEventListenerObject(t)?t.handleEvent:t;super.removeListener(e,i)}}dispatchEvent(e){return super.emit(e.type,e)}}function y(e){return"number"==typeof e&&(e=e.toString(16)),(e=e.toLowerCase()).length<=8&&(e=("00000000"+e).slice(-8)+"-0000-1000-8000-00805f9b34fb"),32===e.length&&(e=e.match(/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/).splice(1).join("-")),e}function E(e){return"string"==typeof e&&s[e]&&(e=s[e]),y(e)}function x(e){return"string"==typeof e&&a[e]&&(e=a[e]),y(e)}function L(e){return"string"==typeof e&&c[e]&&(e=c[e]),y(e)}!function(e){e[e.alert_notification=6161]="alert_notification",e[e.automation_io=6165]="automation_io",e[e.battery_service=6159]="battery_service",e[e.blood_pressure=6160]="blood_pressure",e[e.body_composition=6171]="body_composition",e[e.bond_management=6174]="bond_management",e[e.continuous_glucose_monitoring=6175]="continuous_glucose_monitoring",e[e.current_time=6149]="current_time",e[e.cycling_power=6168]="cycling_power",e[e.cycling_speed_and_cadence=6166]="cycling_speed_and_cadence",e[e.device_information=6154]="device_information",e[e.environmental_sensing=6170]="environmental_sensing",e[e.generic_access=6144]="generic_access",e[e.generic_attribute=6145]="generic_attribute",e[e.glucose=6152]="glucose",e[e.health_thermometer=6153]="health_thermometer",e[e.heart_rate=6157]="heart_rate",e[e.human_interface_device=6162]="human_interface_device",e[e.immediate_alert=6146]="immediate_alert",e[e.indoor_positioning=6177]="indoor_positioning",e[e.internet_protocol_support=6176]="internet_protocol_support",e[e.link_loss=6147]="link_loss",e[e.location_and_navigation=6169]="location_and_navigation",e[e.next_dst_change=6151]="next_dst_change",e[e.phone_alert_status=6158]="phone_alert_status",e[e.pulse_oximeter=6178]="pulse_oximeter",e[e.reference_time_update=6150]="reference_time_update",e[e.running_speed_and_cadence=6164]="running_speed_and_cadence",e[e.scan_parameters=6163]="scan_parameters",e[e.tx_power=6148]="tx_power",e[e.user_data=6172]="user_data",e[e.weight_scale=6173]="weight_scale"}(s||(s={})),function(e){e[e.aerobic_heart_rate_lower_limit=10878]="aerobic_heart_rate_lower_limit",e[e.aerobic_heart_rate_upper_limit=10884]="aerobic_heart_rate_upper_limit",e[e.aerobic_threshold=10879]="aerobic_threshold",e[e.age=10880]="age",e[e.aggregate=10842]="aggregate",e[e.alert_category_id=10819]="alert_category_id",e[e.alert_category_id_bit_mask=10818]="alert_category_id_bit_mask",e[e.alert_level=10758]="alert_level",e[e.alert_notification_control_point=10820]="alert_notification_control_point",e[e.alert_status=10815]="alert_status",e[e.altitude=10931]="altitude",e[e.anaerobic_heart_rate_lower_limit=10881]="anaerobic_heart_rate_lower_limit",e[e.anaerobic_heart_rate_upper_limit=10882]="anaerobic_heart_rate_upper_limit",e[e.anaerobic_threshold=10883]="anaerobic_threshold",e[e.analog=10840]="analog",e[e.apparent_wind_direction=10867]="apparent_wind_direction",e[e.apparent_wind_speed=10866]="apparent_wind_speed",e[e["gap.appearance"]=10753]="gap.appearance",e[e.barometric_pressure_trend=10915]="barometric_pressure_trend",e[e.battery_level=10777]="battery_level",e[e.blood_pressure_feature=10825]="blood_pressure_feature",e[e.blood_pressure_measurement=10805]="blood_pressure_measurement",e[e.body_composition_feature=10907]="body_composition_feature",e[e.body_composition_measurement=10908]="body_composition_measurement",e[e.body_sensor_location=10808]="body_sensor_location",e[e.bond_management_control_point=10916]="bond_management_control_point",e[e.bond_management_feature=10917]="bond_management_feature",e[e.boot_keyboard_input_report=10786]="boot_keyboard_input_report",e[e.boot_keyboard_output_report=10802]="boot_keyboard_output_report",e[e.boot_mouse_input_report=10803]="boot_mouse_input_report",e[e["gap.central_address_resolution_support"]=10918]="gap.central_address_resolution_support",e[e.cgm_feature=10920]="cgm_feature",e[e.cgm_measurement=10919]="cgm_measurement",e[e.cgm_session_run_time=10923]="cgm_session_run_time",e[e.cgm_session_start_time=10922]="cgm_session_start_time",e[e.cgm_specific_ops_control_point=10924]="cgm_specific_ops_control_point",e[e.cgm_status=10921]="cgm_status",e[e.csc_feature=10844]="csc_feature",e[e.csc_measurement=10843]="csc_measurement",e[e.current_time=10795]="current_time",e[e.cycling_power_control_point=10854]="cycling_power_control_point",e[e.cycling_power_feature=10853]="cycling_power_feature",e[e.cycling_power_measurement=10851]="cycling_power_measurement",e[e.cycling_power_vector=10852]="cycling_power_vector",e[e.database_change_increment=10905]="database_change_increment",e[e.date_of_birth=10885]="date_of_birth",e[e.date_of_threshold_assessment=10886]="date_of_threshold_assessment",e[e.date_time=10760]="date_time",e[e.day_date_time=10762]="day_date_time",e[e.day_of_week=10761]="day_of_week",e[e.descriptor_value_changed=10877]="descriptor_value_changed",e[e["gap.device_name"]=10752]="gap.device_name",e[e.dew_point=10875]="dew_point",e[e.digital=10838]="digital",e[e.dst_offset=10765]="dst_offset",e[e.elevation=10860]="elevation",e[e.email_address=10887]="email_address",e[e.exact_time_256=10764]="exact_time_256",e[e.fat_burn_heart_rate_lower_limit=10888]="fat_burn_heart_rate_lower_limit",e[e.fat_burn_heart_rate_upper_limit=10889]="fat_burn_heart_rate_upper_limit",e[e.firmware_revision_string=10790]="firmware_revision_string",e[e.first_name=10890]="first_name",e[e.five_zone_heart_rate_limits=10891]="five_zone_heart_rate_limits",e[e.floor_number=10930]="floor_number",e[e.gender=10892]="gender",e[e.glucose_feature=10833]="glucose_feature",e[e.glucose_measurement=10776]="glucose_measurement",e[e.glucose_measurement_context=10804]="glucose_measurement_context",e[e.gust_factor=10868]="gust_factor",e[e.hardware_revision_string=10791]="hardware_revision_string",e[e.heart_rate_control_point=10809]="heart_rate_control_point",e[e.heart_rate_max=10893]="heart_rate_max",e[e.heart_rate_measurement=10807]="heart_rate_measurement",e[e.heat_index=10874]="heat_index",e[e.height=10894]="height",e[e.hid_control_point=10828]="hid_control_point",e[e.hid_information=10826]="hid_information",e[e.hip_circumference=10895]="hip_circumference",e[e.humidity=10863]="humidity",e[e["ieee_11073-20601_regulatory_certification_data_list"]=10794]="ieee_11073-20601_regulatory_certification_data_list",e[e.indoor_positioning_configuration=10925]="indoor_positioning_configuration",e[e.intermediate_blood_pressure=10806]="intermediate_blood_pressure",e[e.intermediate_temperature=10782]="intermediate_temperature",e[e.irradiance=10871]="irradiance",e[e.language=10914]="language",e[e.last_name=10896]="last_name",e[e.latitude=10926]="latitude",e[e.ln_control_point=10859]="ln_control_point",e[e.ln_feature=10858]="ln_feature",e[e["local_east_coordinate.xml"]=10929]="local_east_coordinate.xml",e[e.local_north_coordinate=10928]="local_north_coordinate",e[e.local_time_information=10767]="local_time_information",e[e.location_and_speed=10855]="location_and_speed",e[e.location_name=10933]="location_name",e[e.longitude=10927]="longitude",e[e.magnetic_declination=10796]="magnetic_declination",e[e.magnetic_flux_density_2D=10912]="magnetic_flux_density_2D",e[e.magnetic_flux_density_3D=10913]="magnetic_flux_density_3D",e[e.manufacturer_name_string=10793]="manufacturer_name_string",e[e.maximum_recommended_heart_rate=10897]="maximum_recommended_heart_rate",e[e.measurement_interval=10785]="measurement_interval",e[e.model_number_string=10788]="model_number_string",e[e.navigation=10856]="navigation",e[e.new_alert=10822]="new_alert",e[e["gap.peripheral_preferred_connection_parameters"]=10756]="gap.peripheral_preferred_connection_parameters",e[e["gap.peripheral_privacy_flag"]=10754]="gap.peripheral_privacy_flag",e[e.plx_continuous_measurement=10847]="plx_continuous_measurement",e[e.plx_features=10848]="plx_features",e[e.plx_spot_check_measurement=10846]="plx_spot_check_measurement",e[e.pnp_id=10832]="pnp_id",e[e.pollen_concentration=10869]="pollen_concentration",e[e.position_quality=10857]="position_quality",e[e.pressure=10861]="pressure",e[e.protocol_mode=10830]="protocol_mode",e[e.rainfall=10872]="rainfall",e[e["gap.reconnection_address"]=10755]="gap.reconnection_address",e[e.record_access_control_point=10834]="record_access_control_point",e[e.reference_time_information=10772]="reference_time_information",e[e.report=10829]="report",e[e.report_map=10827]="report_map",e[e.resting_heart_rate=10898]="resting_heart_rate",e[e.ringer_control_point=10816]="ringer_control_point",e[e.ringer_setting=10817]="ringer_setting",e[e.rsc_feature=10836]="rsc_feature",e[e.rsc_measurement=10835]="rsc_measurement",e[e.sc_control_point=10837]="sc_control_point",e[e.scan_interval_window=10831]="scan_interval_window",e[e.scan_refresh=10801]="scan_refresh",e[e.sensor_location=10845]="sensor_location",e[e.serial_number_string=10789]="serial_number_string",e[e["gatt.service_changed"]=10757]="gatt.service_changed",e[e.software_revision_string=10792]="software_revision_string",e[e.sport_type_for_aerobic_and_anaerobic_thresholds=10899]="sport_type_for_aerobic_and_anaerobic_thresholds",e[e.supported_new_alert_category=10823]="supported_new_alert_category",e[e.supported_unread_alert_category=10824]="supported_unread_alert_category",e[e.system_id=10787]="system_id",e[e.temperature=10862]="temperature",e[e.temperature_measurement=10780]="temperature_measurement",e[e.temperature_type=10781]="temperature_type",e[e.three_zone_heart_rate_limits=10900]="three_zone_heart_rate_limits",e[e.time_accuracy=10770]="time_accuracy",e[e.time_source=10771]="time_source",e[e.time_update_control_point=10774]="time_update_control_point",e[e.time_update_state=10775]="time_update_state",e[e.time_with_dst=10769]="time_with_dst",e[e.time_zone=10766]="time_zone",e[e.true_wind_direction=10865]="true_wind_direction",e[e.true_wind_speed=10864]="true_wind_speed",e[e.two_zone_heart_rate_limit=10901]="two_zone_heart_rate_limit",e[e.tx_power_level=10759]="tx_power_level",e[e.uncertainty=10932]="uncertainty",e[e.unread_alert_status=10821]="unread_alert_status",e[e.user_control_point=10911]="user_control_point",e[e.user_index=10906]="user_index",e[e.uv_index=10870]="uv_index",e[e.vo2_max=10902]="vo2_max",e[e.waist_circumference=10903]="waist_circumference",e[e.weight=10904]="weight",e[e.weight_measurement=10909]="weight_measurement",e[e.weight_scale_feature=10910]="weight_scale_feature",e[e.wind_chill=10873]="wind_chill"}(a||(a={})),function(e){e[e["gatt.characteristic_extended_properties"]=10496]="gatt.characteristic_extended_properties",e[e["gatt.characteristic_user_description"]=10497]="gatt.characteristic_user_description",e[e["gatt.client_characteristic_configuration"]=10498]="gatt.client_characteristic_configuration",e[e["gatt.server_characteristic_configuration"]=10499]="gatt.server_characteristic_configuration",e[e["gatt.characteristic_presentation_format"]=10500]="gatt.characteristic_presentation_format",e[e["gatt.characteristic_aggregate_format"]=10501]="gatt.characteristic_aggregate_format",e[e.valid_range=10502]="valid_range",e[e.external_report_reference=10503]="external_report_reference",e[e.report_reference=10504]="report_reference",e[e.number_of_digitals=10505]="number_of_digitals",e[e.value_trigger_setting=10506]="value_trigger_setting",e[e.es_configuration=10507]="es_configuration",e[e.es_measurement=10508]="es_measurement",e[e.es_trigger_setting=10509]="es_trigger_setting",e[e.time_trigger_setting=10510]="time_trigger_setting"}(c||(c={}));class D extends d{constructor(){super(),this.deviceHandles={},this.serviceHandles={},this.characteristicHandles={},this.descriptorHandles={},this.charNotifies={},this.discoverFn=null,this.initialised=!1,this.enabled=!1,this.os="browser",this.enabled=this.state,e("stateChange",()=>{this.enabled!==this.state&&(this.enabled=this.state,this.emit(D.EVENT_ENABLED,this.enabled))})}get state(){return"poweredOn"===t}init(t){if(this.initialised)return t();e("discover",e=>{this.discoverFn&&this.discoverFn(e)}),this.initialised=!0,t()}checkForError(e,t,i){return function(r){if(r)e(r);else if("function"==typeof t){const e=[].slice.call(arguments,1);null===i?t.apply(this,e):setTimeout(()=>t.apply(this,e),i)}}}bufferToDataView(e){const t=new Uint8Array(e).buffer;return new DataView(t)}dataViewToBuffer(e){const t=new Uint8Array(e.buffer);return new Buffer(t)}validDevice(e,t){if(0===t.length)return!0;if(!e.advertisement.serviceUuids)return!1;const i=e.advertisement.serviceUuids.map(e=>y(e));return t.some(e=>i.indexOf(e)>=0)}deviceToBluetoothDevice(e){const t=e.address&&"unknown"!==e.address?e.address:e.id,i=[];e.advertisement.serviceUuids&&e.advertisement.serviceUuids.forEach(e=>{i.push(y(e))});const r=new Map;if(e.advertisement.manufacturerData){const t=e.advertisement.manufacturerData.readUInt16LE(0),i=e.advertisement.manufacturerData.slice(2);r.set(("0000"+t.toString(16)).slice(-4),this.bufferToDataView(i))}const n=new Map;return e.advertisement.serviceData&&e.advertisement.serviceData.forEach(e=>{n.set(y(e.uuid),this.bufferToDataView(e.data))}),{id:t,name:e.advertisement.localName,_serviceUUIDs:i,adData:{rssi:e.rssi,txPower:e.advertisement.txPowerLevel,serviceData:n,manufacturerData:r}}}getEnabled(e){function r(){e(this.state)}"unknown"===t||"poweredOff"===t?i("stateChange",r.bind(this)):r.call(this)}startScan(e,r,s,a){this.discoverFn=t=>{if(this.validDevice(t,e)){const e=this.deviceToBluetoothDevice(t);this.deviceHandles[e.id]||(this.deviceHandles[e.id]=t,r(e))}},this.init(()=>{function e(){!0===this.state?n([],!0,this.checkForError(a,s)):a("adapter not enabled")}this.deviceHandles={},"unknown"===t||"poweredOff"===t?i("stateChange",e.bind(this)):e.call(this)})}stopScan(e){this.discoverFn=null,r()}connect(e,t,i,r){const n=this.deviceHandles[e];n.removeAllListeners("connect"),n.removeAllListeners("disconnect"),n.once("connect",t),n.once("disconnect",()=>{this.serviceHandles={},this.characteristicHandles={},this.descriptorHandles={},this.charNotifies={},i()}),n.connect(this.checkForError(r))}disconnect(e,t){this.deviceHandles[e].disconnect(this.checkForError(t))}discoverServices(e,t,i,r){this.deviceHandles[e].discoverServices([],this.checkForError(r,e=>{const r=[];e.forEach(e=>{const i=y(e.uuid);(0===t.length||t.indexOf(i)>=0)&&(this.serviceHandles[i]||(this.serviceHandles[i]=e),r.push({uuid:i,primary:!0}))}),i(r)}))}discoverIncludedServices(e,t,i,r){this.serviceHandles[e].discoverIncludedServices([],this.checkForError(r,e=>{const r=[];e.forEach(e=>{const i=y(e.uuid);(0===t.length||t.indexOf(i)>=0)&&(this.serviceHandles[i]||(this.serviceHandles[i]=e),r.push({uuid:i,primary:!1}))},this),i(r)}))}discoverCharacteristics(e,t,i,r){this.serviceHandles[e].discoverCharacteristics([],this.checkForError(r,e=>{const r=[];e.forEach(e=>{const i=y(e.uuid);(0===t.length||t.indexOf(i)>=0)&&(this.characteristicHandles[i]||(this.characteristicHandles[i]=e),r.push({uuid:i,properties:{broadcast:e.properties.indexOf("broadcast")>=0,read:e.properties.indexOf("read")>=0,writeWithoutResponse:e.properties.indexOf("writeWithoutResponse")>=0,write:e.properties.indexOf("write")>=0,notify:e.properties.indexOf("notify")>=0,indicate:e.properties.indexOf("indicate")>=0,authenticatedSignedWrites:e.properties.indexOf("authenticatedSignedWrites")>=0,reliableWrite:e.properties.indexOf("reliableWrite")>=0,writableAuxiliaries:e.properties.indexOf("writableAuxiliaries")>=0}}),e.on("data",(e,t)=>{if(!0===t&&"function"==typeof this.charNotifies[i]){const t=this.bufferToDataView(e);this.charNotifies[i](t)}}))},this),i(r)}))}discoverDescriptors(e,t,i,r){const n=this.characteristicHandles[e];n.discoverDescriptors(this.checkForError(r,e=>{const r=[];e.forEach(e=>{const i=y(e.uuid);if(0===t.length||t.indexOf(i)>=0){const t=n.uuid+"-"+e.uuid;this.descriptorHandles[t]||(this.descriptorHandles[t]=e),r.push({uuid:i})}},this),i(r)}))}readCharacteristic(e,t,i){this.characteristicHandles[e].read(this.checkForError(i,e=>{const i=this.bufferToDataView(e);t(i)}))}writeCharacteristic(e,t,i,r){const n=this.dataViewToBuffer(t),s=this.characteristicHandles[e],a=s.properties.indexOf("writeWithoutResponse")>=0||s.properties.indexOf("authenticatedSignedWrites")>=0,c="darwin"!==this.os&&a?25:null;s.write(n,a,this.checkForError(r,i,c))}enableNotify(e,t,i,r){if(this.charNotifies[e])return this.charNotifies[e]=t,i();this.characteristicHandles[e].once("notify",n=>{if(!0!==n)return r("notify failed to enable");this.charNotifies[e]=t,i()}),this.characteristicHandles[e].notify(!0,this.checkForError(r))}disableNotify(e,t,i){if(!this.charNotifies[e])return t();this.characteristicHandles[e].once("notify",r=>{if(!1!==r)return i("notify failed to disable");this.charNotifies[e]&&delete this.charNotifies[e],t()}),this.characteristicHandles[e].notify(!1,this.checkForError(i))}readDescriptor(e,t,i){this.descriptorHandles[e].readValue(this.checkForError(i,e=>{const i=this.bufferToDataView(e);t(i)}))}writeDescriptor(e,t,i,r){const n=this.dataViewToBuffer(t);this.descriptorHandles[e].writeValue(n,this.checkForError(r,i))}}D.EVENT_ENABLED="enabledchanged";const P=new D;class S{constructor(e){this.characteristic=null,this.uuid=null,this._value=null,this.handle=null,this.characteristic=e.characteristic,this.uuid=e.uuid,this._value=e.value,this.handle=`${this.characteristic.uuid}-${this.uuid}`}get value(){return this._value}readValue(){return new Promise((e,t)=>{if(!this.characteristic.service.device.gatt.connected)return t("readValue error: device not connected");P.readDescriptor(this.handle,t=>{this._value=t,e(t)},e=>{t(`readValue error: ${e}`)})})}writeValue(e){return new Promise((t,i)=>{if(!this.characteristic.service.device.gatt.connected)return i("writeValue error: device not connected");const r=function(e){return void 0!==e.buffer}(e)?e.buffer:e,n=new DataView(r);P.writeDescriptor(this.handle,n,()=>{this._value=n,t()},e=>{i(`writeValue error: ${e}`)})})}}class k{constructor(e,t){this.bubbles=!0,this.cancelable=!1,this.cancelBubble=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=0,this.isTrusted=!0,this.returnValue=!0,this.target=e,this.srcElement=e,this.currentTarget=e,this.type=t}composedPath(){return[]}initEvent(e,t,i){this.type=e,this.bubbles=t,this.cancelable=i}preventDefault(){this.defaultPrevented=!0}stopImmediatePropagation(){}stopPropagation(){}}class O extends b{constructor(e){super(),this.service=null,this.uuid=null,this._value=null,this.handle=null,this.descriptors=null,this.service=e.service,this.uuid=e.uuid,this.properties=e.properties,this._value=e.value,this.handle=this.uuid}get value(){return this._value}set oncharacteristicvaluechanged(e){this._oncharacteristicvaluechanged&&this.removeEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged),this._oncharacteristicvaluechanged=e,this.addEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged)}setValue(e,t){this._value=e,t&&(this.dispatchEvent(new k(this,"characteristicvaluechanged")),this.service.dispatchEvent(new k(this,"characteristicvaluechanged")),this.service.device.dispatchEvent(new k(this,"characteristicvaluechanged")),this.service.device._bluetooth.dispatchEvent(new k(this,"characteristicvaluechanged")))}getDescriptor(e){return new Promise((t,i)=>this.service.device.gatt.connected?e?void this.getDescriptors(e).then(e=>{if(1!==e.length)return i("getDescriptor error: descriptor not found");t(e[0])}).catch(e=>{i(`getDescriptor error: ${e}`)}):i("getDescriptor error: no descriptor specified"):i("getDescriptor error: device not connected"))}getDescriptors(e){return new Promise((t,i)=>{if(!this.service.device.gatt.connected)return i("getDescriptors error: device not connected");function r(){if(!e)return t(this.descriptors);const r=this.descriptors.filter(t=>t.uuid===L(e));if(1!==r.length)return i("getDescriptors error: descriptor not found");t(r)}if(this.descriptors)return r.call(this);P.discoverDescriptors(this.handle,[],e=>{this.descriptors=e.map(e=>(Object.assign(e,{characteristic:this}),new S(e))),r.call(this)},e=>{i(`getDescriptors error: ${e}`)})})}readValue(){return new Promise((e,t)=>{if(!this.service.device.gatt.connected)return t("readValue error: device not connected");P.readCharacteristic(this.handle,t=>{this.setValue(t,!0),e(t)},e=>{t(`readValue error: ${e}`)})})}writeValue(e){return new Promise((t,i)=>{if(!this.service.device.gatt.connected)return i("writeValue error: device not connected");const r=function(e){return void 0!==e.buffer}(e)?e.buffer:e,n=new DataView(r);P.writeCharacteristic(this.handle,n,()=>{this.setValue(n),t()},e=>{i(`writeValue error: ${e}`)})})}startNotifications(){return new Promise((e,t)=>{if(!this.service.device.gatt.connected)return t("startNotifications error: device not connected");P.enableNotify(this.handle,e=>{this.setValue(e,!0)},()=>{e(this)},e=>{t(`startNotifications error: ${e}`)})})}stopNotifications(){return new Promise((e,t)=>{if(!this.service.device.gatt.connected)return t("stopNotifications error: device not connected");P.disableNotify(this.handle,()=>{e(this)},e=>{t(`stopNotifications error: ${e}`)})})}}class T extends b{constructor(e){super(),this.device=null,this.uuid=null,this.isPrimary=!1,this.handle=null,this.services=null,this.characteristics=null,this.device=e.device,this.uuid=e.uuid,this.isPrimary=e.isPrimary,this.handle=this.uuid,this.dispatchEvent(new k(this,"serviceadded")),this.device.dispatchEvent(new k(this,"serviceadded")),this.device._bluetooth.dispatchEvent(new k(this,"serviceadded"))}set oncharacteristicvaluechanged(e){this._oncharacteristicvaluechanged&&this.removeEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged),this._oncharacteristicvaluechanged=e,this.addEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged)}set onserviceadded(e){this._onserviceadded&&this.removeEventListener("serviceadded",this._onserviceadded),this._onserviceadded=e,this.addEventListener("serviceadded",this._onserviceadded)}set onservicechanged(e){this._onservicechanged&&this.removeEventListener("servicechanged",this._onservicechanged),this._onservicechanged=e,this.addEventListener("servicechanged",this._onservicechanged)}set onserviceremoved(e){this._onserviceremoved&&this.removeEventListener("serviceremoved",this._onserviceremoved),this._onserviceremoved=e,this.addEventListener("serviceremoved",this._onserviceremoved)}getCharacteristic(e){return new Promise((t,i)=>this.device.gatt.connected?e?void this.getCharacteristics(e).then(e=>{if(1!==e.length)return i("getCharacteristic error: characteristic not found");t(e[0])}).catch(e=>{i(`getCharacteristic error: ${e}`)}):i("getCharacteristic error: no characteristic specified"):i("getCharacteristic error: device not connected"))}getCharacteristics(e){return new Promise((t,i)=>{if(!this.device.gatt.connected)return i("getCharacteristics error: device not connected");function r(){if(!e)return t(this.characteristics);e=x(e);const r=this.characteristics.filter(t=>t.uuid===e);if(1!==r.length)return i("getCharacteristics error: characteristic not found");t(r)}if(this.characteristics)return r.call(this);P.discoverCharacteristics(this.handle,[],e=>{this.characteristics=e.map(e=>(Object.assign(e,{service:this}),new O(e))),r.call(this)},e=>{i(`getCharacteristics error: ${e}`)})})}getIncludedService(e){return new Promise((t,i)=>this.device.gatt.connected?e?void this.getIncludedServices(e).then(e=>{if(1!==e.length)return i("getIncludedService error: service not found");t(e[0])}).catch(e=>{i(`getIncludedService error: ${e}`)}):i("getIncludedService error: no service specified"):i("getIncludedService error: device not connected"))}getIncludedServices(e){return new Promise((t,i)=>{if(!this.device.gatt.connected)return i("getIncludedServices error: device not connected");function r(){if(!e)return t(this.services);const r=this.services.filter(t=>t.uuid===E(e));if(1!==r.length)return i("getIncludedServices error: service not found");t(r)}if(this.services)return r.call(this);P.discoverIncludedServices(this.handle,this.device._allowedServices,e=>{this.services=e.map(e=>(Object.assign(e,{device:this.device}),new T(e))),r.call(this)},e=>{i(`getIncludedServices error: ${e}`)})})}}class V{constructor(e){this.device=null,this._connected=!1,this.handle=null,this.services=null,this.device=e,this.handle=this.device.id}get connected(){return this._connected}connect(){return new Promise((e,t)=>{if(this.connected)return t("connect error: device already connected");P.connect(this.handle,()=>{this._connected=!0,e(this)},()=>{this.services=null,this._connected=!1,this.device.dispatchEvent(new k(this.device,"gattserverdisconnected")),this.device._bluetooth.dispatchEvent(new k(this.device,"gattserverdisconnected"))},e=>{t(`connect Error: ${e}`)})})}disconnect(){P.disconnect(this.handle),this._connected=!1}getPrimaryService(e){return new Promise((t,i)=>this.connected?e?void this.getPrimaryServices(e).then(e=>{if(1!==e.length)return i("getPrimaryService error: service not found");t(e[0])}).catch(e=>{i(`getPrimaryService error: ${e}`)}):i("getPrimaryService error: no service specified"):i("getPrimaryService error: device not connected"))}getPrimaryServices(e){return new Promise((t,i)=>{if(!this.connected)return i("getPrimaryServices error: device not connected");function r(){if(!e)return t(this.services);const r=this.services.filter(t=>t.uuid===E(e));if(1!==r.length)return i("getPrimaryServices error: service not found");t(r)}if(this.services)return r.call(this);P.discoverServices(this.handle,this.device._allowedServices,e=>{this.services=e.map(e=>(Object.assign(e,{device:this.device}),new T(e))),r.call(this)},e=>{i(`getPrimaryServices error: ${e}`)})})}}class C extends b{constructor(e){super(),this.id=null,this.name=null,this.gatt=null,this.watchingAdvertisements=!1,this._bluetooth=null,this._allowedServices=[],this._serviceUUIDs=[],this.id=e.id,this.name=e.name,this.gatt=e.gatt,this.watchAdvertisements=e.watchAdvertisements,this.adData=e.adData,this._bluetooth=e._bluetooth,this._allowedServices=e._allowedServices,this._serviceUUIDs=e._serviceUUIDs,this.name||(this.name=`Unknown or Unsupported Device (${this.id})`),this.gatt||(this.gatt=new V(this))}set oncharacteristicvaluechanged(e){this._oncharacteristicvaluechanged&&this.removeEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged),this._oncharacteristicvaluechanged=e,this.addEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged)}set onserviceadded(e){this._onserviceadded&&this.removeEventListener("serviceadded",this._onserviceadded),this._onserviceadded=e,this.addEventListener("serviceadded",this._onserviceadded)}set onservicechanged(e){this._onservicechanged&&this.removeEventListener("servicechanged",this._onservicechanged),this._onservicechanged=e,this.addEventListener("servicechanged",this._onservicechanged)}set onserviceremoved(e){this._onserviceremoved&&this.removeEventListener("serviceremoved",this._onserviceremoved),this._onserviceremoved=e,this.addEventListener("serviceremoved",this._onserviceremoved)}set ongattserverdisconnected(e){this._ongattserverdisconnected&&this.removeEventListener("gattserverdisconnected",this._ongattserverdisconnected),this._ongattserverdisconnected=e,this.addEventListener("gattserverdisconnected",this._ongattserverdisconnected)}set onadvertisementreceived(e){this._onadvertisementreceived&&this.removeEventListener("advertisementreceived",this._onadvertisementreceived),this._onadvertisementreceived=e,this.addEventListener("advertisementreceived",this._onadvertisementreceived)}watchAdvertisements(){return new Promise((e,t)=>{t("watchAdvertisements error: method not implemented")})}unwatchAdvertisements(){return new Promise((e,t)=>{t("unwatchAdvertisements error: method not implemented")})}}class H extends b{constructor(e){super(),this.deviceFound=null,this.scanTime=10240,this.scanner=null,e=e||{},this.referringDevice=e.referringDevice,this.deviceFound=e.deviceFound,e.scanTime&&(this.scanTime=1e3*e.scanTime),P.on(D.EVENT_ENABLED,e=>{this.dispatchEvent(new k(this,"availabilitychanged"))})}set oncharacteristicvaluechanged(e){this._oncharacteristicvaluechanged&&this.removeEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged),this._oncharacteristicvaluechanged=e,this.addEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged)}set onserviceadded(e){this._onserviceadded&&this.removeEventListener("serviceadded",this._onserviceadded),this._onserviceadded=e,this.addEventListener("serviceadded",this._onserviceadded)}set onservicechanged(e){this._onservicechanged&&this.removeEventListener("servicechanged",this._onservicechanged),this._onservicechanged=e,this.addEventListener("servicechanged",this._onservicechanged)}set onserviceremoved(e){this._onserviceremoved&&this.removeEventListener("serviceremoved",this._onserviceremoved),this._onserviceremoved=e,this.addEventListener("serviceremoved",this._onserviceremoved)}set ongattserverdisconnected(e){this._ongattserverdisconnected&&this.removeEventListener("gattserverdisconnected",this._ongattserverdisconnected),this._ongattserverdisconnected=e,this.addEventListener("gattserverdisconnected",this._ongattserverdisconnected)}set onadvertisementreceived(e){this._onadvertisementreceived&&this.removeEventListener("advertisementreceived",this._onadvertisementreceived),this._onadvertisementreceived=e,this.addEventListener("advertisementreceived",this._onadvertisementreceived)}set onavailabilitychanged(e){this._onavailabilitychanged&&this.removeEventListener("availabilitychanged",this._onavailabilitychanged),this._onavailabilitychanged=e,this.addEventListener("availabilitychanged",this._onavailabilitychanged)}filterDevice(e,t,i){let r=!1;return e.forEach(e=>{if(!e.name||e.name===t.name){if(e.namePrefix){if(!t.name||e.namePrefix.length>t.name.length)return;if(e.namePrefix!==t.name.substr(0,e.namePrefix.length))return}if(e.services){const r=e.services.map(E);if(!r.every(e=>t._serviceUUIDs.indexOf(e)>-1))return;i=i.concat(r)}r=!0}}),!!r&&t}getAvailability(){return new Promise((e,t)=>{P.getEnabled(t=>{e(t)})})}requestDevice(e={filters:[]}){return new Promise((t,i)=>{if(null!==this.scanner)return i("requestDevice error: request in progress");const r=e=>void 0!==e.filters;let n=[];if(r(e)){if(0===e.filters.length)return i(new TypeError("requestDevice error: no filters specified"));if(e.filters.some(e=>0===Object.keys(e).length))return i(new TypeError("requestDevice error: empty filter specified"));if(e.filters.some(e=>void 0!==e.namePrefix&&""===e.namePrefix))return i(new TypeError("requestDevice error: empty namePrefix specified"));e.filters.forEach(e=>{e.services&&(n=n.concat(e.services.map(E))),n=n.filter((e,t,i)=>i.indexOf(e)===t)})}else if(!(e=>!0===e.acceptAllDevices)(e))return i(new TypeError("requestDevice error: specify filters or acceptAllDevices"));let s=!1;P.startScan(n,i=>{let n=[];function a(e){this.cancelRequest().then(()=>{t(e)})}if(r(e)&&(i=this.filterDevice(e.filters,i,n)),i){s=!0,e.optionalServices&&(n=n.concat(e.optionalServices.map(E)));const t=n.filter((e,t,i)=>i.indexOf(e)===t);Object.assign(i,{_bluetooth:this,_allowedServices:t});const r=new C(i);function c(){a.call(this,r)}this.deviceFound&&!0!==this.deviceFound(r,c.bind(this))||a.call(this,r)}},()=>{this.scanner=setTimeout(()=>{this.cancelRequest().then(()=>{s||i("requestDevice error: no devices found")})},this.scanTime)},e=>i(`requestDevice error: ${e}`))})}cancelRequest(){return new Promise((e,t)=>{this.scanner&&(clearTimeout(this.scanner),this.scanner=null,P.stopScan()),e()})}}H.EVENT_AVAILABILITY="availabilitychanged";const N=new H;export{H as Bluetooth,N as bluetooth,a as bluetoothCharacteristics,c as bluetoothDescriptors,s as bluetoothServices,y as getCanonicalUUID,x as getCharacteristicUUID,L as getDescriptorUUID,E as getServiceUUID};
//# sourceMappingURL=webbluetooth.esm.js.map

@@ -1,2 +0,2 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@abandonware/noble")):"function"==typeof define&&define.amd?define(["exports","@abandonware/noble"],t):t((e=e||self).webbluetooth={},e.noble)}(this,(function(e,t){"use strict";var r,i,n;function s(){}function o(){o.init.call(this)}function a(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function c(e,t,r){if(t)e.call(r);else for(var i=e.length,n=m(e,i),s=0;s<i;++s)n[s].call(r)}function _(e,t,r,i){if(t)e.call(r,i);else for(var n=e.length,s=m(e,n),o=0;o<n;++o)s[o].call(r,i)}function d(e,t,r,i,n){if(t)e.call(r,i,n);else for(var s=e.length,o=m(e,s),a=0;a<s;++a)o[a].call(r,i,n)}function u(e,t,r,i,n,s){if(t)e.call(r,i,n,s);else for(var o=e.length,a=m(e,o),c=0;c<o;++c)a[c].call(r,i,n,s)}function l(e,t,r,i){if(t)e.apply(r,i);else for(var n=e.length,s=m(e,n),o=0;o<n;++o)s[o].apply(r,i)}function h(e,t,r,i){var n,o,c,_;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),c=o[t]):(o=e._events=new s,e._eventsCount=0),c){if("function"==typeof c?c=o[t]=i?[r,c]:[c,r]:i?c.unshift(r):c.push(r),!c.warned&&(n=a(e))&&n>0&&c.length>n){c.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=c.length,_=d,"function"==typeof console.warn?console.warn(_):console.log(_)}}else c=o[t]=r,++e._eventsCount;return e}function f(e,t,r){var i=!1;function n(){e.removeListener(t,n),i||(i=!0,r.apply(e,arguments))}return n.listener=r,n}function p(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function m(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}s.prototype=Object.create(null),o.EventEmitter=o,o.usingDomains=!1,o.prototype.domain=void 0,o.prototype._events=void 0,o.prototype._maxListeners=void 0,o.defaultMaxListeners=10,o.init=function(){this.domain=null,o.usingDomains&&(void 0).active&&(void 0).Domain,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new s,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return a(this)},o.prototype.emit=function(e){var t,r,i,n,s,o,a,h="error"===e;if(o=this._events)h=h&&null==o.error;else if(!h)return!1;if(a=this.domain,h){if(t=arguments[1],!a){if(t instanceof Error)throw t;var f=new Error('Uncaught, unspecified "error" event. ('+t+")");throw f.context=t,f}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var p="function"==typeof r;switch(i=arguments.length){case 1:c(r,p,this);break;case 2:_(r,p,this,arguments[1]);break;case 3:d(r,p,this,arguments[1],arguments[2]);break;case 4:u(r,p,this,arguments[1],arguments[2],arguments[3]);break;default:for(n=new Array(i-1),s=1;s<i;s++)n[s-1]=arguments[s];l(r,p,this,n)}return!0},o.prototype.addListener=function(e,t){return h(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return h(this,e,t,!0)},o.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,f(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,f(this,e,t)),this},o.prototype.removeListener=function(e,t){var r,i,n,o,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new s:(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(n=-1,o=r.length;o-- >0;)if(r[o]===t||r[o].listener&&r[o].listener===t){a=r[o].listener,n=o;break}if(n<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new s,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,n=e.length;i<n;r+=1,i+=1)e[r]=e[i];e.pop()}(r,n);i.removeListener&&this.emit("removeListener",e,a||t)}return this},o.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new s,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new s:delete r[e]),this;if(0===arguments.length){for(var i,n=Object.keys(r),o=0;o<n.length;++o)"removeListener"!==(i=n[o])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new s,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},o.prototype.listeners=function(e){var t,r=this._events;return r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[]},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},o.prototype.listenerCount=p,o.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class v extends o{addEventListener(e,t){return super.addListener(e,t)}removeEventListener(e,t){return super.removeListener(e,t)}dispatchEvent(e,t){return super.emit(e,{type:e,target:this,value:t})}}function g(e){return"number"==typeof e&&(e=e.toString(16)),(e=e.toLowerCase()).length<=8&&(e=("00000000"+e).slice(-8)+"-0000-1000-8000-00805f9b34fb"),32===e.length&&(e=e.match(/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/).splice(1).join("-")),e}function w(t){return"string"==typeof t&&e.bluetoothServices[t]&&(t=e.bluetoothServices[t]),g(t)}function b(t){return"string"==typeof t&&e.bluetoothCharacteristics[t]&&(t=e.bluetoothCharacteristics[t]),g(t)}function y(t){return"string"==typeof t&&e.bluetoothDescriptors[t]&&(t=e.bluetoothDescriptors[t]),g(t)}(r=e.bluetoothServices||(e.bluetoothServices={}))[r.alert_notification=6161]="alert_notification",r[r.automation_io=6165]="automation_io",r[r.battery_service=6159]="battery_service",r[r.blood_pressure=6160]="blood_pressure",r[r.body_composition=6171]="body_composition",r[r.bond_management=6174]="bond_management",r[r.continuous_glucose_monitoring=6175]="continuous_glucose_monitoring",r[r.current_time=6149]="current_time",r[r.cycling_power=6168]="cycling_power",r[r.cycling_speed_and_cadence=6166]="cycling_speed_and_cadence",r[r.device_information=6154]="device_information",r[r.environmental_sensing=6170]="environmental_sensing",r[r.generic_access=6144]="generic_access",r[r.generic_attribute=6145]="generic_attribute",r[r.glucose=6152]="glucose",r[r.health_thermometer=6153]="health_thermometer",r[r.heart_rate=6157]="heart_rate",r[r.human_interface_device=6162]="human_interface_device",r[r.immediate_alert=6146]="immediate_alert",r[r.indoor_positioning=6177]="indoor_positioning",r[r.internet_protocol_support=6176]="internet_protocol_support",r[r.link_loss=6147]="link_loss",r[r.location_and_navigation=6169]="location_and_navigation",r[r.next_dst_change=6151]="next_dst_change",r[r.phone_alert_status=6158]="phone_alert_status",r[r.pulse_oximeter=6178]="pulse_oximeter",r[r.reference_time_update=6150]="reference_time_update",r[r.running_speed_and_cadence=6164]="running_speed_and_cadence",r[r.scan_parameters=6163]="scan_parameters",r[r.tx_power=6148]="tx_power",r[r.user_data=6172]="user_data",r[r.weight_scale=6173]="weight_scale",(i=e.bluetoothCharacteristics||(e.bluetoothCharacteristics={}))[i.aerobic_heart_rate_lower_limit=10878]="aerobic_heart_rate_lower_limit",i[i.aerobic_heart_rate_upper_limit=10884]="aerobic_heart_rate_upper_limit",i[i.aerobic_threshold=10879]="aerobic_threshold",i[i.age=10880]="age",i[i.aggregate=10842]="aggregate",i[i.alert_category_id=10819]="alert_category_id",i[i.alert_category_id_bit_mask=10818]="alert_category_id_bit_mask",i[i.alert_level=10758]="alert_level",i[i.alert_notification_control_point=10820]="alert_notification_control_point",i[i.alert_status=10815]="alert_status",i[i.altitude=10931]="altitude",i[i.anaerobic_heart_rate_lower_limit=10881]="anaerobic_heart_rate_lower_limit",i[i.anaerobic_heart_rate_upper_limit=10882]="anaerobic_heart_rate_upper_limit",i[i.anaerobic_threshold=10883]="anaerobic_threshold",i[i.analog=10840]="analog",i[i.apparent_wind_direction=10867]="apparent_wind_direction",i[i.apparent_wind_speed=10866]="apparent_wind_speed",i[i["gap.appearance"]=10753]="gap.appearance",i[i.barometric_pressure_trend=10915]="barometric_pressure_trend",i[i.battery_level=10777]="battery_level",i[i.blood_pressure_feature=10825]="blood_pressure_feature",i[i.blood_pressure_measurement=10805]="blood_pressure_measurement",i[i.body_composition_feature=10907]="body_composition_feature",i[i.body_composition_measurement=10908]="body_composition_measurement",i[i.body_sensor_location=10808]="body_sensor_location",i[i.bond_management_control_point=10916]="bond_management_control_point",i[i.bond_management_feature=10917]="bond_management_feature",i[i.boot_keyboard_input_report=10786]="boot_keyboard_input_report",i[i.boot_keyboard_output_report=10802]="boot_keyboard_output_report",i[i.boot_mouse_input_report=10803]="boot_mouse_input_report",i[i["gap.central_address_resolution_support"]=10918]="gap.central_address_resolution_support",i[i.cgm_feature=10920]="cgm_feature",i[i.cgm_measurement=10919]="cgm_measurement",i[i.cgm_session_run_time=10923]="cgm_session_run_time",i[i.cgm_session_start_time=10922]="cgm_session_start_time",i[i.cgm_specific_ops_control_point=10924]="cgm_specific_ops_control_point",i[i.cgm_status=10921]="cgm_status",i[i.csc_feature=10844]="csc_feature",i[i.csc_measurement=10843]="csc_measurement",i[i.current_time=10795]="current_time",i[i.cycling_power_control_point=10854]="cycling_power_control_point",i[i.cycling_power_feature=10853]="cycling_power_feature",i[i.cycling_power_measurement=10851]="cycling_power_measurement",i[i.cycling_power_vector=10852]="cycling_power_vector",i[i.database_change_increment=10905]="database_change_increment",i[i.date_of_birth=10885]="date_of_birth",i[i.date_of_threshold_assessment=10886]="date_of_threshold_assessment",i[i.date_time=10760]="date_time",i[i.day_date_time=10762]="day_date_time",i[i.day_of_week=10761]="day_of_week",i[i.descriptor_value_changed=10877]="descriptor_value_changed",i[i["gap.device_name"]=10752]="gap.device_name",i[i.dew_point=10875]="dew_point",i[i.digital=10838]="digital",i[i.dst_offset=10765]="dst_offset",i[i.elevation=10860]="elevation",i[i.email_address=10887]="email_address",i[i.exact_time_256=10764]="exact_time_256",i[i.fat_burn_heart_rate_lower_limit=10888]="fat_burn_heart_rate_lower_limit",i[i.fat_burn_heart_rate_upper_limit=10889]="fat_burn_heart_rate_upper_limit",i[i.firmware_revision_string=10790]="firmware_revision_string",i[i.first_name=10890]="first_name",i[i.five_zone_heart_rate_limits=10891]="five_zone_heart_rate_limits",i[i.floor_number=10930]="floor_number",i[i.gender=10892]="gender",i[i.glucose_feature=10833]="glucose_feature",i[i.glucose_measurement=10776]="glucose_measurement",i[i.glucose_measurement_context=10804]="glucose_measurement_context",i[i.gust_factor=10868]="gust_factor",i[i.hardware_revision_string=10791]="hardware_revision_string",i[i.heart_rate_control_point=10809]="heart_rate_control_point",i[i.heart_rate_max=10893]="heart_rate_max",i[i.heart_rate_measurement=10807]="heart_rate_measurement",i[i.heat_index=10874]="heat_index",i[i.height=10894]="height",i[i.hid_control_point=10828]="hid_control_point",i[i.hid_information=10826]="hid_information",i[i.hip_circumference=10895]="hip_circumference",i[i.humidity=10863]="humidity",i[i["ieee_11073-20601_regulatory_certification_data_list"]=10794]="ieee_11073-20601_regulatory_certification_data_list",i[i.indoor_positioning_configuration=10925]="indoor_positioning_configuration",i[i.intermediate_blood_pressure=10806]="intermediate_blood_pressure",i[i.intermediate_temperature=10782]="intermediate_temperature",i[i.irradiance=10871]="irradiance",i[i.language=10914]="language",i[i.last_name=10896]="last_name",i[i.latitude=10926]="latitude",i[i.ln_control_point=10859]="ln_control_point",i[i.ln_feature=10858]="ln_feature",i[i["local_east_coordinate.xml"]=10929]="local_east_coordinate.xml",i[i.local_north_coordinate=10928]="local_north_coordinate",i[i.local_time_information=10767]="local_time_information",i[i.location_and_speed=10855]="location_and_speed",i[i.location_name=10933]="location_name",i[i.longitude=10927]="longitude",i[i.magnetic_declination=10796]="magnetic_declination",i[i.magnetic_flux_density_2D=10912]="magnetic_flux_density_2D",i[i.magnetic_flux_density_3D=10913]="magnetic_flux_density_3D",i[i.manufacturer_name_string=10793]="manufacturer_name_string",i[i.maximum_recommended_heart_rate=10897]="maximum_recommended_heart_rate",i[i.measurement_interval=10785]="measurement_interval",i[i.model_number_string=10788]="model_number_string",i[i.navigation=10856]="navigation",i[i.new_alert=10822]="new_alert",i[i["gap.peripheral_preferred_connection_parameters"]=10756]="gap.peripheral_preferred_connection_parameters",i[i["gap.peripheral_privacy_flag"]=10754]="gap.peripheral_privacy_flag",i[i.plx_continuous_measurement=10847]="plx_continuous_measurement",i[i.plx_features=10848]="plx_features",i[i.plx_spot_check_measurement=10846]="plx_spot_check_measurement",i[i.pnp_id=10832]="pnp_id",i[i.pollen_concentration=10869]="pollen_concentration",i[i.position_quality=10857]="position_quality",i[i.pressure=10861]="pressure",i[i.protocol_mode=10830]="protocol_mode",i[i.rainfall=10872]="rainfall",i[i["gap.reconnection_address"]=10755]="gap.reconnection_address",i[i.record_access_control_point=10834]="record_access_control_point",i[i.reference_time_information=10772]="reference_time_information",i[i.report=10829]="report",i[i.report_map=10827]="report_map",i[i.resting_heart_rate=10898]="resting_heart_rate",i[i.ringer_control_point=10816]="ringer_control_point",i[i.ringer_setting=10817]="ringer_setting",i[i.rsc_feature=10836]="rsc_feature",i[i.rsc_measurement=10835]="rsc_measurement",i[i.sc_control_point=10837]="sc_control_point",i[i.scan_interval_window=10831]="scan_interval_window",i[i.scan_refresh=10801]="scan_refresh",i[i.sensor_location=10845]="sensor_location",i[i.serial_number_string=10789]="serial_number_string",i[i["gatt.service_changed"]=10757]="gatt.service_changed",i[i.software_revision_string=10792]="software_revision_string",i[i.sport_type_for_aerobic_and_anaerobic_thresholds=10899]="sport_type_for_aerobic_and_anaerobic_thresholds",i[i.supported_new_alert_category=10823]="supported_new_alert_category",i[i.supported_unread_alert_category=10824]="supported_unread_alert_category",i[i.system_id=10787]="system_id",i[i.temperature=10862]="temperature",i[i.temperature_measurement=10780]="temperature_measurement",i[i.temperature_type=10781]="temperature_type",i[i.three_zone_heart_rate_limits=10900]="three_zone_heart_rate_limits",i[i.time_accuracy=10770]="time_accuracy",i[i.time_source=10771]="time_source",i[i.time_update_control_point=10774]="time_update_control_point",i[i.time_update_state=10775]="time_update_state",i[i.time_with_dst=10769]="time_with_dst",i[i.time_zone=10766]="time_zone",i[i.true_wind_direction=10865]="true_wind_direction",i[i.true_wind_speed=10864]="true_wind_speed",i[i.two_zone_heart_rate_limit=10901]="two_zone_heart_rate_limit",i[i.tx_power_level=10759]="tx_power_level",i[i.uncertainty=10932]="uncertainty",i[i.unread_alert_status=10821]="unread_alert_status",i[i.user_control_point=10911]="user_control_point",i[i.user_index=10906]="user_index",i[i.uv_index=10870]="uv_index",i[i.vo2_max=10902]="vo2_max",i[i.waist_circumference=10903]="waist_circumference",i[i.weight=10904]="weight",i[i.weight_measurement=10909]="weight_measurement",i[i.weight_scale_feature=10910]="weight_scale_feature",i[i.wind_chill=10873]="wind_chill",(n=e.bluetoothDescriptors||(e.bluetoothDescriptors={}))[n["gatt.characteristic_extended_properties"]=10496]="gatt.characteristic_extended_properties",n[n["gatt.characteristic_user_description"]=10497]="gatt.characteristic_user_description",n[n["gatt.client_characteristic_configuration"]=10498]="gatt.client_characteristic_configuration",n[n["gatt.server_characteristic_configuration"]=10499]="gatt.server_characteristic_configuration",n[n["gatt.characteristic_presentation_format"]=10500]="gatt.characteristic_presentation_format",n[n["gatt.characteristic_aggregate_format"]=10501]="gatt.characteristic_aggregate_format",n[n.valid_range=10502]="valid_range",n[n.external_report_reference=10503]="external_report_reference",n[n.report_reference=10504]="report_reference",n[n.number_of_digitals=10505]="number_of_digitals",n[n.value_trigger_setting=10506]="value_trigger_setting",n[n.es_configuration=10507]="es_configuration",n[n.es_measurement=10508]="es_measurement",n[n.es_trigger_setting=10509]="es_trigger_setting",n[n.time_trigger_setting=10510]="time_trigger_setting";class E extends o{constructor(){super(),this.deviceHandles={},this.serviceHandles={},this.characteristicHandles={},this.descriptorHandles={},this.charNotifies={},this.discoverFn=null,this.initialised=!1,this.enabled=!1,this.os="browser",this.enabled=this.state,t.on("stateChange",()=>{this.enabled!==this.state&&(this.enabled=this.state,this.emit(E.EVENT_ENABLED,this.enabled))})}get state(){return"poweredOn"===t.state}init(e){if(this.initialised)return e();t.on("discover",e=>{this.discoverFn&&this.discoverFn(e)}),this.initialised=!0,e()}checkForError(e,t,r){return function(i){if(i)e(i);else if("function"==typeof t){const e=[].slice.call(arguments,1);null===r?t.apply(this,e):setTimeout(()=>t.apply(this,e),r)}}}bufferToDataView(e){const t=new Uint8Array(e).buffer;return new DataView(t)}dataViewToBuffer(e){const t=new Uint8Array(e.buffer);return new Buffer(t)}validDevice(e,t){if(0===t.length)return!0;if(!e.advertisement.serviceUuids)return!1;const r=e.advertisement.serviceUuids.map(e=>g(e));return t.some(e=>r.indexOf(e)>=0)}deviceToBluetoothDevice(e){const t=e.address&&"unknown"!==e.address?e.address:e.id,r=[];e.advertisement.serviceUuids&&e.advertisement.serviceUuids.forEach(e=>{r.push(g(e))});const i=new Map;if(e.advertisement.manufacturerData){const t=e.advertisement.manufacturerData.readUInt16LE(0),r=e.advertisement.manufacturerData.slice(2);i.set(("0000"+t.toString(16)).slice(-4),this.bufferToDataView(r))}const n=new Map;return e.advertisement.serviceData&&e.advertisement.serviceData.forEach(e=>{n.set(g(e.uuid),this.bufferToDataView(e.data))}),{id:t,name:e.advertisement.localName,_serviceUUIDs:r,adData:{rssi:e.rssi,txPower:e.advertisement.txPowerLevel,serviceData:n,manufacturerData:i}}}getEnabled(e){function r(){e(this.state)}"unknown"===t.state||"poweredOff"===t.state?t.once("stateChange",r.bind(this)):r.call(this)}startScan(e,r,i,n){this.discoverFn=t=>{if(this.validDevice(t,e)){const e=this.deviceToBluetoothDevice(t);this.deviceHandles[e.id]||(this.deviceHandles[e.id]=t,r(e))}},this.init(()=>{function e(){!0===this.state?t.startScanning([],!0,this.checkForError(n,i)):n("adapter not enabled")}this.deviceHandles={},"unknown"===t.state||"poweredOff"===t.state?t.once("stateChange",e.bind(this)):e.call(this)})}stopScan(e){this.discoverFn=null,t.stopScanning()}connect(e,t,r,i){const n=this.deviceHandles[e];n.removeAllListeners("connect"),n.removeAllListeners("disconnect"),n.once("connect",t),n.once("disconnect",()=>{this.serviceHandles={},this.characteristicHandles={},this.descriptorHandles={},this.charNotifies={},r()}),n.connect(this.checkForError(i))}disconnect(e,t){this.deviceHandles[e].disconnect(this.checkForError(t))}discoverServices(e,t,r,i){this.deviceHandles[e].discoverServices([],this.checkForError(i,e=>{const i=[];e.forEach(e=>{const r=g(e.uuid);(0===t.length||t.indexOf(r)>=0)&&(this.serviceHandles[r]||(this.serviceHandles[r]=e),i.push({uuid:r,primary:!0}))}),r(i)}))}discoverIncludedServices(e,t,r,i){this.serviceHandles[e].discoverIncludedServices([],this.checkForError(i,e=>{const i=[];e.forEach(e=>{const r=g(e.uuid);(0===t.length||t.indexOf(r)>=0)&&(this.serviceHandles[r]||(this.serviceHandles[r]=e),i.push({uuid:r,primary:!1}))},this),r(i)}))}discoverCharacteristics(e,t,r,i){this.serviceHandles[e].discoverCharacteristics([],this.checkForError(i,e=>{const i=[];e.forEach(e=>{const r=g(e.uuid);(0===t.length||t.indexOf(r)>=0)&&(this.characteristicHandles[r]||(this.characteristicHandles[r]=e),i.push({uuid:r,properties:{broadcast:e.properties.indexOf("broadcast")>=0,read:e.properties.indexOf("read")>=0,writeWithoutResponse:e.properties.indexOf("writeWithoutResponse")>=0,write:e.properties.indexOf("write")>=0,notify:e.properties.indexOf("notify")>=0,indicate:e.properties.indexOf("indicate")>=0,authenticatedSignedWrites:e.properties.indexOf("authenticatedSignedWrites")>=0,reliableWrite:e.properties.indexOf("reliableWrite")>=0,writableAuxiliaries:e.properties.indexOf("writableAuxiliaries")>=0}}),e.on("data",(e,t)=>{if(!0===t&&"function"==typeof this.charNotifies[r]){const t=this.bufferToDataView(e);this.charNotifies[r](t)}}))},this),r(i)}))}discoverDescriptors(e,t,r,i){const n=this.characteristicHandles[e];n.discoverDescriptors(this.checkForError(i,e=>{const i=[];e.forEach(e=>{const r=g(e.uuid);if(0===t.length||t.indexOf(r)>=0){const t=n.uuid+"-"+e.uuid;this.descriptorHandles[t]||(this.descriptorHandles[t]=e),i.push({uuid:r})}},this),r(i)}))}readCharacteristic(e,t,r){this.characteristicHandles[e].read(this.checkForError(r,e=>{const r=this.bufferToDataView(e);t(r)}))}writeCharacteristic(e,t,r,i){const n=this.dataViewToBuffer(t),s=this.characteristicHandles[e],o=s.properties.indexOf("writeWithoutResponse")>=0||s.properties.indexOf("authenticatedSignedWrites")>=0,a="darwin"!==this.os&&o?25:null;s.write(n,o,this.checkForError(i,r,a))}enableNotify(e,t,r,i){if(this.charNotifies[e])return this.charNotifies[e]=t,r();this.characteristicHandles[e].once("notify",n=>{if(!0!==n)return i("notify failed to enable");this.charNotifies[e]=t,r()}),this.characteristicHandles[e].notify(!0,this.checkForError(i))}disableNotify(e,t,r){if(!this.charNotifies[e])return t();this.characteristicHandles[e].once("notify",i=>{if(!1!==i)return r("notify failed to disable");this.charNotifies[e]&&delete this.charNotifies[e],t()}),this.characteristicHandles[e].notify(!1,this.checkForError(r))}readDescriptor(e,t,r){this.descriptorHandles[e].readValue(this.checkForError(r,e=>{const r=this.bufferToDataView(e);t(r)}))}writeDescriptor(e,t,r,i){const n=this.dataViewToBuffer(t);this.descriptorHandles[e].writeValue(n,this.checkForError(i,r))}}E.EVENT_ENABLED="enabledchanged";const D=new E;class x{constructor(e){this.characteristic=null,this.uuid=null,this._value=null,this.handle=null,this.characteristic=e.characteristic,this.uuid=e.uuid,this._value=e.value,this.handle=`${this.characteristic.uuid}-${this.uuid}`}get value(){return this._value}readValue(){return new Promise((e,t)=>{if(!this.characteristic.service.device.gatt.connected)return t("readValue error: device not connected");D.readDescriptor(this.handle,t=>{this._value=t,e(t)},e=>{t(`readValue error: ${e}`)})})}writeValue(e){return new Promise((t,r)=>{if(!this.characteristic.service.device.gatt.connected)return r("writeValue error: device not connected");const i=function(e){return void 0!==e.buffer}(e)?e.buffer:e,n=new DataView(i);D.writeDescriptor(this.handle,n,()=>{this._value=n,t()},e=>{r(`writeValue error: ${e}`)})})}}class T extends v{constructor(e){super(),this.service=null,this.uuid=null,this._value=null,this.handle=null,this.descriptors=null,this.service=e.service,this.uuid=e.uuid,this.properties=e.properties,this._value=e.value,this.handle=this.uuid}get value(){return this._value}setValue(e,t){this._value=e,t&&(this.dispatchEvent(T.EVENT_CHANGED,e),this.service.dispatchEvent(T.EVENT_CHANGED,e),this.service.device.dispatchEvent(T.EVENT_CHANGED,e),this.service.device._bluetooth.dispatchEvent(T.EVENT_CHANGED,e))}getDescriptor(e){return new Promise((t,r)=>this.service.device.gatt.connected?e?void this.getDescriptors(e).then(e=>{if(1!==e.length)return r("getDescriptor error: descriptor not found");t(e[0])}).catch(e=>{r(`getDescriptor error: ${e}`)}):r("getDescriptor error: no descriptor specified"):r("getDescriptor error: device not connected"))}getDescriptors(e){return new Promise((t,r)=>{if(!this.service.device.gatt.connected)return r("getDescriptors error: device not connected");function i(){if(!e)return t(this.descriptors);const i=this.descriptors.filter(t=>t.uuid===y(e));if(1!==i.length)return r("getDescriptors error: descriptor not found");t(i)}if(this.descriptors)return i.call(this);D.discoverDescriptors(this.handle,[],e=>{this.descriptors=e.map(e=>(Object.assign(e,{characteristic:this}),new x(e))),i.call(this)},e=>{r(`getDescriptors error: ${e}`)})})}readValue(){return new Promise((e,t)=>{if(!this.service.device.gatt.connected)return t("readValue error: device not connected");D.readCharacteristic(this.handle,t=>{this.setValue(t,!0),e(t)},e=>{t(`readValue error: ${e}`)})})}writeValue(e){return new Promise((t,r)=>{if(!this.service.device.gatt.connected)return r("writeValue error: device not connected");const i=function(e){return void 0!==e.buffer}(e)?e.buffer:e,n=new DataView(i);D.writeCharacteristic(this.handle,n,()=>{this.setValue(n),t()},e=>{r(`writeValue error: ${e}`)})})}startNotifications(){return new Promise((e,t)=>{if(!this.service.device.gatt.connected)return t("startNotifications error: device not connected");D.enableNotify(this.handle,e=>{this.setValue(e,!0)},()=>{e(this)},e=>{t(`startNotifications error: ${e}`)})})}stopNotifications(){return new Promise((e,t)=>{if(!this.service.device.gatt.connected)return t("stopNotifications error: device not connected");D.disableNotify(this.handle,()=>{e(this)},e=>{t(`stopNotifications error: ${e}`)})})}}T.EVENT_CHANGED="characteristicvaluechanged";class N extends v{constructor(e){super(),this.device=null,this.uuid=null,this.isPrimary=!1,this.handle=null,this.services=null,this.characteristics=null,this.device=e.device,this.uuid=e.uuid,this.isPrimary=e.isPrimary,this.handle=this.uuid,this.dispatchEvent(N.EVENT_ADDED),this.device.dispatchEvent(N.EVENT_ADDED),this.device._bluetooth.dispatchEvent(N.EVENT_ADDED)}getCharacteristic(e){return new Promise((t,r)=>this.device.gatt.connected?e?void this.getCharacteristics(e).then(e=>{if(1!==e.length)return r("getCharacteristic error: characteristic not found");t(e[0])}).catch(e=>{r(`getCharacteristic error: ${e}`)}):r("getCharacteristic error: no characteristic specified"):r("getCharacteristic error: device not connected"))}getCharacteristics(e){return new Promise((t,r)=>{if(!this.device.gatt.connected)return r("getCharacteristics error: device not connected");function i(){if(!e)return t(this.characteristics);e=b(e);const i=this.characteristics.filter(t=>t.uuid===e);if(1!==i.length)return r("getCharacteristics error: characteristic not found");t(i)}if(this.characteristics)return i.call(this);D.discoverCharacteristics(this.handle,[],e=>{this.characteristics=e.map(e=>(Object.assign(e,{service:this}),new T(e))),i.call(this)},e=>{r(`getCharacteristics error: ${e}`)})})}getIncludedService(e){return new Promise((t,r)=>this.device.gatt.connected?e?void this.getIncludedServices(e).then(e=>{if(1!==e.length)return r("getIncludedService error: service not found");t(e[0])}).catch(e=>{r(`getIncludedService error: ${e}`)}):r("getIncludedService error: no service specified"):r("getIncludedService error: device not connected"))}getIncludedServices(e){return new Promise((t,r)=>{if(!this.device.gatt.connected)return r("getIncludedServices error: device not connected");function i(){if(!e)return t(this.services);const i=this.services.filter(t=>t.uuid===w(e));if(1!==i.length)return r("getIncludedServices error: service not found");t(i)}if(this.services)return i.call(this);D.discoverIncludedServices(this.handle,this.device._allowedServices,e=>{this.services=e.map(e=>(Object.assign(e,{device:this.device}),new N(e))),i.call(this)},e=>{r(`getIncludedServices error: ${e}`)})})}}N.EVENT_ADDED="serviceadded",N.EVENT_CHANGED="servicechanged",N.EVENT_REMOVED="serviceremoved";class S{constructor(e){this.device=null,this._connected=!1,this.handle=null,this.services=null,this.device=e,this.handle=this.device.id}get connected(){return this._connected}connect(){return new Promise((e,t)=>{if(this.connected)return t("connect error: device already connected");D.connect(this.handle,()=>{this._connected=!0,e(this)},()=>{this.services=null,this._connected=!1,this.device.dispatchEvent(V.EVENT_DISCONNECTED),this.device._bluetooth.dispatchEvent(V.EVENT_DISCONNECTED)},e=>{t(`connect Error: ${e}`)})})}disconnect(){D.disconnect(this.handle),this._connected=!1}getPrimaryService(e){return new Promise((t,r)=>this.connected?e?void this.getPrimaryServices(e).then(e=>{if(1!==e.length)return r("getPrimaryService error: service not found");t(e[0])}).catch(e=>{r(`getPrimaryService error: ${e}`)}):r("getPrimaryService error: no service specified"):r("getPrimaryService error: device not connected"))}getPrimaryServices(e){return new Promise((t,r)=>{if(!this.connected)return r("getPrimaryServices error: device not connected");function i(){if(!e)return t(this.services);const i=this.services.filter(t=>t.uuid===w(e));if(1!==i.length)return r("getPrimaryServices error: service not found");t(i)}if(this.services)return i.call(this);D.discoverServices(this.handle,this.device._allowedServices,e=>{this.services=e.map(e=>(Object.assign(e,{device:this.device}),new N(e))),i.call(this)},e=>{r(`getPrimaryServices error: ${e}`)})})}}class V extends v{constructor(e){super(),this.id=null,this.name=null,this.gatt=null,this.watchingAdvertisements=!1,this._bluetooth=null,this._allowedServices=[],this._serviceUUIDs=[],this.id=e.id,this.name=e.name,this.gatt=e.gatt,this.watchAdvertisements=e.watchAdvertisements,this.adData=e.adData,this._bluetooth=e._bluetooth,this._allowedServices=e._allowedServices,this._serviceUUIDs=e._serviceUUIDs,this.name||(this.name=`Unknown or Unsupported Device (${this.id})`),this.gatt||(this.gatt=new S(this))}watchAdvertisements(){return new Promise((e,t)=>{t("watchAdvertisements error: method not implemented")})}unwatchAdvertisements(){return new Promise((e,t)=>{t("unwatchAdvertisements error: method not implemented")})}}V.EVENT_DISCONNECTED="gattserverdisconnected",V.EVENT_ADVERT="advertisementreceived";class C extends v{constructor(e){super(),this.deviceFound=null,this.scanTime=10240,this.scanner=null,e=e||{},this.referringDevice=e.referringDevice,this.deviceFound=e.deviceFound,e.scanTime&&(this.scanTime=1e3*e.scanTime),D.on(E.EVENT_ENABLED,e=>{this.dispatchEvent(C.EVENT_AVAILABILITY,e)})}filterDevice(e,t,r){let i=!1;return e.filters.forEach(e=>{if(!e.name||e.name===t.name){if(e.namePrefix){if(!t.name||e.namePrefix.length>t.name.length)return;if(e.namePrefix!==t.name.substr(0,e.namePrefix.length))return}if(e.services){const i=e.services.map(w);if(!i.every(e=>t._serviceUUIDs.indexOf(e)>-1))return;r=r.concat(i)}i=!0}}),!!i&&t}getAvailability(){return new Promise((e,t)=>{D.getEnabled(t=>{e(t)})})}requestDevice(e){return new Promise((t,r)=>{if(e=e||{},null!==this.scanner)return r("requestDevice error: request in progress");if(!e.acceptAllDevices&&!this.deviceFound){if(!e.filters||0===e.filters.length)return r(new TypeError("requestDevice error: no filters specified"));if(e.filters.some(e=>0===Object.keys(e).length))return r(new TypeError("requestDevice error: empty filter specified"));if(e.filters.some(e=>void 0!==e.namePrefix&&""===e.namePrefix))return r(new TypeError("requestDevice error: empty namePrefix specified"))}let i=[];e.filters&&e.filters.forEach(e=>{e.services&&(i=i.concat(e.services.map(w)))}),i=i.filter((e,t,r)=>r.indexOf(e)===t);let n=!1;D.startScan(i,r=>{let i=[];function s(e){this.cancelRequest().then(()=>{t(e)})}if(e.filters&&(r=this.filterDevice(e,r,i)),r){n=!0,e.optionalServices&&(i=i.concat(e.optionalServices.map(w)));const t=i.filter((e,t,r)=>r.indexOf(e)===t);Object.assign(r,{_bluetooth:this,_allowedServices:t});const a=new V(r);function o(){s.call(this,a)}this.deviceFound&&!0!==this.deviceFound(a,o.bind(this))||s.call(this,a)}},()=>{this.scanner=setTimeout(()=>{this.cancelRequest().then(()=>{n||r("requestDevice error: no devices found")})},this.scanTime)},e=>r(`requestDevice error: ${e}`))})}cancelRequest(){return new Promise((e,t)=>{this.scanner&&(clearTimeout(this.scanner),this.scanner=null,D.stopScan()),e()})}}C.EVENT_AVAILABILITY="availabilitychanged";const L=new C;e.Bluetooth=C,e.BluetoothDevice=V,e.BluetoothRemoteGATTCharacteristic=T,e.BluetoothRemoteGATTDescriptor=x,e.BluetoothRemoteGATTServer=S,e.BluetoothRemoteGATTService=N,e.bluetooth=L,e.getCanonicalUUID=g,e.getCharacteristicUUID=b,e.getDescriptorUUID=y,e.getServiceUUID=w,Object.defineProperty(e,"__esModule",{value:!0})}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@abandonware/noble")):"function"==typeof define&&define.amd?define(["exports","@abandonware/noble"],t):t((e=e||self).webbluetooth={},e.noble)}(this,(function(e,t){"use strict";var i,r,n;function s(){}function a(){a.init.call(this)}function c(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function o(e,t,i){if(t)e.call(i);else for(var r=e.length,n=p(e,r),s=0;s<r;++s)n[s].call(i)}function d(e,t,i,r){if(t)e.call(i,r);else for(var n=e.length,s=p(e,n),a=0;a<n;++a)s[a].call(i,r)}function h(e,t,i,r,n){if(t)e.call(i,r,n);else for(var s=e.length,a=p(e,s),c=0;c<s;++c)a[c].call(i,r,n)}function _(e,t,i,r,n,s){if(t)e.call(i,r,n,s);else for(var a=e.length,c=p(e,a),o=0;o<a;++o)c[o].call(i,r,n,s)}function l(e,t,i,r){if(t)e.apply(i,r);else for(var n=e.length,s=p(e,n),a=0;a<n;++a)s[a].apply(i,r)}function u(e,t,i,r){var n,a,o,d;if("function"!=typeof i)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),a=e._events),o=a[t]):(a=e._events=new s,e._eventsCount=0),o){if("function"==typeof o?o=a[t]=r?[i,o]:[o,i]:r?o.unshift(i):o.push(i),!o.warned&&(n=c(e))&&n>0&&o.length>n){o.warned=!0;var h=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");h.name="MaxListenersExceededWarning",h.emitter=e,h.type=t,h.count=o.length,d=h,"function"==typeof console.warn?console.warn(d):console.log(d)}}else o=a[t]=i,++e._eventsCount;return e}function v(e,t,i){var r=!1;function n(){e.removeListener(t,n),r||(r=!0,i.apply(e,arguments))}return n.listener=i,n}function m(e){var t=this._events;if(t){var i=t[e];if("function"==typeof i)return 1;if(i)return i.length}return 0}function p(e,t){for(var i=new Array(t);t--;)i[t]=e[t];return i}s.prototype=Object.create(null),a.EventEmitter=a,a.usingDomains=!1,a.prototype.domain=void 0,a.prototype._events=void 0,a.prototype._maxListeners=void 0,a.defaultMaxListeners=10,a.init=function(){this.domain=null,a.usingDomains&&(void 0).active&&(void 0).Domain,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new s,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},a.prototype.getMaxListeners=function(){return c(this)},a.prototype.emit=function(e){var t,i,r,n,s,a,c,u="error"===e;if(a=this._events)u=u&&null==a.error;else if(!u)return!1;if(c=this.domain,u){if(t=arguments[1],!c){if(t instanceof Error)throw t;var v=new Error('Uncaught, unspecified "error" event. ('+t+")");throw v.context=t,v}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=c,t.domainThrown=!1,c.emit("error",t),!1}if(!(i=a[e]))return!1;var m="function"==typeof i;switch(r=arguments.length){case 1:o(i,m,this);break;case 2:d(i,m,this,arguments[1]);break;case 3:h(i,m,this,arguments[1],arguments[2]);break;case 4:_(i,m,this,arguments[1],arguments[2],arguments[3]);break;default:for(n=new Array(r-1),s=1;s<r;s++)n[s-1]=arguments[s];l(i,m,this,n)}return!0},a.prototype.addListener=function(e,t){return u(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return u(this,e,t,!0)},a.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,v(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,v(this,e,t)),this},a.prototype.removeListener=function(e,t){var i,r,n,a,c;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(r=this._events))return this;if(!(i=r[e]))return this;if(i===t||i.listener&&i.listener===t)0==--this._eventsCount?this._events=new s:(delete r[e],r.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(n=-1,a=i.length;a-- >0;)if(i[a]===t||i[a].listener&&i[a].listener===t){c=i[a].listener,n=a;break}if(n<0)return this;if(1===i.length){if(i[0]=void 0,0==--this._eventsCount)return this._events=new s,this;delete r[e]}else!function(e,t){for(var i=t,r=i+1,n=e.length;r<n;i+=1,r+=1)e[i]=e[r];e.pop()}(i,n);r.removeListener&&this.emit("removeListener",e,c||t)}return this},a.prototype.removeAllListeners=function(e){var t,i;if(!(i=this._events))return this;if(!i.removeListener)return 0===arguments.length?(this._events=new s,this._eventsCount=0):i[e]&&(0==--this._eventsCount?this._events=new s:delete i[e]),this;if(0===arguments.length){for(var r,n=Object.keys(i),a=0;a<n.length;++a)"removeListener"!==(r=n[a])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=new s,this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},a.prototype.listeners=function(e){var t,i=this._events;return i&&(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(t):[]},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):m.call(e,t)},a.prototype.listenerCount=m,a.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class f extends a{constructor(){super(...arguments),this.isEventListenerObject=e=>void 0!==e.handleEvent}addEventListener(e,t){if(t){const i=this.isEventListenerObject(t)?t.handleEvent:t;super.addListener(e,i)}}removeEventListener(e,t){if(t){const i=this.isEventListenerObject(t)?t.handleEvent:t;super.removeListener(e,i)}}dispatchEvent(e){return super.emit(e.type,e)}}function g(e){return"number"==typeof e&&(e=e.toString(16)),(e=e.toLowerCase()).length<=8&&(e=("00000000"+e).slice(-8)+"-0000-1000-8000-00805f9b34fb"),32===e.length&&(e=e.match(/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/).splice(1).join("-")),e}function w(t){return"string"==typeof t&&e.bluetoothServices[t]&&(t=e.bluetoothServices[t]),g(t)}function b(t){return"string"==typeof t&&e.bluetoothCharacteristics[t]&&(t=e.bluetoothCharacteristics[t]),g(t)}function y(t){return"string"==typeof t&&e.bluetoothDescriptors[t]&&(t=e.bluetoothDescriptors[t]),g(t)}(i=e.bluetoothServices||(e.bluetoothServices={}))[i.alert_notification=6161]="alert_notification",i[i.automation_io=6165]="automation_io",i[i.battery_service=6159]="battery_service",i[i.blood_pressure=6160]="blood_pressure",i[i.body_composition=6171]="body_composition",i[i.bond_management=6174]="bond_management",i[i.continuous_glucose_monitoring=6175]="continuous_glucose_monitoring",i[i.current_time=6149]="current_time",i[i.cycling_power=6168]="cycling_power",i[i.cycling_speed_and_cadence=6166]="cycling_speed_and_cadence",i[i.device_information=6154]="device_information",i[i.environmental_sensing=6170]="environmental_sensing",i[i.generic_access=6144]="generic_access",i[i.generic_attribute=6145]="generic_attribute",i[i.glucose=6152]="glucose",i[i.health_thermometer=6153]="health_thermometer",i[i.heart_rate=6157]="heart_rate",i[i.human_interface_device=6162]="human_interface_device",i[i.immediate_alert=6146]="immediate_alert",i[i.indoor_positioning=6177]="indoor_positioning",i[i.internet_protocol_support=6176]="internet_protocol_support",i[i.link_loss=6147]="link_loss",i[i.location_and_navigation=6169]="location_and_navigation",i[i.next_dst_change=6151]="next_dst_change",i[i.phone_alert_status=6158]="phone_alert_status",i[i.pulse_oximeter=6178]="pulse_oximeter",i[i.reference_time_update=6150]="reference_time_update",i[i.running_speed_and_cadence=6164]="running_speed_and_cadence",i[i.scan_parameters=6163]="scan_parameters",i[i.tx_power=6148]="tx_power",i[i.user_data=6172]="user_data",i[i.weight_scale=6173]="weight_scale",(r=e.bluetoothCharacteristics||(e.bluetoothCharacteristics={}))[r.aerobic_heart_rate_lower_limit=10878]="aerobic_heart_rate_lower_limit",r[r.aerobic_heart_rate_upper_limit=10884]="aerobic_heart_rate_upper_limit",r[r.aerobic_threshold=10879]="aerobic_threshold",r[r.age=10880]="age",r[r.aggregate=10842]="aggregate",r[r.alert_category_id=10819]="alert_category_id",r[r.alert_category_id_bit_mask=10818]="alert_category_id_bit_mask",r[r.alert_level=10758]="alert_level",r[r.alert_notification_control_point=10820]="alert_notification_control_point",r[r.alert_status=10815]="alert_status",r[r.altitude=10931]="altitude",r[r.anaerobic_heart_rate_lower_limit=10881]="anaerobic_heart_rate_lower_limit",r[r.anaerobic_heart_rate_upper_limit=10882]="anaerobic_heart_rate_upper_limit",r[r.anaerobic_threshold=10883]="anaerobic_threshold",r[r.analog=10840]="analog",r[r.apparent_wind_direction=10867]="apparent_wind_direction",r[r.apparent_wind_speed=10866]="apparent_wind_speed",r[r["gap.appearance"]=10753]="gap.appearance",r[r.barometric_pressure_trend=10915]="barometric_pressure_trend",r[r.battery_level=10777]="battery_level",r[r.blood_pressure_feature=10825]="blood_pressure_feature",r[r.blood_pressure_measurement=10805]="blood_pressure_measurement",r[r.body_composition_feature=10907]="body_composition_feature",r[r.body_composition_measurement=10908]="body_composition_measurement",r[r.body_sensor_location=10808]="body_sensor_location",r[r.bond_management_control_point=10916]="bond_management_control_point",r[r.bond_management_feature=10917]="bond_management_feature",r[r.boot_keyboard_input_report=10786]="boot_keyboard_input_report",r[r.boot_keyboard_output_report=10802]="boot_keyboard_output_report",r[r.boot_mouse_input_report=10803]="boot_mouse_input_report",r[r["gap.central_address_resolution_support"]=10918]="gap.central_address_resolution_support",r[r.cgm_feature=10920]="cgm_feature",r[r.cgm_measurement=10919]="cgm_measurement",r[r.cgm_session_run_time=10923]="cgm_session_run_time",r[r.cgm_session_start_time=10922]="cgm_session_start_time",r[r.cgm_specific_ops_control_point=10924]="cgm_specific_ops_control_point",r[r.cgm_status=10921]="cgm_status",r[r.csc_feature=10844]="csc_feature",r[r.csc_measurement=10843]="csc_measurement",r[r.current_time=10795]="current_time",r[r.cycling_power_control_point=10854]="cycling_power_control_point",r[r.cycling_power_feature=10853]="cycling_power_feature",r[r.cycling_power_measurement=10851]="cycling_power_measurement",r[r.cycling_power_vector=10852]="cycling_power_vector",r[r.database_change_increment=10905]="database_change_increment",r[r.date_of_birth=10885]="date_of_birth",r[r.date_of_threshold_assessment=10886]="date_of_threshold_assessment",r[r.date_time=10760]="date_time",r[r.day_date_time=10762]="day_date_time",r[r.day_of_week=10761]="day_of_week",r[r.descriptor_value_changed=10877]="descriptor_value_changed",r[r["gap.device_name"]=10752]="gap.device_name",r[r.dew_point=10875]="dew_point",r[r.digital=10838]="digital",r[r.dst_offset=10765]="dst_offset",r[r.elevation=10860]="elevation",r[r.email_address=10887]="email_address",r[r.exact_time_256=10764]="exact_time_256",r[r.fat_burn_heart_rate_lower_limit=10888]="fat_burn_heart_rate_lower_limit",r[r.fat_burn_heart_rate_upper_limit=10889]="fat_burn_heart_rate_upper_limit",r[r.firmware_revision_string=10790]="firmware_revision_string",r[r.first_name=10890]="first_name",r[r.five_zone_heart_rate_limits=10891]="five_zone_heart_rate_limits",r[r.floor_number=10930]="floor_number",r[r.gender=10892]="gender",r[r.glucose_feature=10833]="glucose_feature",r[r.glucose_measurement=10776]="glucose_measurement",r[r.glucose_measurement_context=10804]="glucose_measurement_context",r[r.gust_factor=10868]="gust_factor",r[r.hardware_revision_string=10791]="hardware_revision_string",r[r.heart_rate_control_point=10809]="heart_rate_control_point",r[r.heart_rate_max=10893]="heart_rate_max",r[r.heart_rate_measurement=10807]="heart_rate_measurement",r[r.heat_index=10874]="heat_index",r[r.height=10894]="height",r[r.hid_control_point=10828]="hid_control_point",r[r.hid_information=10826]="hid_information",r[r.hip_circumference=10895]="hip_circumference",r[r.humidity=10863]="humidity",r[r["ieee_11073-20601_regulatory_certification_data_list"]=10794]="ieee_11073-20601_regulatory_certification_data_list",r[r.indoor_positioning_configuration=10925]="indoor_positioning_configuration",r[r.intermediate_blood_pressure=10806]="intermediate_blood_pressure",r[r.intermediate_temperature=10782]="intermediate_temperature",r[r.irradiance=10871]="irradiance",r[r.language=10914]="language",r[r.last_name=10896]="last_name",r[r.latitude=10926]="latitude",r[r.ln_control_point=10859]="ln_control_point",r[r.ln_feature=10858]="ln_feature",r[r["local_east_coordinate.xml"]=10929]="local_east_coordinate.xml",r[r.local_north_coordinate=10928]="local_north_coordinate",r[r.local_time_information=10767]="local_time_information",r[r.location_and_speed=10855]="location_and_speed",r[r.location_name=10933]="location_name",r[r.longitude=10927]="longitude",r[r.magnetic_declination=10796]="magnetic_declination",r[r.magnetic_flux_density_2D=10912]="magnetic_flux_density_2D",r[r.magnetic_flux_density_3D=10913]="magnetic_flux_density_3D",r[r.manufacturer_name_string=10793]="manufacturer_name_string",r[r.maximum_recommended_heart_rate=10897]="maximum_recommended_heart_rate",r[r.measurement_interval=10785]="measurement_interval",r[r.model_number_string=10788]="model_number_string",r[r.navigation=10856]="navigation",r[r.new_alert=10822]="new_alert",r[r["gap.peripheral_preferred_connection_parameters"]=10756]="gap.peripheral_preferred_connection_parameters",r[r["gap.peripheral_privacy_flag"]=10754]="gap.peripheral_privacy_flag",r[r.plx_continuous_measurement=10847]="plx_continuous_measurement",r[r.plx_features=10848]="plx_features",r[r.plx_spot_check_measurement=10846]="plx_spot_check_measurement",r[r.pnp_id=10832]="pnp_id",r[r.pollen_concentration=10869]="pollen_concentration",r[r.position_quality=10857]="position_quality",r[r.pressure=10861]="pressure",r[r.protocol_mode=10830]="protocol_mode",r[r.rainfall=10872]="rainfall",r[r["gap.reconnection_address"]=10755]="gap.reconnection_address",r[r.record_access_control_point=10834]="record_access_control_point",r[r.reference_time_information=10772]="reference_time_information",r[r.report=10829]="report",r[r.report_map=10827]="report_map",r[r.resting_heart_rate=10898]="resting_heart_rate",r[r.ringer_control_point=10816]="ringer_control_point",r[r.ringer_setting=10817]="ringer_setting",r[r.rsc_feature=10836]="rsc_feature",r[r.rsc_measurement=10835]="rsc_measurement",r[r.sc_control_point=10837]="sc_control_point",r[r.scan_interval_window=10831]="scan_interval_window",r[r.scan_refresh=10801]="scan_refresh",r[r.sensor_location=10845]="sensor_location",r[r.serial_number_string=10789]="serial_number_string",r[r["gatt.service_changed"]=10757]="gatt.service_changed",r[r.software_revision_string=10792]="software_revision_string",r[r.sport_type_for_aerobic_and_anaerobic_thresholds=10899]="sport_type_for_aerobic_and_anaerobic_thresholds",r[r.supported_new_alert_category=10823]="supported_new_alert_category",r[r.supported_unread_alert_category=10824]="supported_unread_alert_category",r[r.system_id=10787]="system_id",r[r.temperature=10862]="temperature",r[r.temperature_measurement=10780]="temperature_measurement",r[r.temperature_type=10781]="temperature_type",r[r.three_zone_heart_rate_limits=10900]="three_zone_heart_rate_limits",r[r.time_accuracy=10770]="time_accuracy",r[r.time_source=10771]="time_source",r[r.time_update_control_point=10774]="time_update_control_point",r[r.time_update_state=10775]="time_update_state",r[r.time_with_dst=10769]="time_with_dst",r[r.time_zone=10766]="time_zone",r[r.true_wind_direction=10865]="true_wind_direction",r[r.true_wind_speed=10864]="true_wind_speed",r[r.two_zone_heart_rate_limit=10901]="two_zone_heart_rate_limit",r[r.tx_power_level=10759]="tx_power_level",r[r.uncertainty=10932]="uncertainty",r[r.unread_alert_status=10821]="unread_alert_status",r[r.user_control_point=10911]="user_control_point",r[r.user_index=10906]="user_index",r[r.uv_index=10870]="uv_index",r[r.vo2_max=10902]="vo2_max",r[r.waist_circumference=10903]="waist_circumference",r[r.weight=10904]="weight",r[r.weight_measurement=10909]="weight_measurement",r[r.weight_scale_feature=10910]="weight_scale_feature",r[r.wind_chill=10873]="wind_chill",(n=e.bluetoothDescriptors||(e.bluetoothDescriptors={}))[n["gatt.characteristic_extended_properties"]=10496]="gatt.characteristic_extended_properties",n[n["gatt.characteristic_user_description"]=10497]="gatt.characteristic_user_description",n[n["gatt.client_characteristic_configuration"]=10498]="gatt.client_characteristic_configuration",n[n["gatt.server_characteristic_configuration"]=10499]="gatt.server_characteristic_configuration",n[n["gatt.characteristic_presentation_format"]=10500]="gatt.characteristic_presentation_format",n[n["gatt.characteristic_aggregate_format"]=10501]="gatt.characteristic_aggregate_format",n[n.valid_range=10502]="valid_range",n[n.external_report_reference=10503]="external_report_reference",n[n.report_reference=10504]="report_reference",n[n.number_of_digitals=10505]="number_of_digitals",n[n.value_trigger_setting=10506]="value_trigger_setting",n[n.es_configuration=10507]="es_configuration",n[n.es_measurement=10508]="es_measurement",n[n.es_trigger_setting=10509]="es_trigger_setting",n[n.time_trigger_setting=10510]="time_trigger_setting";class E extends a{constructor(){super(),this.deviceHandles={},this.serviceHandles={},this.characteristicHandles={},this.descriptorHandles={},this.charNotifies={},this.discoverFn=null,this.initialised=!1,this.enabled=!1,this.os="browser",this.enabled=this.state,t.on("stateChange",()=>{this.enabled!==this.state&&(this.enabled=this.state,this.emit(E.EVENT_ENABLED,this.enabled))})}get state(){return"poweredOn"===t.state}init(e){if(this.initialised)return e();t.on("discover",e=>{this.discoverFn&&this.discoverFn(e)}),this.initialised=!0,e()}checkForError(e,t,i){return function(r){if(r)e(r);else if("function"==typeof t){const e=[].slice.call(arguments,1);null===i?t.apply(this,e):setTimeout(()=>t.apply(this,e),i)}}}bufferToDataView(e){const t=new Uint8Array(e).buffer;return new DataView(t)}dataViewToBuffer(e){const t=new Uint8Array(e.buffer);return new Buffer(t)}validDevice(e,t){if(0===t.length)return!0;if(!e.advertisement.serviceUuids)return!1;const i=e.advertisement.serviceUuids.map(e=>g(e));return t.some(e=>i.indexOf(e)>=0)}deviceToBluetoothDevice(e){const t=e.address&&"unknown"!==e.address?e.address:e.id,i=[];e.advertisement.serviceUuids&&e.advertisement.serviceUuids.forEach(e=>{i.push(g(e))});const r=new Map;if(e.advertisement.manufacturerData){const t=e.advertisement.manufacturerData.readUInt16LE(0),i=e.advertisement.manufacturerData.slice(2);r.set(("0000"+t.toString(16)).slice(-4),this.bufferToDataView(i))}const n=new Map;return e.advertisement.serviceData&&e.advertisement.serviceData.forEach(e=>{n.set(g(e.uuid),this.bufferToDataView(e.data))}),{id:t,name:e.advertisement.localName,_serviceUUIDs:i,adData:{rssi:e.rssi,txPower:e.advertisement.txPowerLevel,serviceData:n,manufacturerData:r}}}getEnabled(e){function i(){e(this.state)}"unknown"===t.state||"poweredOff"===t.state?t.once("stateChange",i.bind(this)):i.call(this)}startScan(e,i,r,n){this.discoverFn=t=>{if(this.validDevice(t,e)){const e=this.deviceToBluetoothDevice(t);this.deviceHandles[e.id]||(this.deviceHandles[e.id]=t,i(e))}},this.init(()=>{function e(){!0===this.state?t.startScanning([],!0,this.checkForError(n,r)):n("adapter not enabled")}this.deviceHandles={},"unknown"===t.state||"poweredOff"===t.state?t.once("stateChange",e.bind(this)):e.call(this)})}stopScan(e){this.discoverFn=null,t.stopScanning()}connect(e,t,i,r){const n=this.deviceHandles[e];n.removeAllListeners("connect"),n.removeAllListeners("disconnect"),n.once("connect",t),n.once("disconnect",()=>{this.serviceHandles={},this.characteristicHandles={},this.descriptorHandles={},this.charNotifies={},i()}),n.connect(this.checkForError(r))}disconnect(e,t){this.deviceHandles[e].disconnect(this.checkForError(t))}discoverServices(e,t,i,r){this.deviceHandles[e].discoverServices([],this.checkForError(r,e=>{const r=[];e.forEach(e=>{const i=g(e.uuid);(0===t.length||t.indexOf(i)>=0)&&(this.serviceHandles[i]||(this.serviceHandles[i]=e),r.push({uuid:i,primary:!0}))}),i(r)}))}discoverIncludedServices(e,t,i,r){this.serviceHandles[e].discoverIncludedServices([],this.checkForError(r,e=>{const r=[];e.forEach(e=>{const i=g(e.uuid);(0===t.length||t.indexOf(i)>=0)&&(this.serviceHandles[i]||(this.serviceHandles[i]=e),r.push({uuid:i,primary:!1}))},this),i(r)}))}discoverCharacteristics(e,t,i,r){this.serviceHandles[e].discoverCharacteristics([],this.checkForError(r,e=>{const r=[];e.forEach(e=>{const i=g(e.uuid);(0===t.length||t.indexOf(i)>=0)&&(this.characteristicHandles[i]||(this.characteristicHandles[i]=e),r.push({uuid:i,properties:{broadcast:e.properties.indexOf("broadcast")>=0,read:e.properties.indexOf("read")>=0,writeWithoutResponse:e.properties.indexOf("writeWithoutResponse")>=0,write:e.properties.indexOf("write")>=0,notify:e.properties.indexOf("notify")>=0,indicate:e.properties.indexOf("indicate")>=0,authenticatedSignedWrites:e.properties.indexOf("authenticatedSignedWrites")>=0,reliableWrite:e.properties.indexOf("reliableWrite")>=0,writableAuxiliaries:e.properties.indexOf("writableAuxiliaries")>=0}}),e.on("data",(e,t)=>{if(!0===t&&"function"==typeof this.charNotifies[i]){const t=this.bufferToDataView(e);this.charNotifies[i](t)}}))},this),i(r)}))}discoverDescriptors(e,t,i,r){const n=this.characteristicHandles[e];n.discoverDescriptors(this.checkForError(r,e=>{const r=[];e.forEach(e=>{const i=g(e.uuid);if(0===t.length||t.indexOf(i)>=0){const t=n.uuid+"-"+e.uuid;this.descriptorHandles[t]||(this.descriptorHandles[t]=e),r.push({uuid:i})}},this),i(r)}))}readCharacteristic(e,t,i){this.characteristicHandles[e].read(this.checkForError(i,e=>{const i=this.bufferToDataView(e);t(i)}))}writeCharacteristic(e,t,i,r){const n=this.dataViewToBuffer(t),s=this.characteristicHandles[e],a=s.properties.indexOf("writeWithoutResponse")>=0||s.properties.indexOf("authenticatedSignedWrites")>=0,c="darwin"!==this.os&&a?25:null;s.write(n,a,this.checkForError(r,i,c))}enableNotify(e,t,i,r){if(this.charNotifies[e])return this.charNotifies[e]=t,i();this.characteristicHandles[e].once("notify",n=>{if(!0!==n)return r("notify failed to enable");this.charNotifies[e]=t,i()}),this.characteristicHandles[e].notify(!0,this.checkForError(r))}disableNotify(e,t,i){if(!this.charNotifies[e])return t();this.characteristicHandles[e].once("notify",r=>{if(!1!==r)return i("notify failed to disable");this.charNotifies[e]&&delete this.charNotifies[e],t()}),this.characteristicHandles[e].notify(!1,this.checkForError(i))}readDescriptor(e,t,i){this.descriptorHandles[e].readValue(this.checkForError(i,e=>{const i=this.bufferToDataView(e);t(i)}))}writeDescriptor(e,t,i,r){const n=this.dataViewToBuffer(t);this.descriptorHandles[e].writeValue(n,this.checkForError(r,i))}}E.EVENT_ENABLED="enabledchanged";const x=new E;class L{constructor(e){this.characteristic=null,this.uuid=null,this._value=null,this.handle=null,this.characteristic=e.characteristic,this.uuid=e.uuid,this._value=e.value,this.handle=`${this.characteristic.uuid}-${this.uuid}`}get value(){return this._value}readValue(){return new Promise((e,t)=>{if(!this.characteristic.service.device.gatt.connected)return t("readValue error: device not connected");x.readDescriptor(this.handle,t=>{this._value=t,e(t)},e=>{t(`readValue error: ${e}`)})})}writeValue(e){return new Promise((t,i)=>{if(!this.characteristic.service.device.gatt.connected)return i("writeValue error: device not connected");const r=function(e){return void 0!==e.buffer}(e)?e.buffer:e,n=new DataView(r);x.writeDescriptor(this.handle,n,()=>{this._value=n,t()},e=>{i(`writeValue error: ${e}`)})})}}class D{constructor(e,t){this.bubbles=!0,this.cancelable=!1,this.cancelBubble=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=0,this.isTrusted=!0,this.returnValue=!0,this.target=e,this.srcElement=e,this.currentTarget=e,this.type=t}composedPath(){return[]}initEvent(e,t,i){this.type=e,this.bubbles=t,this.cancelable=i}preventDefault(){this.defaultPrevented=!0}stopImmediatePropagation(){}stopPropagation(){}}class P extends f{constructor(e){super(),this.service=null,this.uuid=null,this._value=null,this.handle=null,this.descriptors=null,this.service=e.service,this.uuid=e.uuid,this.properties=e.properties,this._value=e.value,this.handle=this.uuid}get value(){return this._value}set oncharacteristicvaluechanged(e){this._oncharacteristicvaluechanged&&this.removeEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged),this._oncharacteristicvaluechanged=e,this.addEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged)}setValue(e,t){this._value=e,t&&(this.dispatchEvent(new D(this,"characteristicvaluechanged")),this.service.dispatchEvent(new D(this,"characteristicvaluechanged")),this.service.device.dispatchEvent(new D(this,"characteristicvaluechanged")),this.service.device._bluetooth.dispatchEvent(new D(this,"characteristicvaluechanged")))}getDescriptor(e){return new Promise((t,i)=>this.service.device.gatt.connected?e?void this.getDescriptors(e).then(e=>{if(1!==e.length)return i("getDescriptor error: descriptor not found");t(e[0])}).catch(e=>{i(`getDescriptor error: ${e}`)}):i("getDescriptor error: no descriptor specified"):i("getDescriptor error: device not connected"))}getDescriptors(e){return new Promise((t,i)=>{if(!this.service.device.gatt.connected)return i("getDescriptors error: device not connected");function r(){if(!e)return t(this.descriptors);const r=this.descriptors.filter(t=>t.uuid===y(e));if(1!==r.length)return i("getDescriptors error: descriptor not found");t(r)}if(this.descriptors)return r.call(this);x.discoverDescriptors(this.handle,[],e=>{this.descriptors=e.map(e=>(Object.assign(e,{characteristic:this}),new L(e))),r.call(this)},e=>{i(`getDescriptors error: ${e}`)})})}readValue(){return new Promise((e,t)=>{if(!this.service.device.gatt.connected)return t("readValue error: device not connected");x.readCharacteristic(this.handle,t=>{this.setValue(t,!0),e(t)},e=>{t(`readValue error: ${e}`)})})}writeValue(e){return new Promise((t,i)=>{if(!this.service.device.gatt.connected)return i("writeValue error: device not connected");const r=function(e){return void 0!==e.buffer}(e)?e.buffer:e,n=new DataView(r);x.writeCharacteristic(this.handle,n,()=>{this.setValue(n),t()},e=>{i(`writeValue error: ${e}`)})})}startNotifications(){return new Promise((e,t)=>{if(!this.service.device.gatt.connected)return t("startNotifications error: device not connected");x.enableNotify(this.handle,e=>{this.setValue(e,!0)},()=>{e(this)},e=>{t(`startNotifications error: ${e}`)})})}stopNotifications(){return new Promise((e,t)=>{if(!this.service.device.gatt.connected)return t("stopNotifications error: device not connected");x.disableNotify(this.handle,()=>{e(this)},e=>{t(`stopNotifications error: ${e}`)})})}}class S extends f{constructor(e){super(),this.device=null,this.uuid=null,this.isPrimary=!1,this.handle=null,this.services=null,this.characteristics=null,this.device=e.device,this.uuid=e.uuid,this.isPrimary=e.isPrimary,this.handle=this.uuid,this.dispatchEvent(new D(this,"serviceadded")),this.device.dispatchEvent(new D(this,"serviceadded")),this.device._bluetooth.dispatchEvent(new D(this,"serviceadded"))}set oncharacteristicvaluechanged(e){this._oncharacteristicvaluechanged&&this.removeEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged),this._oncharacteristicvaluechanged=e,this.addEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged)}set onserviceadded(e){this._onserviceadded&&this.removeEventListener("serviceadded",this._onserviceadded),this._onserviceadded=e,this.addEventListener("serviceadded",this._onserviceadded)}set onservicechanged(e){this._onservicechanged&&this.removeEventListener("servicechanged",this._onservicechanged),this._onservicechanged=e,this.addEventListener("servicechanged",this._onservicechanged)}set onserviceremoved(e){this._onserviceremoved&&this.removeEventListener("serviceremoved",this._onserviceremoved),this._onserviceremoved=e,this.addEventListener("serviceremoved",this._onserviceremoved)}getCharacteristic(e){return new Promise((t,i)=>this.device.gatt.connected?e?void this.getCharacteristics(e).then(e=>{if(1!==e.length)return i("getCharacteristic error: characteristic not found");t(e[0])}).catch(e=>{i(`getCharacteristic error: ${e}`)}):i("getCharacteristic error: no characteristic specified"):i("getCharacteristic error: device not connected"))}getCharacteristics(e){return new Promise((t,i)=>{if(!this.device.gatt.connected)return i("getCharacteristics error: device not connected");function r(){if(!e)return t(this.characteristics);e=b(e);const r=this.characteristics.filter(t=>t.uuid===e);if(1!==r.length)return i("getCharacteristics error: characteristic not found");t(r)}if(this.characteristics)return r.call(this);x.discoverCharacteristics(this.handle,[],e=>{this.characteristics=e.map(e=>(Object.assign(e,{service:this}),new P(e))),r.call(this)},e=>{i(`getCharacteristics error: ${e}`)})})}getIncludedService(e){return new Promise((t,i)=>this.device.gatt.connected?e?void this.getIncludedServices(e).then(e=>{if(1!==e.length)return i("getIncludedService error: service not found");t(e[0])}).catch(e=>{i(`getIncludedService error: ${e}`)}):i("getIncludedService error: no service specified"):i("getIncludedService error: device not connected"))}getIncludedServices(e){return new Promise((t,i)=>{if(!this.device.gatt.connected)return i("getIncludedServices error: device not connected");function r(){if(!e)return t(this.services);const r=this.services.filter(t=>t.uuid===w(e));if(1!==r.length)return i("getIncludedServices error: service not found");t(r)}if(this.services)return r.call(this);x.discoverIncludedServices(this.handle,this.device._allowedServices,e=>{this.services=e.map(e=>(Object.assign(e,{device:this.device}),new S(e))),r.call(this)},e=>{i(`getIncludedServices error: ${e}`)})})}}class C{constructor(e){this.device=null,this._connected=!1,this.handle=null,this.services=null,this.device=e,this.handle=this.device.id}get connected(){return this._connected}connect(){return new Promise((e,t)=>{if(this.connected)return t("connect error: device already connected");x.connect(this.handle,()=>{this._connected=!0,e(this)},()=>{this.services=null,this._connected=!1,this.device.dispatchEvent(new D(this.device,"gattserverdisconnected")),this.device._bluetooth.dispatchEvent(new D(this.device,"gattserverdisconnected"))},e=>{t(`connect Error: ${e}`)})})}disconnect(){x.disconnect(this.handle),this._connected=!1}getPrimaryService(e){return new Promise((t,i)=>this.connected?e?void this.getPrimaryServices(e).then(e=>{if(1!==e.length)return i("getPrimaryService error: service not found");t(e[0])}).catch(e=>{i(`getPrimaryService error: ${e}`)}):i("getPrimaryService error: no service specified"):i("getPrimaryService error: device not connected"))}getPrimaryServices(e){return new Promise((t,i)=>{if(!this.connected)return i("getPrimaryServices error: device not connected");function r(){if(!e)return t(this.services);const r=this.services.filter(t=>t.uuid===w(e));if(1!==r.length)return i("getPrimaryServices error: service not found");t(r)}if(this.services)return r.call(this);x.discoverServices(this.handle,this.device._allowedServices,e=>{this.services=e.map(e=>(Object.assign(e,{device:this.device}),new S(e))),r.call(this)},e=>{i(`getPrimaryServices error: ${e}`)})})}}class k extends f{constructor(e){super(),this.id=null,this.name=null,this.gatt=null,this.watchingAdvertisements=!1,this._bluetooth=null,this._allowedServices=[],this._serviceUUIDs=[],this.id=e.id,this.name=e.name,this.gatt=e.gatt,this.watchAdvertisements=e.watchAdvertisements,this.adData=e.adData,this._bluetooth=e._bluetooth,this._allowedServices=e._allowedServices,this._serviceUUIDs=e._serviceUUIDs,this.name||(this.name=`Unknown or Unsupported Device (${this.id})`),this.gatt||(this.gatt=new C(this))}set oncharacteristicvaluechanged(e){this._oncharacteristicvaluechanged&&this.removeEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged),this._oncharacteristicvaluechanged=e,this.addEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged)}set onserviceadded(e){this._onserviceadded&&this.removeEventListener("serviceadded",this._onserviceadded),this._onserviceadded=e,this.addEventListener("serviceadded",this._onserviceadded)}set onservicechanged(e){this._onservicechanged&&this.removeEventListener("servicechanged",this._onservicechanged),this._onservicechanged=e,this.addEventListener("servicechanged",this._onservicechanged)}set onserviceremoved(e){this._onserviceremoved&&this.removeEventListener("serviceremoved",this._onserviceremoved),this._onserviceremoved=e,this.addEventListener("serviceremoved",this._onserviceremoved)}set ongattserverdisconnected(e){this._ongattserverdisconnected&&this.removeEventListener("gattserverdisconnected",this._ongattserverdisconnected),this._ongattserverdisconnected=e,this.addEventListener("gattserverdisconnected",this._ongattserverdisconnected)}set onadvertisementreceived(e){this._onadvertisementreceived&&this.removeEventListener("advertisementreceived",this._onadvertisementreceived),this._onadvertisementreceived=e,this.addEventListener("advertisementreceived",this._onadvertisementreceived)}watchAdvertisements(){return new Promise((e,t)=>{t("watchAdvertisements error: method not implemented")})}unwatchAdvertisements(){return new Promise((e,t)=>{t("unwatchAdvertisements error: method not implemented")})}}class O extends f{constructor(e){super(),this.deviceFound=null,this.scanTime=10240,this.scanner=null,e=e||{},this.referringDevice=e.referringDevice,this.deviceFound=e.deviceFound,e.scanTime&&(this.scanTime=1e3*e.scanTime),x.on(E.EVENT_ENABLED,e=>{this.dispatchEvent(new D(this,"availabilitychanged"))})}set oncharacteristicvaluechanged(e){this._oncharacteristicvaluechanged&&this.removeEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged),this._oncharacteristicvaluechanged=e,this.addEventListener("characteristicvaluechanged",this._oncharacteristicvaluechanged)}set onserviceadded(e){this._onserviceadded&&this.removeEventListener("serviceadded",this._onserviceadded),this._onserviceadded=e,this.addEventListener("serviceadded",this._onserviceadded)}set onservicechanged(e){this._onservicechanged&&this.removeEventListener("servicechanged",this._onservicechanged),this._onservicechanged=e,this.addEventListener("servicechanged",this._onservicechanged)}set onserviceremoved(e){this._onserviceremoved&&this.removeEventListener("serviceremoved",this._onserviceremoved),this._onserviceremoved=e,this.addEventListener("serviceremoved",this._onserviceremoved)}set ongattserverdisconnected(e){this._ongattserverdisconnected&&this.removeEventListener("gattserverdisconnected",this._ongattserverdisconnected),this._ongattserverdisconnected=e,this.addEventListener("gattserverdisconnected",this._ongattserverdisconnected)}set onadvertisementreceived(e){this._onadvertisementreceived&&this.removeEventListener("advertisementreceived",this._onadvertisementreceived),this._onadvertisementreceived=e,this.addEventListener("advertisementreceived",this._onadvertisementreceived)}set onavailabilitychanged(e){this._onavailabilitychanged&&this.removeEventListener("availabilitychanged",this._onavailabilitychanged),this._onavailabilitychanged=e,this.addEventListener("availabilitychanged",this._onavailabilitychanged)}filterDevice(e,t,i){let r=!1;return e.forEach(e=>{if(!e.name||e.name===t.name){if(e.namePrefix){if(!t.name||e.namePrefix.length>t.name.length)return;if(e.namePrefix!==t.name.substr(0,e.namePrefix.length))return}if(e.services){const r=e.services.map(w);if(!r.every(e=>t._serviceUUIDs.indexOf(e)>-1))return;i=i.concat(r)}r=!0}}),!!r&&t}getAvailability(){return new Promise((e,t)=>{x.getEnabled(t=>{e(t)})})}requestDevice(e={filters:[]}){return new Promise((t,i)=>{if(null!==this.scanner)return i("requestDevice error: request in progress");const r=e=>void 0!==e.filters;let n=[];if(r(e)){if(0===e.filters.length)return i(new TypeError("requestDevice error: no filters specified"));if(e.filters.some(e=>0===Object.keys(e).length))return i(new TypeError("requestDevice error: empty filter specified"));if(e.filters.some(e=>void 0!==e.namePrefix&&""===e.namePrefix))return i(new TypeError("requestDevice error: empty namePrefix specified"));e.filters.forEach(e=>{e.services&&(n=n.concat(e.services.map(w))),n=n.filter((e,t,i)=>i.indexOf(e)===t)})}else if(!(e=>!0===e.acceptAllDevices)(e))return i(new TypeError("requestDevice error: specify filters or acceptAllDevices"));let s=!1;x.startScan(n,i=>{let n=[];function a(e){this.cancelRequest().then(()=>{t(e)})}if(r(e)&&(i=this.filterDevice(e.filters,i,n)),i){s=!0,e.optionalServices&&(n=n.concat(e.optionalServices.map(w)));const t=n.filter((e,t,i)=>i.indexOf(e)===t);Object.assign(i,{_bluetooth:this,_allowedServices:t});const r=new k(i);function c(){a.call(this,r)}this.deviceFound&&!0!==this.deviceFound(r,c.bind(this))||a.call(this,r)}},()=>{this.scanner=setTimeout(()=>{this.cancelRequest().then(()=>{s||i("requestDevice error: no devices found")})},this.scanTime)},e=>i(`requestDevice error: ${e}`))})}cancelRequest(){return new Promise((e,t)=>{this.scanner&&(clearTimeout(this.scanner),this.scanner=null,x.stopScan()),e()})}}O.EVENT_AVAILABILITY="availabilitychanged";const T=new O;e.Bluetooth=O,e.bluetooth=T,e.getCanonicalUUID=g,e.getCharacteristicUUID=b,e.getDescriptorUUID=y,e.getServiceUUID=w,Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=webbluetooth.umd.js.map

@@ -6,3 +6,3 @@ # Node Web Bluetooth

[Node.js > v6.15.0](https://nodejs.org), which includes `npm`.
[Node.js > v8.14.0](https://nodejs.org), which includes `npm`.

@@ -31,13 +31,10 @@ ## Installation

```JavaScript
var bluetooth = require("webbluetooth").bluetooth;
const bluetooth = require("webbluetooth").bluetooth;
bluetooth.requestDevice({
const device = await bluetooth.requestDevice({
filters:[{ services:[ "heart_rate" ] }]
})
.then(device => {
return device.gatt.connect();
})
.then(server => {
...
})
});
const server = await device.gatt.connect();
...
```

@@ -52,5 +49,5 @@

```JavaScript
var Bluetooth = require("webbluetooth").Bluetooth;
const Bluetooth = require("webbluetooth").Bluetooth;
function handleDeviceFound(device, selectFn) {
const deviceFound = (device, selectFn) => {
// If device can be automatically selected, do so by returning true

@@ -60,17 +57,12 @@ if (device.name === "myName") return true;

// Otherwise store the selectFn somewhere and execute it later to select this device
}
};
var bluetooth = new Bluetooth({
deviceFound: handleDeviceFound
const bluetooth = new Bluetooth({ deviceFound });
const device = await bluetooth.requestDevice({
filters:[{ services:[ "heart_rate" ] }]
});
bluetooth.requestDevice({
filters:[{ services:[ "heart_rate" ] }]
})
.then(device => {
return device.gatt.connect();
})
.then(server => {
...
})
const server = await device.gatt.connect();
...
```

@@ -77,0 +69,0 @@

@@ -26,7 +26,7 @@ /*

var webbluetooth = require("../");
const webbluetooth = require("../");
var eddystoneUUID = 0xFEAA;
const eddystoneUUID = 0xFEAA;
var frameTypes = {
const frameTypes = {
"UID": 0x00,

@@ -37,3 +37,3 @@ "URL": 0x10,

var schemes = {
const schemes = {
0x00: "http://www.",

@@ -45,3 +45,3 @@ 0x01: "https://www.",

var expansions = {
const expansions = {
0x00: ".com/",

@@ -63,17 +63,17 @@ 0x01: ".org/",

function handleDeviceFound(bluetoothDevice) {
var uuid = webbluetooth.getServiceUUID(eddystoneUUID);
var eddyData = bluetoothDevice.adData.serviceData.get(uuid);
const deviceFound = bluetoothDevice => {
const uuid = webbluetooth.getServiceUUID(eddystoneUUID);
const eddyData = bluetoothDevice.adData.serviceData.get(uuid);
if (eddyData) {
var decoded = decodeEddystone(eddyData);
const decoded = decodeEddystone(eddyData);
if (decoded) {
switch(decoded.type) {
case frameTypes.UID:
console.log("txPower: " + decoded.txPower);
console.log(`txPower: ${decoded.txPower}`);
break;
case frameTypes.URL:
console.log("url: " + decoded.url);
console.log(`url: ${decoded.url}`);
break;
case frameTypes.TLM:
console.log("version: " + decoded.version);
console.log(`version: ${decoded.version}`);
break;

@@ -83,16 +83,14 @@ }

}
}
};
var bluetooth = new webbluetooth.Bluetooth({
deviceFound: handleDeviceFound
});
const bluetooth = new webbluetooth.Bluetooth({ deviceFound });
function decodeEddystone(view) {
var type = view.getUint8(0);
if (typeof type === "undefined") return null;
const decodeEddystone = view => {
const type = view.getUint8(0);
if (typeof type === "undefined") return undefined;
if (type === frameTypes.UID) {
var uidArray = [];
for (var i = 2; i < view.byteLength; i++) {
var hex = view.getUint8(i).toString(16);
const uidArray = [];
for (let i = 2; i < view.byteLength; i++) {
const hex = view.getUint8(i).toString(16);
uidArray.push(("00" + hex).slice(-2));

@@ -109,4 +107,4 @@ }

if (type === frameTypes.URL) {
var url = "";
for (var i = 2; i < view.byteLength; i++) {
const url = "";
for (let i = 2; i < view.byteLength; i++) {
if (i === 2) {

@@ -137,14 +135,16 @@ url += schemes[view.getUint8(i)];

// Recursively scan
function scan() {
// Continuously scan
(async () => {
console.log("scanning...");
bluetooth.requestDevice({
filters:[{ services:[ eddystoneUUID ] }]
})
.then(scan)
.catch(error => {
console.log(error);
process.exit();
});
}
scan();
while (true) {
try {
await bluetooth.requestDevice({
filters: [{ services: [ eddystoneUUID ] }]
});
} catch (error) {
console.log(error);
process.exit();
}
}
})();

@@ -26,34 +26,32 @@ /*

var bluetooth = require("../").bluetooth;
const bluetooth = require("../").bluetooth;
console.log("Requesting Bluetooth Devices...");
bluetooth.requestDevice({
filters:[{ services:[ "heart_rate" ] }]
})
.then(device => {
console.log("Found device: " + device.name);
return device.gatt.connect();
})
.then(server => {
console.log("Gatt server connected: " + server.connected);
return server.getPrimaryService("heart_rate");
})
.then(service => {
console.log("Primary service: " + service.uuid);
return service.getCharacteristic("heart_rate_measurement");
})
.then(characteristic => {
console.log("Characteristic: " + characteristic.uuid);
return characteristic.startNotifications();
})
.then(characteristic => {
console.log("Notifications started");
(async () => {
try {
console.log("Requesting Bluetooth Devices...");
characteristic.addEventListener("characteristicvaluechanged", event => {
if (event.value.buffer.byteLength) console.log(event.value.getUint16(0));
});
})
.catch(error => {
console.log(error);
process.exit();
});
const device = await bluetooth.requestDevice({
filters: [{ services: [ "heart_rate" ] }]
});
console.log(`Found device: ${device.name}`);
const server = await device.gatt.connect();
console.log(`Gatt server connected: ${server.connected}`);
const service = await server.getPrimaryService("heart_rate");
console.log(`Primary service: ${service.uuid}`);
const characteristic = await service.getCharacteristic("heart_rate_measurement");
console.log(`Characteristic: ${characteristic.uuid}`);
await characteristic.startNotifications();
console.log("Notifications started");
characteristic.addEventListener("characteristicvaluechanged", event => {
if (event.value.buffer.byteLength) console.log(event.value.getUint16(0));
});
} catch(error) {
console.log(error);
process.exit(1);
};
})();

@@ -26,21 +26,22 @@ /*

var Bluetooth = require("../").Bluetooth;
var bluetoothDevices = [];
const Bluetooth = require("../").Bluetooth;
const bluetoothDevices = [];
process.stdin.setEncoding("utf8");
process.stdin.on("readable", () => {
var input = process.stdin.read();
const input = process.stdin.read();
if (input === "\u0003") {
process.exit();
} else {
var index = parseInt(input);
if (index && index <= bluetoothDevices.length) {
process.stdin.setRawMode(false);
selectDevice(index - 1);
}
}
const index = parseInt(input);
if (index && index <= bluetoothDevices.length) {
process.stdin.setRawMode(false);
const device = bluetoothDevices[index - 1];
device.select();
}
});
function handleDeviceFound(bluetoothDevice, selectFn) {
var discovered = bluetoothDevices.some(device => {
const deviceFound = (bluetoothDevice, selectFn) => {
const discovered = bluetoothDevices.some(device => {
return (device.id === bluetoothDevice.id);

@@ -57,70 +58,49 @@ });

console.log(bluetoothDevices.length + ": " + bluetoothDevice.name);
console.log(`${bluetoothDevices.length}: ${bluetoothDevice.name}`);
if (bluetoothDevice._serviceUUIDs.length) {
console.log("\tAdvertising: " + bluetoothDevice._serviceUUIDs);
console.log(`\tAdvertising: ${bluetoothDevice._serviceUUIDs}`);
}
}
};
var bluetooth = new Bluetooth({
deviceFound: handleDeviceFound
});
const enumerateGatt = async server => {
const services = await server.getPrimaryServices();
const sPromises = services.map(async service => {
const characteristics = await service.getCharacteristics();
const cPromises = characteristics.map(async characteristic => {
let descriptors = await characteristic.getDescriptors();
descriptors = descriptors.map(descriptor => `\t\t└descriptor: ${descriptor.uuid}`);
descriptors.unshift(`\t└characteristic: ${characteristic.uuid}`);
return descriptors.join("\n");
});
function logError(error) {
console.log(error);
process.exit();
}
const descriptors = await Promise.all(cPromises);
descriptors.unshift(`service: ${service.uuid}`);
return descriptors.join("\n");
});
function enumerateGatt(server) {
return server.getPrimaryServices()
.then(services => {
var sPromises = services.map(service => {
return service.getCharacteristics()
.then(characteristics => {
var cPromises = characteristics.map(characteristic => {
return characteristic.getDescriptors()
.then(descriptors => {
descriptors = descriptors.map(descriptor => `\t\t└descriptor: ${descriptor.uuid}`);
descriptors.unshift(`\t└characteristic: ${characteristic.uuid}`);
return descriptors.join("\n");
});
});
const result = await Promise.all(sPromises);
console.log(result.join("\n"));
};
return Promise.all(cPromises)
.then(descriptors => {
descriptors.unshift(`service: ${service.uuid}`);
return descriptors.join("\n");
});
});
});
const bluetooth = new Bluetooth({ deviceFound });
console.log("scanning...");
return Promise.all(sPromises)
.then(services => {
console.log(services.join("\n"));
(async () => {
try {
const device = await bluetooth.requestDevice({
acceptAllDevices: true
});
});
}
console.log("connecting...");
function selectDevice(index) {
var device = bluetoothDevices[index];
device.select();
}
const server = await device.gatt.connect();
console.log("connected");
var server = null;
console.log("scanning...");
await enumerateGatt(server);
await server.disconnect();
bluetooth.requestDevice()
.then(device => {
console.log("connecting...");
return device.gatt.connect();
})
.then(gattServer => {
console.log("connected");
server = gattServer;
return enumerateGatt(server);
})
.then(() => server.disconnect())
.then(() => {
console.log("\ndisconnected");
process.exit();
})
.catch(logError);
console.log("\ndisconnected");
} catch (error) {
console.log(error);
}
process.exit(0);
})();
{
"name": "webbluetooth",
"version": "1.3.1-next.b464a24.0",
"version": "2.0.0",
"description": "Node.js implementation of the Web Bluetooth Specification",

@@ -25,3 +25,3 @@ "homepage": "https://github.com/thegecko/webbluetooth",

"engines": {
"node": ">=6.15.0"
"node": ">=8.14.0"
},

@@ -43,4 +43,5 @@ "devDependencies": {

"@types/node": "^8.0.54",
"@types/web-bluetooth": "^0.0.5",
"@abandonware/noble": "thegecko/noble"
}
}

@@ -10,3 +10,3 @@ # Node Web Bluetooth

[Node.js > v6.15.0](https://nodejs.org), which includes `npm`.
[Node.js > v8.14.0](https://nodejs.org), which includes `npm`.

@@ -97,5 +97,13 @@ ## Installation

- [x] availabilitychanged - specification unstable
#### Bluetooth
- [x] availabilitychanged
#### Bluetooth Device
- [x] gattserverdisconnected
- [x] characteristicvaluechanged
- [ ] advertisementreceived - specification unstable
#### Bluetooth Service
- [x] serviceadded

@@ -105,2 +113,6 @@ - [ ] servicechanged - unsupported in noble

#### Bluetooth Characteristic
- [x] characteristicvaluechanged
### Other

@@ -107,0 +119,0 @@

@@ -31,3 +31,2 @@ /*

import { BluetoothRemoteGATTService } from "./service";
import { BluetoothRemoteGATTDescriptor } from "./descriptor";
import { BluetoothRemoteGATTCharacteristic } from "./characteristic";

@@ -34,0 +33,0 @@ import * as noble from "@abandonware/noble";

@@ -26,6 +26,8 @@ /*

import { EventDispatcher } from "./dispatcher";
import { BluetoothDevice } from "./device";
import { EventDispatcher, TypedDispatcher } from "./dispatcher";
import { BluetoothDevice, BluetoothDeviceEvents } from "./device";
import { getServiceUUID } from "./helpers";
import { adapter, NobleAdapter } from "./adapter";
import { W3CBluetooth } from "./interfaces";
import { DOMEvent } from "./events";

@@ -53,50 +55,15 @@ /**

/**
* BluetoothLE Scan Filter Init interface
* @hidden
*/
export interface BluetoothLEScanFilterInit {
export interface BluetoothEvents extends BluetoothDeviceEvents {
/**
* An array of service UUIDs to filter on
* Bluetooth Availability Changed event
*/
services?: Array<string | number>;
/**
* The device name to filter on
*/
name?: string;
/**
* The device name prefix to filter on
*/
namePrefix?: string;
// Maps unsigned shorts to BluetoothDataFilters.
// object manufacturerData;
// Maps BluetoothServiceUUIDs to BluetoothDataFilters.
// object serviceData;
availabilitychanged: Event;
}
/**
* Request Device Options interface
*/
export interface RequestDeviceOptions {
/**
* An array of device filters to match
*/
filters?: Array<BluetoothLEScanFilterInit>;
/**
* An array of optional services to have access to
*/
optionalServices?: Array<string | number>;
/**
* Whether to accept all devices
*/
acceptAllDevices?: boolean;
}
/**
* Bluetooth class
*/
export class Bluetooth extends EventDispatcher {
export class Bluetooth extends (EventDispatcher as new() => TypedDispatcher<BluetoothEvents>) implements W3CBluetooth {

@@ -118,2 +85,65 @@ /**

private _oncharacteristicvaluechanged: (ev: Event) => void;
public set oncharacteristicvaluechanged(fn: (ev: Event) => void) {
if (this._oncharacteristicvaluechanged) {
this.removeEventListener("characteristicvaluechanged", this._oncharacteristicvaluechanged);
}
this._oncharacteristicvaluechanged = fn;
this.addEventListener("characteristicvaluechanged", this._oncharacteristicvaluechanged);
}
private _onserviceadded: (ev: Event) => void;
public set onserviceadded(fn: (ev: Event) => void) {
if (this._onserviceadded) {
this.removeEventListener("serviceadded", this._onserviceadded);
}
this._onserviceadded = fn;
this.addEventListener("serviceadded", this._onserviceadded);
}
private _onservicechanged: (ev: Event) => void;
public set onservicechanged(fn: (ev: Event) => void) {
if (this._onservicechanged) {
this.removeEventListener("servicechanged", this._onservicechanged);
}
this._onservicechanged = fn;
this.addEventListener("servicechanged", this._onservicechanged);
}
private _onserviceremoved: (ev: Event) => void;
public set onserviceremoved(fn: (ev: Event) => void) {
if (this._onserviceremoved) {
this.removeEventListener("serviceremoved", this._onserviceremoved);
}
this._onserviceremoved = fn;
this.addEventListener("serviceremoved", this._onserviceremoved);
}
private _ongattserverdisconnected: (ev: Event) => void;
public set ongattserverdisconnected(fn: (ev: Event) => void) {
if (this._ongattserverdisconnected) {
this.removeEventListener("gattserverdisconnected", this._ongattserverdisconnected);
}
this._ongattserverdisconnected = fn;
this.addEventListener("gattserverdisconnected", this._ongattserverdisconnected);
}
private _onadvertisementreceived: (ev: Event) => void;
public set onadvertisementreceived(fn: (ev: Event) => void) {
if (this._onadvertisementreceived) {
this.removeEventListener("advertisementreceived", this._onadvertisementreceived);
}
this._onadvertisementreceived = fn;
this.addEventListener("advertisementreceived", this._onadvertisementreceived);
}
private _onavailabilitychanged: (ev: Event) => void;
public set onavailabilitychanged(fn: (ev: Event) => void) {
if (this._onavailabilitychanged) {
this.removeEventListener("availabilitychanged", this._onavailabilitychanged);
}
this._onavailabilitychanged = fn;
this.addEventListener("availabilitychanged", this._onavailabilitychanged);
}
/**

@@ -131,11 +161,11 @@ * Bluetooth constructor

adapter.on(NobleAdapter.EVENT_ENABLED, value => {
this.dispatchEvent(Bluetooth.EVENT_AVAILABILITY, value);
adapter.on(NobleAdapter.EVENT_ENABLED, _value => {
this.dispatchEvent(new DOMEvent(this, "availabilitychanged"));
});
}
private filterDevice(options: RequestDeviceOptions, deviceInfo, validServices) {
private filterDevice(filters: Array<BluetoothRequestDeviceFilter>, deviceInfo, validServices) {
let valid = false;
options.filters.forEach(filter => {
filters.forEach(filter => {
// Name

@@ -185,11 +215,28 @@ if (filter.name && filter.name !== deviceInfo.name) return;

*/
public requestDevice(options?: RequestDeviceOptions): Promise<BluetoothDevice> {
public requestDevice(options: RequestDeviceOptions = { filters: [] }): Promise<BluetoothDevice> {
return new Promise((resolve, reject) => {
options = options || {};
if (this.scanner !== null) return reject("requestDevice error: request in progress");
if (!options.acceptAllDevices && !this.deviceFound) {
interface Filtered {
filters: Array<BluetoothRequestDeviceFilter>;
optionalServices?: Array<BluetoothServiceUUID>;
}
interface AcceptAll {
acceptAllDevices: boolean;
optionalServices?: Array<BluetoothServiceUUID>;
}
const isFiltered = (maybeFiltered: RequestDeviceOptions): maybeFiltered is Filtered =>
(maybeFiltered as Filtered).filters !== undefined;
const isAcceptAll = (maybeAcceptAll: RequestDeviceOptions): maybeAcceptAll is AcceptAll =>
(maybeAcceptAll as AcceptAll).acceptAllDevices === true;
let searchUUIDs = [];
if (isFiltered(options)) {
// Must have a filter
if (!options.filters || options.filters.length === 0) {
if (options.filters.length === 0) {
return reject(new TypeError("requestDevice error: no filters specified"));

@@ -213,17 +260,15 @@ }

}
}
let searchUUIDs = [];
if (options.filters) {
options.filters.forEach(filter => {
if (filter.services) searchUUIDs = searchUUIDs.concat(filter.services.map(getServiceUUID));
// Unique-ify
searchUUIDs = searchUUIDs.filter((item, index, array) => {
return array.indexOf(item) === index;
});
});
} else if (!isAcceptAll(options)) {
return reject(new TypeError("requestDevice error: specify filters or acceptAllDevices"));
}
// Unique-ify
searchUUIDs = searchUUIDs.filter((item, index, array) => {
return array.indexOf(item) === index;
});
let found = false;

@@ -241,4 +286,4 @@ adapter.startScan(searchUUIDs, deviceInfo => {

// filter devices if filters specified
if (options.filters) {
deviceInfo = this.filterDevice(options, deviceInfo, validServices);
if (isFiltered(options)) {
deviceInfo = this.filterDevice(options.filters, deviceInfo, validServices);
}

@@ -245,0 +290,0 @@

@@ -26,3 +26,3 @@ /*

import { EventDispatcher } from "./dispatcher";
import { EventDispatcher, TypedDispatcher } from "./dispatcher";
import { BluetoothRemoteGATTService } from "./service";

@@ -32,43 +32,13 @@ import { BluetoothRemoteGATTDescriptor } from "./descriptor";

import { adapter } from "./adapter";
import { W3CBluetoothRemoteGATTCharacteristic } from "./interfaces";
import { DOMEvent } from "./events";
/**
* Bluetooth Characteristic Properties interface
* @hidden
*/
export interface BluetoothCharacteristicProperties {
export interface BluetoothRemoteGATTCharacteristicEvents {
/**
* Broadcast property
* Characteristic value changed event
*/
broadcast: boolean;
/**
* Read property
*/
read: boolean;
/**
* Write without response property
*/
writeWithoutResponse: boolean;
/**
* Write property
*/
write: boolean;
/**
* Notify property
*/
notify: boolean;
/**
* Indicate property
*/
indicate: boolean;
/**
* Authenticated signed writes property
*/
authenticatedSignedWrites: boolean;
/**
* Reliable write property
*/
reliableWrite: boolean;
/**
* Writable auxiliaries property
*/
writableAuxiliaries: boolean;
characteristicvaluechanged: Event;
}

@@ -79,11 +49,5 @@

*/
export class BluetoothRemoteGATTCharacteristic extends EventDispatcher {
export class BluetoothRemoteGATTCharacteristic extends (EventDispatcher as new() => TypedDispatcher<BluetoothRemoteGATTCharacteristicEvents>) implements W3CBluetoothRemoteGATTCharacteristic {
/**
* Characteristic Value Changed event
* @event
*/
public static EVENT_CHANGED: string = "characteristicvaluechanged";
/**
* The service the characteristic is related to

@@ -114,2 +78,11 @@ */

private _oncharacteristicvaluechanged: (ev: Event) => void;
public set oncharacteristicvaluechanged(fn: (ev: Event) => void) {
if (this._oncharacteristicvaluechanged) {
this.removeEventListener("characteristicvaluechanged", this._oncharacteristicvaluechanged);
}
this._oncharacteristicvaluechanged = fn;
this.addEventListener("characteristicvaluechanged", this._oncharacteristicvaluechanged);
}
/**

@@ -133,6 +106,6 @@ * Characteristic constructor

if (emit) {
this.dispatchEvent(BluetoothRemoteGATTCharacteristic.EVENT_CHANGED, value);
this.service.dispatchEvent(BluetoothRemoteGATTCharacteristic.EVENT_CHANGED, value);
this.service.device.dispatchEvent(BluetoothRemoteGATTCharacteristic.EVENT_CHANGED, value);
this.service.device._bluetooth.dispatchEvent(BluetoothRemoteGATTCharacteristic.EVENT_CHANGED, value);
this.dispatchEvent(new DOMEvent(this, "characteristicvaluechanged"));
this.service.dispatchEvent(new DOMEvent(this, "characteristicvaluechanged"));
this.service.device.dispatchEvent(new DOMEvent(this, "characteristicvaluechanged"));
this.service.device._bluetooth.dispatchEvent(new DOMEvent(this, "characteristicvaluechanged"));
}

@@ -244,3 +217,3 @@ }

*/
public startNotifications(): Promise<BluetoothRemoteGATTCharacteristic> {
public startNotifications(): Promise<W3CBluetoothRemoteGATTCharacteristic> {
return new Promise((resolve, reject) => {

@@ -247,0 +220,0 @@ if (!this.service.device.gatt.connected) return reject("startNotifications error: device not connected");

@@ -26,4 +26,4 @@ /*

import { BluetoothRemoteGATTCharacteristic } from "./characteristic";
import { adapter } from "./adapter";
import { W3CBluetoothRemoteGATTDescriptor } from "./interfaces";

@@ -33,3 +33,3 @@ /**

*/
export class BluetoothRemoteGATTDescriptor {
export class BluetoothRemoteGATTDescriptor implements W3CBluetoothRemoteGATTDescriptor {

@@ -36,0 +36,0 @@ /**

@@ -26,23 +26,27 @@ /*

import { EventDispatcher } from "./dispatcher";
import { EventDispatcher, TypedDispatcher } from "./dispatcher";
import { Bluetooth } from "./bluetooth";
import { BluetoothRemoteGATTServer } from "./server";
import { BluetoothRemoteGATTServiceEvents } from "./service";
import { W3CBluetoothDevice } from "./interfaces";
/**
* Bluetooth Device class
* @hidden
*/
export class BluetoothDevice extends EventDispatcher {
export interface BluetoothDeviceEvents extends BluetoothRemoteGATTServiceEvents {
/**
* Server Disconnected event
* @event
* GATT server disconnected event
*/
public static EVENT_DISCONNECTED: string = "gattserverdisconnected";
gattserverdisconnected: Event;
/**
* Advertisement Received event
* @event
* Advertisement received event
*/
public static EVENT_ADVERT: string = "advertisementreceived";
advertisementreceived: Event;
}
/**
* Bluetooth Device class
*/
export class BluetoothDevice extends (EventDispatcher as new() => TypedDispatcher<BluetoothDeviceEvents>) implements W3CBluetoothDevice {
/**

@@ -93,2 +97,56 @@ * The unique identifier of the device

private _oncharacteristicvaluechanged: (ev: Event) => void;
public set oncharacteristicvaluechanged(fn: (ev: Event) => void) {
if (this._oncharacteristicvaluechanged) {
this.removeEventListener("characteristicvaluechanged", this._oncharacteristicvaluechanged);
}
this._oncharacteristicvaluechanged = fn;
this.addEventListener("characteristicvaluechanged", this._oncharacteristicvaluechanged);
}
private _onserviceadded: (ev: Event) => void;
public set onserviceadded(fn: (ev: Event) => void) {
if (this._onserviceadded) {
this.removeEventListener("serviceadded", this._onserviceadded);
}
this._onserviceadded = fn;
this.addEventListener("serviceadded", this._onserviceadded);
}
private _onservicechanged: (ev: Event) => void;
public set onservicechanged(fn: (ev: Event) => void) {
if (this._onservicechanged) {
this.removeEventListener("servicechanged", this._onservicechanged);
}
this._onservicechanged = fn;
this.addEventListener("servicechanged", this._onservicechanged);
}
private _onserviceremoved: (ev: Event) => void;
public set onserviceremoved(fn: (ev: Event) => void) {
if (this._onserviceremoved) {
this.removeEventListener("serviceremoved", this._onserviceremoved);
}
this._onserviceremoved = fn;
this.addEventListener("serviceremoved", this._onserviceremoved);
}
private _ongattserverdisconnected: (ev: Event) => void;
public set ongattserverdisconnected(fn: (ev: Event) => void) {
if (this._ongattserverdisconnected) {
this.removeEventListener("gattserverdisconnected", this._ongattserverdisconnected);
}
this._ongattserverdisconnected = fn;
this.addEventListener("gattserverdisconnected", this._ongattserverdisconnected);
}
private _onadvertisementreceived: (ev: Event) => void;
public set onadvertisementreceived(fn: (ev: Event) => void) {
if (this._onadvertisementreceived) {
this.removeEventListener("advertisementreceived", this._onadvertisementreceived);
}
this._onadvertisementreceived = fn;
this.addEventListener("advertisementreceived", this._onadvertisementreceived);
}
/**

@@ -95,0 +153,0 @@ * Device constructor

/*
* Node Web Bluetooth
* Copyright (c) 2017 Rob Moran
* Copyright (c) 2019 Rob Moran
*

@@ -28,24 +28,67 @@ * The MIT License (MIT)

// tslint:disable:ban-types
/**
* @hidden
*/
export class EventDispatcher extends EventEmitter {
export interface EventListeners<T> {
newListener: keyof T;
removeListener: keyof T;
}
// tslint:disable-next-line:array-type
public addEventListener(event: string | symbol, listener: (...args: any[]) => void) {
return super.addListener(event, listener);
/**
* @hidden
*/
export interface TypedDispatcher<T> {
addEventListener<K extends keyof T>(type: K, listener: (this: this, event: T[K]) => void): void;
addEventListener<E extends keyof EventListeners<T>>(type: E, listener: (this: this, event: EventListeners<T>[E]) => void): void;
removeEventListener<K extends keyof T>(type: K, callback: (this: this, event: T[K]) => void): void;
removeEventListener<E extends keyof EventListeners<T>>(type: E, callback: (this: this, event: EventListeners<T>[E]) => void): void;
dispatchEvent<K extends keyof T>(event: T[K]): boolean;
addListener<K extends keyof T>(event: K, listener: (data: T[K]) => void): this;
addListener<E extends keyof EventListeners<T>>(event: E, listener: (data: EventListeners<T>[E]) => void): this;
on<K extends keyof T>(event: K, listener: (data: T[K]) => void): this;
on<E extends keyof EventListeners<T>>(event: E, listener: (data: EventListeners<T>[E]) => void): this;
once<K extends keyof T>(event: K, listener: (data: T[K]) => void): this;
once<E extends keyof EventListeners<T>>(event: E, listener: (data: EventListeners<T>[E]) => void): this;
prependListener<K extends keyof T>(event: K, listener: (data: T[K]) => void): this;
prependOnceListener<K extends keyof T>(event: K, listener: (data: T[K]) => void): this;
removeListener<K extends keyof T>(event: K, listener: (data: T[K]) => void): this;
removeListener<E extends keyof EventListeners<T>>(event: E, listener: (data: EventListeners<T>[E]) => void): this;
removeAllListeners<K extends keyof T>(event?: K): this;
removeAllListeners<E extends keyof EventListeners<T>>(event?: E): this;
listeners<K extends keyof T>(event: K): Array<Function>;
listeners<E extends keyof EventListeners<T>>(event: EventListeners<T>[E]): Array<Function>;
emit<K extends keyof T>(event: K, data: T[K]): boolean;
eventNames<K extends keyof T, E extends keyof EventListeners<T>>(): Array<K | E>;
listenerCount<K extends keyof T>(type: K): number;
listenerCount<E extends keyof EventListeners<T>>(type: EventListeners<T>[E]): number;
setMaxListeners(n: number): this;
getMaxListeners(): number;
}
/**
* @hidden
*/
export class EventDispatcher extends EventEmitter implements EventTarget {
private isEventListenerObject = (listener: EventListenerOrEventListenerObject): listener is EventListenerObject => (listener as EventListenerObject).handleEvent !== undefined;
public addEventListener(type: string, listener: EventListenerOrEventListenerObject | null) {
if (listener) {
const handler = this.isEventListenerObject(listener) ? listener.handleEvent : listener;
super.addListener(type, handler);
}
}
// tslint:disable-next-line:array-type
public removeEventListener(event: string | symbol, listener: (...args: any[]) => void) {
return super.removeListener(event, listener);
public removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null) {
if (callback) {
const handler = this.isEventListenerObject(callback) ? callback.handleEvent : callback;
super.removeListener(type, handler);
}
}
public dispatchEvent(event: string | symbol, value?: any) {
return super.emit(event, {
type: event,
target: this,
value: value
});
public dispatchEvent(event: Event): boolean {
return super.emit(event.type, event);
}
}

@@ -26,3 +26,3 @@ /*

import { Bluetooth } from "./bluetooth";
import { Bluetooth, BluetoothOptions } from "./bluetooth";

@@ -35,18 +35,9 @@ /**

/**
* Helper methods and enums
*/
export * from "./helpers";
/**
* Bluetooth class for creating new instances
*/
export { Bluetooth };
export { Bluetooth, BluetoothOptions };
/**
* Other classes if required
* Helper methods and enums
*/
export { BluetoothDevice } from "./device";
export { BluetoothRemoteGATTServer } from "./server";
export { BluetoothRemoteGATTService } from "./service";
export { BluetoothRemoteGATTCharacteristic } from "./characteristic";
export { BluetoothRemoteGATTDescriptor } from "./descriptor";
export * from "./helpers";

@@ -27,5 +27,7 @@ /*

import { BluetoothDevice } from "./device";
import { BluetoothRemoteGATTService } from "./service";
import { getServiceUUID } from "./helpers";
import { adapter } from "./adapter";
import { W3CBluetoothRemoteGATTServer } from "./interfaces";
import { BluetoothRemoteGATTService } from "./service";
import { DOMEvent } from "./events";

@@ -35,3 +37,3 @@ /**

*/
export class BluetoothRemoteGATTServer {
export class BluetoothRemoteGATTServer implements W3CBluetoothRemoteGATTServer {

@@ -77,4 +79,4 @@ /**

this._connected = false;
this.device.dispatchEvent(BluetoothDevice.EVENT_DISCONNECTED);
this.device._bluetooth.dispatchEvent(BluetoothDevice.EVENT_DISCONNECTED);
this.device.dispatchEvent(new DOMEvent(this.device, "gattserverdisconnected"));
this.device._bluetooth.dispatchEvent(new DOMEvent(this.device, "gattserverdisconnected"));
}, error => {

@@ -81,0 +83,0 @@ reject(`connect Error: ${error}`);

@@ -26,31 +26,33 @@ /*

import { EventDispatcher } from "./dispatcher";
import { EventDispatcher, TypedDispatcher } from "./dispatcher";
import { BluetoothDevice } from "./device";
import { BluetoothRemoteGATTCharacteristic } from "./characteristic";
import { BluetoothRemoteGATTCharacteristic, BluetoothRemoteGATTCharacteristicEvents } from "./characteristic";
import { getCharacteristicUUID, getServiceUUID } from "./helpers";
import { adapter } from "./adapter";
import { W3CBluetoothRemoteGATTService } from "./interfaces";
import { DOMEvent } from "./events";
/**
* Bluetooth Remote GATT Service class
* @hidden
*/
export class BluetoothRemoteGATTService extends EventDispatcher {
export interface BluetoothRemoteGATTServiceEvents extends BluetoothRemoteGATTCharacteristicEvents {
/**
* Service Added event
* @event
* Service added event
*/
public static EVENT_ADDED: string = "serviceadded";
serviceadded: Event;
/**
* Service Changed event
* @event
* Service changed event
*/
public static EVENT_CHANGED: string = "servicechanged";
servicechanged: Event;
/**
* Service Removed event
* @event
* Service removed event
*/
public static EVENT_REMOVED: string = "serviceremoved";
serviceremoved: Event;
}
/**
* Bluetooth Remote GATT Service class
*/
export class BluetoothRemoteGATTService extends (EventDispatcher as new() => TypedDispatcher<BluetoothRemoteGATTServiceEvents>) implements W3CBluetoothRemoteGATTService {
/**

@@ -75,2 +77,38 @@ * The device the service is related to

private _oncharacteristicvaluechanged: (ev: Event) => void;
public set oncharacteristicvaluechanged(fn: (ev: Event) => void) {
if (this._oncharacteristicvaluechanged) {
this.removeEventListener("characteristicvaluechanged", this._oncharacteristicvaluechanged);
}
this._oncharacteristicvaluechanged = fn;
this.addEventListener("characteristicvaluechanged", this._oncharacteristicvaluechanged);
}
private _onserviceadded: (ev: Event) => void;
public set onserviceadded(fn: (ev: Event) => void) {
if (this._onserviceadded) {
this.removeEventListener("serviceadded", this._onserviceadded);
}
this._onserviceadded = fn;
this.addEventListener("serviceadded", this._onserviceadded);
}
private _onservicechanged: (ev: Event) => void;
public set onservicechanged(fn: (ev: Event) => void) {
if (this._onservicechanged) {
this.removeEventListener("servicechanged", this._onservicechanged);
}
this._onservicechanged = fn;
this.addEventListener("servicechanged", this._onservicechanged);
}
private _onserviceremoved: (ev: Event) => void;
public set onserviceremoved(fn: (ev: Event) => void) {
if (this._onserviceremoved) {
this.removeEventListener("serviceremoved", this._onserviceremoved);
}
this._onserviceremoved = fn;
this.addEventListener("serviceremoved", this._onserviceremoved);
}
/**

@@ -89,5 +127,5 @@ * Service constructor

this.dispatchEvent(BluetoothRemoteGATTService.EVENT_ADDED);
this.device.dispatchEvent(BluetoothRemoteGATTService.EVENT_ADDED);
this.device._bluetooth.dispatchEvent(BluetoothRemoteGATTService.EVENT_ADDED);
this.dispatchEvent(new DOMEvent(this, "serviceadded"));
this.device.dispatchEvent(new DOMEvent(this, "serviceadded"));
this.device._bluetooth.dispatchEvent(new DOMEvent(this, "serviceadded"));
}

@@ -94,0 +132,0 @@

/// <reference types="node" />
/// <reference types="web-bluetooth" />
import { EventEmitter } from "events";
import { BluetoothDevice } from "./device";
import { BluetoothRemoteGATTService } from "./service";
import { BluetoothRemoteGATTDescriptor } from "./descriptor";
import { BluetoothRemoteGATTCharacteristic } from "./characteristic";

@@ -42,3 +42,3 @@ /**

constructor();
private get state();
private readonly state;
private init;

@@ -45,0 +45,0 @@ private checkForError;

@@ -1,3 +0,5 @@

import { EventDispatcher } from "./dispatcher";
import { BluetoothDevice } from "./device";
/// <reference types="web-bluetooth" />
import { TypedDispatcher } from "./dispatcher";
import { BluetoothDevice, BluetoothDeviceEvents } from "./device";
import { W3CBluetooth } from "./interfaces";
/**

@@ -21,39 +23,15 @@ * Bluetooth Options interface

/**
* BluetoothLE Scan Filter Init interface
* @hidden
*/
export interface BluetoothLEScanFilterInit {
export interface BluetoothEvents extends BluetoothDeviceEvents {
/**
* An array of service UUIDs to filter on
* Bluetooth Availability Changed event
*/
services?: Array<string | number>;
/**
* The device name to filter on
*/
name?: string;
/**
* The device name prefix to filter on
*/
namePrefix?: string;
availabilitychanged: Event;
}
declare const Bluetooth_base: new () => TypedDispatcher<BluetoothEvents>;
/**
* Request Device Options interface
*/
export interface RequestDeviceOptions {
/**
* An array of device filters to match
*/
filters?: Array<BluetoothLEScanFilterInit>;
/**
* An array of optional services to have access to
*/
optionalServices?: Array<string | number>;
/**
* Whether to accept all devices
*/
acceptAllDevices?: boolean;
}
/**
* Bluetooth class
*/
export declare class Bluetooth extends EventDispatcher {
export declare class Bluetooth extends Bluetooth_base implements W3CBluetooth {
/**

@@ -71,2 +49,16 @@ * Bluetooth Availability Changed event

private scanner;
private _oncharacteristicvaluechanged;
oncharacteristicvaluechanged: (ev: Event) => void;
private _onserviceadded;
onserviceadded: (ev: Event) => void;
private _onservicechanged;
onservicechanged: (ev: Event) => void;
private _onserviceremoved;
onserviceremoved: (ev: Event) => void;
private _ongattserverdisconnected;
ongattserverdisconnected: (ev: Event) => void;
private _onadvertisementreceived;
onadvertisementreceived: (ev: Event) => void;
private _onavailabilitychanged;
onavailabilitychanged: (ev: Event) => void;
/**

@@ -94,1 +86,2 @@ * Bluetooth constructor

}
export {};

@@ -1,55 +0,21 @@

import { EventDispatcher } from "./dispatcher";
/// <reference types="web-bluetooth" />
import { TypedDispatcher } from "./dispatcher";
import { BluetoothRemoteGATTService } from "./service";
import { BluetoothRemoteGATTDescriptor } from "./descriptor";
import { W3CBluetoothRemoteGATTCharacteristic } from "./interfaces";
/**
* Bluetooth Characteristic Properties interface
* @hidden
*/
export interface BluetoothCharacteristicProperties {
export interface BluetoothRemoteGATTCharacteristicEvents {
/**
* Broadcast property
* Characteristic value changed event
*/
broadcast: boolean;
/**
* Read property
*/
read: boolean;
/**
* Write without response property
*/
writeWithoutResponse: boolean;
/**
* Write property
*/
write: boolean;
/**
* Notify property
*/
notify: boolean;
/**
* Indicate property
*/
indicate: boolean;
/**
* Authenticated signed writes property
*/
authenticatedSignedWrites: boolean;
/**
* Reliable write property
*/
reliableWrite: boolean;
/**
* Writable auxiliaries property
*/
writableAuxiliaries: boolean;
characteristicvaluechanged: Event;
}
declare const BluetoothRemoteGATTCharacteristic_base: new () => TypedDispatcher<BluetoothRemoteGATTCharacteristicEvents>;
/**
* Bluetooth Remote GATT Characteristic class
*/
export declare class BluetoothRemoteGATTCharacteristic extends EventDispatcher {
export declare class BluetoothRemoteGATTCharacteristic extends BluetoothRemoteGATTCharacteristic_base implements W3CBluetoothRemoteGATTCharacteristic {
/**
* Characteristic Value Changed event
* @event
*/
static EVENT_CHANGED: string;
/**
* The service the characteristic is related to

@@ -70,5 +36,7 @@ */

*/
get value(): DataView;
readonly value: DataView;
private handle;
private descriptors;
private _oncharacteristicvaluechanged;
oncharacteristicvaluechanged: (ev: Event) => void;
/**

@@ -106,3 +74,3 @@ * Characteristic constructor

*/
startNotifications(): Promise<BluetoothRemoteGATTCharacteristic>;
startNotifications(): Promise<W3CBluetoothRemoteGATTCharacteristic>;
/**

@@ -114,1 +82,2 @@ * Stop notifications of changes for the characteristic

}
export {};

@@ -1,6 +0,7 @@

import { BluetoothRemoteGATTCharacteristic } from "./characteristic";
/// <reference types="web-bluetooth" />
import { W3CBluetoothRemoteGATTDescriptor } from "./interfaces";
/**
* Bluetooth Remote GATT Descriptor class
*/
export declare class BluetoothRemoteGATTDescriptor {
export declare class BluetoothRemoteGATTDescriptor implements W3CBluetoothRemoteGATTDescriptor {
/**

@@ -18,3 +19,3 @@ * The characteristic the descriptor is related to

*/
get value(): DataView;
readonly value: DataView;
private handle;

@@ -21,0 +22,0 @@ /**

@@ -1,18 +0,24 @@

import { EventDispatcher } from "./dispatcher";
import { TypedDispatcher } from "./dispatcher";
import { Bluetooth } from "./bluetooth";
import { BluetoothRemoteGATTServer } from "./server";
import { BluetoothRemoteGATTServiceEvents } from "./service";
import { W3CBluetoothDevice } from "./interfaces";
/**
* Bluetooth Device class
* @hidden
*/
export declare class BluetoothDevice extends EventDispatcher {
export interface BluetoothDeviceEvents extends BluetoothRemoteGATTServiceEvents {
/**
* Server Disconnected event
* @event
* GATT server disconnected event
*/
static EVENT_DISCONNECTED: string;
gattserverdisconnected: Event;
/**
* Advertisement Received event
* @event
* Advertisement received event
*/
static EVENT_ADVERT: string;
advertisementreceived: Event;
}
declare const BluetoothDevice_base: new () => TypedDispatcher<BluetoothDeviceEvents>;
/**
* Bluetooth Device class
*/
export declare class BluetoothDevice extends BluetoothDevice_base implements W3CBluetoothDevice {
/**

@@ -55,2 +61,14 @@ * The unique identifier of the device

readonly _serviceUUIDs: Array<string>;
private _oncharacteristicvaluechanged;
oncharacteristicvaluechanged: (ev: Event) => void;
private _onserviceadded;
onserviceadded: (ev: Event) => void;
private _onservicechanged;
onservicechanged: (ev: Event) => void;
private _onserviceremoved;
onserviceremoved: (ev: Event) => void;
private _ongattserverdisconnected;
ongattserverdisconnected: (ev: Event) => void;
private _onadvertisementreceived;
onadvertisementreceived: (ev: Event) => void;
/**

@@ -68,3 +86,4 @@ * Device constructor

*/
unwatchAdvertisements(): Promise<unknown>;
unwatchAdvertisements(): Promise<{}>;
}
export {};

@@ -6,6 +6,44 @@ /// <reference types="node" />

*/
export declare class EventDispatcher extends EventEmitter {
addEventListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeEventListener(event: string | symbol, listener: (...args: any[]) => void): this;
dispatchEvent(event: string | symbol, value?: any): boolean;
export interface EventListeners<T> {
newListener: keyof T;
removeListener: keyof T;
}
/**
* @hidden
*/
export interface TypedDispatcher<T> {
addEventListener<K extends keyof T>(type: K, listener: (this: this, event: T[K]) => void): void;
addEventListener<E extends keyof EventListeners<T>>(type: E, listener: (this: this, event: EventListeners<T>[E]) => void): void;
removeEventListener<K extends keyof T>(type: K, callback: (this: this, event: T[K]) => void): void;
removeEventListener<E extends keyof EventListeners<T>>(type: E, callback: (this: this, event: EventListeners<T>[E]) => void): void;
dispatchEvent<K extends keyof T>(event: T[K]): boolean;
addListener<K extends keyof T>(event: K, listener: (data: T[K]) => void): this;
addListener<E extends keyof EventListeners<T>>(event: E, listener: (data: EventListeners<T>[E]) => void): this;
on<K extends keyof T>(event: K, listener: (data: T[K]) => void): this;
on<E extends keyof EventListeners<T>>(event: E, listener: (data: EventListeners<T>[E]) => void): this;
once<K extends keyof T>(event: K, listener: (data: T[K]) => void): this;
once<E extends keyof EventListeners<T>>(event: E, listener: (data: EventListeners<T>[E]) => void): this;
prependListener<K extends keyof T>(event: K, listener: (data: T[K]) => void): this;
prependOnceListener<K extends keyof T>(event: K, listener: (data: T[K]) => void): this;
removeListener<K extends keyof T>(event: K, listener: (data: T[K]) => void): this;
removeListener<E extends keyof EventListeners<T>>(event: E, listener: (data: EventListeners<T>[E]) => void): this;
removeAllListeners<K extends keyof T>(event?: K): this;
removeAllListeners<E extends keyof EventListeners<T>>(event?: E): this;
listeners<K extends keyof T>(event: K): Array<Function>;
listeners<E extends keyof EventListeners<T>>(event: EventListeners<T>[E]): Array<Function>;
emit<K extends keyof T>(event: K, data: T[K]): boolean;
eventNames<K extends keyof T, E extends keyof EventListeners<T>>(): Array<K | E>;
listenerCount<K extends keyof T>(type: K): number;
listenerCount<E extends keyof EventListeners<T>>(type: EventListeners<T>[E]): number;
setMaxListeners(n: number): this;
getMaxListeners(): number;
}
/**
* @hidden
*/
export declare class EventDispatcher extends EventEmitter implements EventTarget {
private isEventListenerObject;
addEventListener(type: string, listener: EventListenerOrEventListenerObject | null): void;
removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null): void;
dispatchEvent(event: Event): boolean;
}

@@ -1,2 +0,2 @@

import { Bluetooth } from "./bluetooth";
import { Bluetooth, BluetoothOptions } from "./bluetooth";
/**

@@ -7,16 +7,8 @@ * Default bluetooth instance synonymous with `navigator.bluetooth`

/**
* Helper methods and enums
*/
export * from "./helpers";
/**
* Bluetooth class for creating new instances
*/
export { Bluetooth };
export { Bluetooth, BluetoothOptions };
/**
* Other classes if required
* Helper methods and enums
*/
export { BluetoothDevice } from "./device";
export { BluetoothRemoteGATTServer } from "./server";
export { BluetoothRemoteGATTService } from "./service";
export { BluetoothRemoteGATTCharacteristic } from "./characteristic";
export { BluetoothRemoteGATTDescriptor } from "./descriptor";
export * from "./helpers";
import { BluetoothDevice } from "./device";
import { W3CBluetoothRemoteGATTServer } from "./interfaces";
import { BluetoothRemoteGATTService } from "./service";

@@ -6,3 +7,3 @@ /**

*/
export declare class BluetoothRemoteGATTServer {
export declare class BluetoothRemoteGATTServer implements W3CBluetoothRemoteGATTServer {
/**

@@ -16,3 +17,3 @@ * The device the gatt server is related to

*/
get connected(): boolean;
readonly connected: boolean;
private handle;

@@ -19,0 +20,0 @@ private services;

@@ -1,23 +0,27 @@

import { EventDispatcher } from "./dispatcher";
import { TypedDispatcher } from "./dispatcher";
import { BluetoothDevice } from "./device";
import { BluetoothRemoteGATTCharacteristic } from "./characteristic";
import { BluetoothRemoteGATTCharacteristic, BluetoothRemoteGATTCharacteristicEvents } from "./characteristic";
import { W3CBluetoothRemoteGATTService } from "./interfaces";
/**
* Bluetooth Remote GATT Service class
* @hidden
*/
export declare class BluetoothRemoteGATTService extends EventDispatcher {
export interface BluetoothRemoteGATTServiceEvents extends BluetoothRemoteGATTCharacteristicEvents {
/**
* Service Added event
* @event
* Service added event
*/
static EVENT_ADDED: string;
serviceadded: Event;
/**
* Service Changed event
* @event
* Service changed event
*/
static EVENT_CHANGED: string;
servicechanged: Event;
/**
* Service Removed event
* @event
* Service removed event
*/
static EVENT_REMOVED: string;
serviceremoved: Event;
}
declare const BluetoothRemoteGATTService_base: new () => TypedDispatcher<BluetoothRemoteGATTServiceEvents>;
/**
* Bluetooth Remote GATT Service class
*/
export declare class BluetoothRemoteGATTService extends BluetoothRemoteGATTService_base implements W3CBluetoothRemoteGATTService {
/**

@@ -38,2 +42,10 @@ * The device the service is related to

private characteristics;
private _oncharacteristicvaluechanged;
oncharacteristicvaluechanged: (ev: Event) => void;
private _onserviceadded;
onserviceadded: (ev: Event) => void;
private _onservicechanged;
onservicechanged: (ev: Event) => void;
private _onserviceremoved;
onserviceremoved: (ev: Event) => void;
/**

@@ -69,1 +81,2 @@ * Service constructor

}
export {};

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc