赞
踩
首先参考 通过 Web 控制蓝牙设备:WebBluetooth入门。
www/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Web Bluetooth</title>
<script src="js/web-bluetooth.js"></script>
</head>
<body>
<button onclick="sendAndReceive()">Send And Receive!</button>
</body>
navigator.bluetooth.requestDevice
必须在某个用户触发的回调内执行,例如在 button
元素的 onclick
事件中调用。在其它环境下调用将产生错误,比如在 $(document).ready 回调中执行就会报告错误:
Must be handling a user gesture to show a permission request
www/js/web-bluetooth.js
async function sendAndReceive() { let device = await navigator.bluetooth.requestDevice({ filters: [ {services: [0xffe0]}, ] }); let server = await device.gatt.connect(); let service = await server.getPrimaryService(0xffe0); let characteristic = await service.getCharacteristic(0xffe1); characteristic.addEventListener( 'characteristicvaluechanged', e => { console.log(e.target.value); } ); characteristic.startNotifications(); await characteristic.writeValue( new Uint8Array([50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]) ); }
getPrimaryService
的参数,那么可以首先用 getPrimaryServices
函数获取服务的 uuid,注意这个函数后面有个s字母。getPrimaryServices
返回一个服务数组,每个数组元素有 uuid 属性。可以这样操作:server.getPrimaryService(server.getPrimaryServices()[0].uuid)
。getCharacteristic
也一样,可以用 getCharacteristics
函数获取特性的 uuid,注意s字母。characteristic.readValue()
读取的数据不对,一定要用 characteristic.addEventListener( 'characteristicvaluechanged'
的办法。httpd.js
#!/usr/bin/env node const port = 8089; const express = require('express'); var app = express(); app.use(express.static(__dirname + '/www')); var https = require('https'); var fs = require('fs'); var options = { key:fs.readFileSync('./keys/server.key'), cert:fs.readFileSync('./keys/server.crt') } var httpsServer = https.createServer(options, app); httpsServer.listen(port); console.log('listening https://localhost:' + port);
MDN 上说 Web Bluetooth 只能用在 HTTPS :
This feature is available only in secure contexts (HTTPS)
用 Chrome 87 实测,如果访问的是 localhost 或 127.0.0.1,那么 HTTP 也是可以的,如果是其它地址,那么必须要用 HTTPS,否则会报告错误:
TypeError: Cannot read property ‘requestDevice’ of undefined
HTTPS 服务需要证书,用下面的脚本生成自签名证书:
keys/gen-crt.sh
#!/bin/sh # https://www.cnblogs.com/whm-blog/p/9413958.html # 生成服务器端私钥 openssl genrsa -out server.key 1024 # 生成服务端公钥 openssl rsa -in server.key -pubout -out server.pem # 生成CA私钥 openssl genrsa -out ca.key 1024 # 生成csr文件 openssl req -new -key ca.key -out ca.csr # 生成自签名证书 openssl x509 -req -in ca.csr -signkey ca.key -out ca.crt # 生成server.csr文件 openssl req -new -key server.key -out server.csr # 生成带有ca签名的证书 openssl x509 -req -CA ca.crt -CAkey ca.key -CAcreateserial -in server.csr -out server.crt
HTTPS 服务的建立参考 node.js express 启用 https 。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。