Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///////////////////////////////////////////////////////////////
- /* Polyfill for Web Bluetooth */
- (function(navigator) {
- 'use strict';
- let allowedDevices = [
- { id: '1', name: 'Device A', connectGATT: function() { return new Promise((resolve, reject) => { reject(); }) } },
- { id: '2', name: 'Device B', connectGATT: function() { return new Promise((resolve, reject) => { reject(); }) } },
- { id: '3', name: 'Device C', connectGATT: function() { return new Promise((resolve, reject) => { resolve(); }) } },
- ];
- navigator.bluetooth.getAllowedDevices = function() {
- return new Promise((resolve, reject) => {
- resolve(allowedDevices);
- });
- }
- navigator.bluetooth.referringDevice = allowedDevices[0];
- })(navigator);
- ///////////////////////////////////////////////////////////////
- var button = document.createElement('button');
- var index = 0;
- var allowedDevices = null;
- // Get all bluetooth allowed devices first.
- navigator.bluetooth.getDevices()
- .then(devices => {
- // Cache all bluetooth allowed devices.
- allowedDevices = devices;
- if (navigator.bluetooth.referringDevice) {
- // Device is coming from Physical Web... let's connect to it now.
- // This assumes this device is the first one in allowedDevices.
- connect(navigator.bluetooth.referringDevice, true);
- } else if (allowedDevices.length > 0) {
- // If website already interacted with bluetooth devices, let's try to connect to them.
- connect(allowedDevices[index], true);
- } else {
- // Show "Scan for devices" button.
- showScanButton();
- }
- })
- .catch(error => {
- // Show "Scan for devices" button.
- showScanButton();
- });
- function connect(bluetoothDevice, toContinue) {
- bluetoothDevice.connectGATT()
- .then(server => {
- // Interact with bluetooth device.
- })
- .catch(error => {
- if (toContinue && ++index < allowedDevices.length) {
- // Try to connect to the next allowed device.
- var nextDevice = allowedDevices[index];
- connect(nextDevice, true);
- } else {
- // Show "scan for devices" button.
- showScanButton();
- }
- })
- }
- function showScanButton() {
- button.style.display = 'block';
- button.addEventListener('click', () => {
- // Start bluetooth discovery session
- var options = { filters: [ { services: [ 'battery_service' ] } ] };
- navigator.bluetooth.requestDevice(options)
- .then(device => {
- connect(device, false);
- })
- .catch(error => {
- console.log(error);
- });
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement