java怎么与蓝⽛交互数据_使⽤Web蓝⽛API与蓝⽛设备进⾏交
互
java怎么与蓝⽛交互数据
TL; DR: 或查看⽰例React应⽤程序: : 。
If you have smart home devices, you’ve likely interacted with them over Bluetooth from a native app on your phone. Did you know that you can also interact with Bluetooth devices through a website? You can using the Web Bluetooth API.
如果您有智能家居设备,则可能已经通过⼿机上的本机应⽤程序通过蓝⽛与它们进⾏了交互。 您知道您还可以通过⽹站与蓝⽛设备进⾏交互吗? 您可以使⽤Web Bluetooth API。
Getting a device’s battery level with the Web Bluetooth API
使⽤Web Bluetooth API获取设备的电池电量
Although this API is still considered experimental technology, . Some of the things you can do with the Web Bluetooth API include:
尽管此API仍被认为是实验性技术, 。 您可以使⽤Web Bluetooth API进⾏的⼀些操作包括:
Requesting and connecting to nearby devices
请求并连接到附近的设备
Reading and writing Bluetooth characteristics
读写蓝⽛特性
Receiving GATT notifications
接收关贸总协定通知
Receiving notifications when a device is disconnected
断开设备时接收通知
Reading and writing Bluetooth descriptors
读写蓝⽛描述符
If you’re new to how Bluetooth devices work, I’ll explain some of the concepts above. Otherwise, .
如果您不了解蓝⽛设备的⼯作原理,那么我将解释上⾯的⼀些概念。 否则,请 。
蓝⽛关键概念 (Bluetooth Key Concepts)
Here are a few key concepts you’re likely to come across as you start working with the Web Bluetooth API.
在开始使⽤Web Bluetooth API时,可能会遇到⼀些关键概念。
GATT(通⽤属性配置⽂件) (GATT (Generic Attribute Profile))
GATT plays an integral role in defining how data is shared over a Bluetooth connection. It describes the data transfer processes and formats. Even more important, it provides a reference framework that’s used for all devices with GATT-based profiles to ensure that devices from different vendors work together.
GATT在定义如何通过蓝⽛连接共享数据⽅⾯起着不可或缺的作⽤。 它描述了数据传输过程和格式。 更重要的是,它提供了⼀个参考框架,该框架可⽤于具有基于GATT的配置⽂件的所有设备,以确保来⾃不同供应商的设备可以协同⼯作。
GATT客户端与服务器 (GATT Client vs. Server)
The GATT client sends requests to a Bluetooth device and gets responses from it. In our case, the GATT client is a web browser that supports the Web Bluetooth API.
GATT客户端将请求发送到蓝⽛设备,并从中获取响应。 在我们的例⼦中,GATT客户端是⽀持Web蓝⽛API的Web浏览器。
The GATT server gets requests from a client and returns data. It can also be configured to send data on its own without receiving a request from a client. Bluetooth devices generally serve this role.
GATT服务器从客户端获取请求并返回数据。 还可以将其配置为⾃⾏发送数据,⽽不接收来⾃客户端的请求。 蓝⽛设备通常扮演这个⾓⾊。
共享资料 (Sharing Data)
When sharing data between Bluetooth devices, GATT organizes the data into characteristics, services, and descriptors.
在蓝⽛设备之间共享数据时,GATT会将数据组织为特征,服务和描述符 。
CharacteristicsCharacteristics hold user data and have at least two attributes:
特征特征保存⽤户数据,并⾄少具有两个属性:
Characteristic name
特征名称
Describes what the characteristic is, such as battery level or heart rate
描述特征是什么,例如电池电量或⼼率
The value for that characteristic
该特性的价值
ServicesGATT services are collections of related characteristics. For example, you could have a service called “Battery”that includes characteristics like the current battery level and the estimated amount of time remaining before the battery needs recharging.
服务 GATT服务是相关特征的集合。 例如,您可能有⼀项名为“电池”的服务,其中包括诸如当前电池电量以及电池需要充电之前估计的剩余时间之类的特征。
DescriptorsDescriptors are defined attributes that describe a characteristic value. They can be used to provide information that makes it easier to understand what a characteristic’s value represents. For example, a descriptor could explain the expected range for a value or a unit of measure being used for a value.
描述符描述符是定义的描述特性值的属性。 它们可⽤于提供信息,使您更容易理解特征值代表什么。 例如,描述符可以解释值的预期范围或⽤于该值的度量单位。
关贸总协定通知 (GATT Notifications)
GATT notifications let a website or application know when a particular characteristic changes on a device. For example, a web page that displays the battery level for a Bluetooth device could subscribe to notifications that indicate changes in the paired device’s battery level.
GATT通知可让⽹站或应⽤程序知道设备上的特定特征何时发⽣变化。 例如,显⽰蓝⽛设备电池电量的⽹页可以订阅通知,该通知指⽰配对设备电池电量的变化。
安全防护 (Security Protections)
In order to use the Web Bluetooth API, there are a few requirements to protect the privacy of users:
为了使⽤Web Bluetooth API,有⼀些要求可以保护⽤户的隐私:
The web page must be hosted with HTTPS
该⽹页必须使⽤HTTPS托管
You can interact with the API on
您可以在
The user has to make a gesture of some sort (click, touch, etc.) in order for the web page to discover Bluetooth devices
⽤户必须做出某种⼿势(单击,触摸等)才能使⽹页发现蓝⽛设备
从浏览器连接到蓝⽛设备 (Connecting to a Bluetooth Device from the Browser)
Now that you have some background information on how Bluetooth devices communicate with each other, let’s build something!
现在您已经掌握了蓝⽛设备之间如何通信的⼀些背景信息,让我们来构建⼀些东西!
For this example, let’s write some JavaScript that gets a device’s battery level using the Web Bluetooth API and displays it on a web page.
对于此⽰例,让我们编写⼀些JavaScript,这些JavaScript使⽤Web Bluetooth API获取设备的电池电量并将其显⽰在⽹页上。
A Note on TestingOnly devices that actively advertise a battery service will appear in the list of devices the browser can pair with for this example. I found that my Galaxy S9+ on it’s own doesn’t seem to advertise the battery service, so I used a simulator to test. An easy way to try this is to use a BLE simulator like (Android) or (Apple).
关于测试的注意事项在此⽰例中,浏览器可以配对的设备列表中仅显⽰正在积极宣传电池服务的设备。 我发现⾃⼰的Galaxy S9 +似乎并没有宣传电池服务,因此我使⽤模拟器进⾏了测试。 ⼀种简单的尝试⽅法是使⽤BLE模拟器,例如 (Android)或 (Apple)。
The CodeTo get started, create an asynchronous function that will search for Bluetooth devices and connect to the one selected.
代码要开始使⽤,请创建⼀个异步功能,该功能将搜索Bluetooth设备并连接到选定的设备。
const connectToDeviceAndSubscribeToUpdates = async () => {}
Inside the function, let’s start by requesting devices that advertise a battery service. The questDevice function takes an options object where you can specify what type of devices to scan for. In our case, we want to scan for devices that advertise their battery service, so that we can get the device’s battery level.
在该函数内部,让我们从请求宣传电池服务的设备开始。 questDevice函数采⽤⼀个options对象,您可以在其中指定要扫描的设备类型。 在本例中,我们要扫描宣传其电池服务的设备,以便获得设备的电池电量。
const connectToDeviceAndSubscribeToUpdates = async () => { const device = await navigator.bluetooth
.requestDevice({
filters: [{ services: ['battery_service']}
});
};
There are lots of other ways to filter devices, including by device name, service UUID (handy when you make your own GATT Server on a Bluetooth peripheral like a Raspberry Pi), or 16-bit service ID. You can also use multiple filters of the same or different types to filter the devices available for pairing. and try using different filters to get data from your devices.
还有许多其他过滤设备的⽅法,包括按设备名称,服务UUID(在Raspberry Pi等Bluetooth外围设备上制作⾃⼰的GATT服务器时很⽅便)或16位服务ID。 您也可以使⽤相同或不同类型的多个过滤器来过滤可⽤于配对的设备。 然后尝试使⽤其他过滤器从设备中获取数据。
Next, add an HTML button element to your web page and set its onClick function to call the connectToDeviceAndSubscribeToUpdates function. To pair with a Bluetooth device from the browser, you have to have a way for the user to initiate the action such as by clicking on a button.
接下来,将HTML按钮元素添加到您的⽹页,并将其onClick函数设置为调⽤connectToDeviceAndSubscribeToUpdates函数。 要从浏览器与蓝⽛设备配对,您必须有⼀种⽅法让⽤户启动操作,例如通过单击按钮。
<button onClick="connectToDeviceAndSubscribeToUpdates()">Connect to Bluetooth device</button>
Clicking on the button and calling the questDevice function triggers the browser to show a popup that lists the devices that meet the specified filters.
单击该按钮并调⽤questDevice函数将触发浏览器以显⽰弹出窗⼝,该弹出窗⼝列出符合指定过滤器的设备。
Popup showing devices that meet our filter requirements
弹出窗⼝显⽰符合我们过滤器要求的设备
At this point, you can select a device from the list and pair it with the browser. Nothing will happen yet though. We need to try to connect to the GATT server that’s running on the Bluetooth device.
此时,您可以从列表中选择设备并将其与浏览器配对。 不过什么都不会发⽣。 我们需要尝试连接到在蓝⽛设备上运⾏的GATT服务器。
const connectToDeviceAndSubscribeToUpdates = async () => {
const device = await navigator.bluetooth
.requestDevice({
filters: [{ services: ['battery_service']}
}); const server = await t();
};
After we’re connected to the GATT server, we need to get the battery service from the server.
连接到GATT服务器后,我们需要从服务器获取电池服务。
const connectToDeviceAndSubscribeToUpdates = async () => {
const device = await navigator.bluetooth
.requestDevice({
filters: [{ services: ['battery_service']}
}); const server = await t(); const service = PrimaryService('battery_service');
};
With the service now available, we can get the battery level characteristic from the device.
使⽤现在可⽤的服务,我们可以从设备获取电池电量特性。
const connectToDeviceAndSubscribeToUpdates = async () => {
const device = await navigator.bluetooth
.requestDevice({
filters: [{ services: ['battery_service']}
}); const server = await t(); const service = PrimaryService('battery_service'); const characteristic = Ch };
At this point, we have what we need to be able to get the battery level for the device. To do that, we use the readValue
function on the characteristic. The value is a DataView of an ArrayBuffer, so we use the getUint8 function to get an individual
byte from the array at the index passed in, which is 0 in our case.
⾄此,我们已经具备了获取设备电池电量所需的条件。 为此,我们在特征上使⽤readValue函数。 该值是ArrayBuffer的DataView,因此
我们使⽤getUint8函数从传⼊的索引处的数组中获取单个字节,在本例中为0 。
const connectToDeviceAndSubscribeToUpdates = async () => {
const device = await navigator.bluetooth
.requestDevice({
filters: [{ services: ['battery_service']}
}); const server = await t(); const service = PrimaryService('battery_service'); const characteristic = Ch console.Uint8(0) + '%');};
The function above will now get the battery level reading from the paired device and log it to the browser’s console.
现在,上述功能将从配对的设备获取电池电量读数,并将其记录到浏览器的控制台中。
This is great, but so far our code will only get a reading one time, right after the device connects. We can subscribe to
updates (aka GATT notifications) by calling the startNotifications function on the characteristic. Adding an event handler for
write的返回值the characteristicvaluechanged event will allow us to update the web page with the new value as the battery level changes.
很好,但是到⽬前为⽌,在设备连接后,我们的代码只会读取⼀次。 我们可以通过调⽤特征上的startNotifications函数来订阅更新(也称为
GATT通知)。 添加了⼀个事件处理程序characteristicvaluechanged事件将使我们能够⽤新值随着电池电量的变化更新⽹页。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论