【问题标题】:Bluetooth device get disconnected when navigating to other pages导航到其他页面时蓝牙设备断开连接
【发布时间】:2021-03-19 01:43:20
【问题描述】:

我正在创建一个网络应用程序,其中需要在所有网页中配对网络蓝牙。我能够在 index.html 页面上配对设备,但是当导航到其他页面时,蓝牙连接断开。有没有办法再次使用相同的配对设备而无需重新连接? 我正在使用以下示例连接到设备 https://googlechrome.github.io/samples/web-bluetooth/automatic-reconnect.html

代码:

<ul><a href="page1.html">page1</a></ul>
<ul><a href="page2.html">page2</a></ul>
<ul><a href="page3.html">page3</a></ul>

<form>
    <button>Scan</button>
</form>
<h3>Live Output</h3>
<div id="output" class="output">
    <div id="content"></div>
    <div id="status"></div>
    <pre id="log"></pre>
</div>

<script>
    var bluetoothDevice;

    var ChromeSamples = {
        log: function() {
            var line = Array.prototype.slice.call(arguments).map(function(argument) {
                return typeof argument === 'string' ? argument : JSON.stringify(argument);
            }).join(' ');

            document.querySelector('#log').textContent += line + '\n';
        },

        clearLog: function() {
            document.querySelector('#log').textContent = '';
        },

        setStatus: function(status) {
            document.querySelector('#status').textContent = status;
        },

        setContent: function(newContent) {
            var content = document.querySelector('#content');
            while(content.hasChildNodes()) {
                content.removeChild(content.lastChild);
            }
            content.appendChild(newContent);
        }
    };

    function onButtonClick() {
        bluetoothDevice = null;
        log('Requesting any Bluetooth Device...');
        navigator.bluetooth.requestDevice({
            // filters: [...] <- Prefer filters to save energy & show relevant devices.
            acceptAllDevices: true})
        .then(device => {
            bluetoothDevice = device;
            sessionStorage.lastDevice = device.id;

            console.log(bluetoothDevice);
            log(bluetoothDevice.id);
            log(bluetoothDevice.name);
            bluetoothDevice.addEventListener('gattserverdisconnected', onDisconnected);
            connect();
        })
        .catch(error => {
            log('Argh! ' + error);
        });
    }

    function connect() {
        exponentialBackoff(3 /* max retries */, 2 /* seconds delay */,
            function toTry() {
            time('Connecting to Bluetooth Device... ');
            return bluetoothDevice.gatt.connect();
            },
            function success() {
            log('> Bluetooth Device connected. Try disconnect it now.');
            },
            function fail() {
            time('Failed to reconnect.');
            });
    }

    function onDisconnected() {
        log('> Bluetooth Device disconnected');
        connect();
    }

    // if (sessionStorage) {
    //     navigator.permissions.query({
    //         name: "bluetooth",
    //         deviceId: sessionStorage.lastDevice,
    //     }).then(result => {
    //         if (result.devices.length == 1) {
    //             log(result.devices[0].id);
    //             log(result.devices[0].name);
    //             return result.devices[0];
    //         } else {
    //             throw new DOMException("Lost permission", "NotFoundError");
    //         }
    //     })
    // }

    /* Utils */

    // This function keeps calling "toTry" until promise resolves or has
    // retried "max" number of times. First retry has a delay of "delay" seconds.
    // "success" is called upon success.
    function exponentialBackoff(max, delay, toTry, success, fail) {
        toTry().then(result => success(result))
        .catch(_ => {
            if (max === 0) {
            return fail();
            }
            time('Retrying in ' + delay + 's... (' + max + ' tries left)');
            setTimeout(function() {
            exponentialBackoff(--max, delay * 2, toTry, success, fail);
            }, delay * 1000);
        });
    }

    function time(text) {
        log('[' + new Date().toJSON().substr(11, 8) + '] ' + text);
    }

    document.querySelector('button').addEventListener('click', function(event) {
        event.stopPropagation();
        event.preventDefault();

        if (isWebBluetoothEnabled()) {
        ChromeSamples.clearLog();
        onButtonClick();
        }
    });
    
    log = ChromeSamples.log;

    function isWebBluetoothEnabled() {
        if (navigator.bluetooth) {
        return true;
        } else {
        ChromeSamples.setStatus('Web Bluetooth API is not available.\n' +
            'Please make sure the "Experimental Web Platform features" flag is enabled.');
        return false;
        }
    }
</script>

【问题讨论】:

  • 请试着解释一下你做了什么。并想出一些代码。
  • @Abilogos 添加了代码示例。

标签: javascript bluetooth webapi web-bluetooth


【解决方案1】:

Chrome 当前的网络蓝牙实现无法让网站获取允许的设备列表。 WIP getDevices() 将返回一个蓝牙设备对象列表,当前源已被授予用户使用权限,以便您可以重新连接到它们。

https://www.chromestatus.com/feature/4797798639730688

下面是一些示例代码,您可以在今天启用 chrome://flags 中的 experimental-web-platform-features 标志来尝试一下。

navigator.bluetooth.getDevices()
.then(devices => {
  console.log('> Got ' + devices.length + ' Bluetooth devices.');
  for (const device of devices) {
    console.log('  > ' + device.name + ' (' + device.id + ')');
  }
})
.catch(error => {
  console.log('Argh! ' + error);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-18
    • 2016-01-30
    • 2018-01-20
    • 1970-01-01
    • 2012-10-22
    • 2012-11-14
    • 1970-01-01
    • 2021-05-21
    相关资源
    最近更新 更多