UNPKG

react-bluetooth

Version:
89 lines 3.27 kB
import invariant from 'invariant'; export var BluetoothEvent; (function (BluetoothEvent) { BluetoothEvent["onAvailabilityChanged"] = "onavailabilitychanged"; BluetoothEvent["onGATTServerDisconnected"] = "ongattserverdisconnected"; BluetoothEvent["onCharacteristicValueChanged"] = "oncharacteristicvaluechanged"; BluetoothEvent["onServiceAdded"] = "onserviceadded"; BluetoothEvent["onServiceChanged"] = "onservicechanged"; BluetoothEvent["onServiceRemoved"] = "onserviceremoved"; })(BluetoothEvent || (BluetoothEvent = {})); let platformListeners = {}; export const isCapable = 'bluetooth' in navigator; /* TODO: Bacon: Web: This will show a modal and allow you to select one. We may need to build a custom component to do this on native. */ export async function requestDeviceAsync(options = { acceptAllDevices: true }) { try { const device = await platformModule().requestDevice(options); return { type: 'success', device }; } catch (error) { if (error.code === 8) { // User Cancelled return { type: 'cancel' }; } throw error; } } export async function getAvailabilityAsync() { const bluetooth = platformModule(); if (bluetooth.getAvailability) { return await platformModule().getAvailability(); } else { return !!bluetooth; } } export function getReferringDevice() { return platformModule().referringDevice; } export function addPlatformHandler(eventName, handler) { if (!(eventName in platformListeners)) { platformListeners[eventName] = []; } platformListeners[eventName].push(handler); return { remove() { const index = platformListeners[eventName].indexOf(handler); if (index !== -1) { platformListeners[eventName].splice(index, 1); } }, }; } /* In theory these event listeners shouldn't matter */ // type: 'availabilitychanged' export function addEventListener(listener, useCapture) { platformModule().addEventListener('availabilitychanged', listener, useCapture); } export function dispatchEvent(event) { return platformModule().dispatchEvent(event); } export function removeEventListener(callback, options) { platformModule().removeEventListener('availabilitychanged', callback, options); } function platformModule() { const _navigator = navigator; invariant(_navigator.bluetooth, 'This device is not capable of using Bluetooth'); return _navigator.bluetooth; } function _setupHandlers() { const events = [ BluetoothEvent.onAvailabilityChanged, BluetoothEvent.onGATTServerDisconnected, BluetoothEvent.onCharacteristicValueChanged, BluetoothEvent.onServiceAdded, BluetoothEvent.onServiceChanged, BluetoothEvent.onServiceRemoved, ]; for (const eventName of events) { /* This could be messy if the developer redefines these values */ platformModule()[eventName] = (...event) => { const subscriptions = platformListeners[eventName]; for (const subscription of subscriptions) { subscription(...event); } }; } } _setupHandlers(); //# sourceMappingURL=Bluetooth.js.map