【鸿蒙蓝牙连接】

2024-09-05 06:28
文章标签 连接 蓝牙 鸿蒙

本文主要是介绍【鸿蒙蓝牙连接】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

鸿蒙蓝牙连接

  • ble.startBLEScan

startBLEScan(filters: Array, options?: ScanOptions): void
发起BLE扫描流程。
需要权限:ohos.permission.ACCESS_BLUETOOTH
在这里插入图片描述

import { BusinessError } from '@ohos.base';
function onReceiveEvent(data: Array<ble.ScanResult>) {console.info('BLE scan device find result = '+ JSON.stringify(data));
}
try {ble.on("BLEDeviceFind", onReceiveEvent);let scanFilter: ble.ScanFilter = {deviceId:"XX:XX:XX:XX:XX:XX",name:"test",serviceUuid:"00001888-0000-1000-8000-00805f9b34fb"};let scanOptions: ble.ScanOptions = {interval: 500,dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER,matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE,}ble.startBLEScan([scanFilter],scanOptions);
} catch (err) {console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}
  • ble.stopBLEScan

stopBLEScan(): void
停止BLE扫描流程。
需要权限:ohos.permission.ACCESS_BLUETOOTH

import { BusinessError } from '@ohos.base';
try {ble.stopBLEScan();
} catch (err) {console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}
  • connect
    connect(): void
    client端发起连接远端蓝牙低功耗设备。
    需要权限:ohos.permission.ACCESS_BLUETOOTH
import { BusinessError } from '@ohos.base';
try {let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');device.connect();
} catch (err) {console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}
  • disconnect
    disconnect(): void
    client端断开与远端蓝牙低功耗设备的连接。
    需要权限:ohos.permission.ACCESS_BLUETOOTH
import { BusinessError } from '@ohos.base';
try {let device: ble.GattClientDevice = ble.createGattClientDevice('XX:XX:XX:XX:XX:XX');device.disconnect();
} catch (err) {console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);
}
  • 下面是测试例子:
import { BusinessError } from '@ohos.base';
import ble from '@ohos.bluetooth.ble';
import { TAG } from '@ohos/hypium/src/main/Constant';@Entry
@Component
struct BluetoothText {@State message: string = '蓝牙测试界面';@State scanResults: Array<string> = [];  // 存储扫描结果private scannedDeviceIds: Set<string> = new Set();  // 存储已经扫描到的设备IDprivate targetDeviceId: string = "7C:87:CE:1D:DF:F2";  // 目标设备的Device IDprivate gattClientDevice: ble.GattClientDevice | null = null;mBorder: BorderOptions = { radius: 10, color: '#385E0F', width: 1 };fontSize = 16mColor: string = '#2E8B57'build() {Row() {Column() {// 显示当前状态信息Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)Row() {Button("连接").fontSize(this.fontSize).height('60%').width('40%').border(this.mBorder).backgroundColor(this.mColor).onClick(() => {this.startBLEScan();});Button("停止").fontSize(this.fontSize).height('60%').width('40%').border(this.mBorder).backgroundColor(this.mColor).onClick(() => {this.stopBLEScan();});}.width('30%').height('10%').padding({ left: 10, right: 10 })// 滚动容器,用于显示扫描结果列表Scroll() {Column() {  // 使用 Column 作为 Scroll 的唯一子组件ForEach(this.scanResults, (result: string) => {Text(result).fontSize(20).fontColor(Color.Black).padding(10)})}}.height('80%')  // 设置滚动区域高度.width('100%')}.width('100%')}.height('100%')}startBLEScan() {// 使用箭头函数定义try {ble.on("BLEDeviceFind", this.onReceiveEvent);  // 直接传递引用let scanFilter: ble.ScanFilter = {deviceId: this.targetDeviceId,};let scanOptions: ble.ScanOptions = {interval: 500,dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER,matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE,};ble.startBLEScan([scanFilter], scanOptions);this.message = 'Scanning...';} catch (err) {console.error('errCode: ' + err.code + ', errMessage: ' + err.message);this.message = 'Scan failed: ' + err.message;}}onReceiveEvent = (data: Array<ble.ScanResult>) => {console.info('BLE scan device find result = ' + JSON.stringify(data));let newResults = data.map((device) => {if (!this.scannedDeviceIds.has(device.deviceId)) {this.scannedDeviceIds.add(device.deviceId);  // 添加设备ID到集合中if (device.deviceId === this.targetDeviceId) {// 创建并连接到 GATT 客户端设备try {this.gattClientDevice = ble.createGattClientDevice(device.deviceId);this.gattClientDevice.connect();console.debug(TAG,"连接成功")} catch (err) {console.error('创建GATT客户端设备失败,errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);this.message = '创建GATT客户端设备失败';}}console.debug(TAG,`Device Name: ${device.deviceName || 'Unknown'}, Device ID: ${device.deviceId}`);return `Device Name: ${device.deviceName || 'Unknown'}, Device ID: ${device.deviceId}`;}return null;}).filter(result => result !== null);  // 过滤掉 null 值this.scanResults = [...this.scanResults, ...newResults as string[]];  // 合并新旧结果this.message = 'Scan result received!';}//停止蓝牙扫描stopBLEScan(){try {ble.stopBLEScan();this.gattClientDevice?.disconnect();} catch (err) {console.error('errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message);}}
}

这篇关于【鸿蒙蓝牙连接】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1138196

相关文章

MySQL中的表连接原理分析

《MySQL中的表连接原理分析》:本文主要介绍MySQL中的表连接原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、环境3、表连接原理【1】驱动表和被驱动表【2】内连接【3】外连接【4编程】嵌套循环连接【5】join buffer4、总结1、背景

SpringBoot连接Redis集群教程

《SpringBoot连接Redis集群教程》:本文主要介绍SpringBoot连接Redis集群教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1. 依赖2. 修改配置文件3. 创建RedisClusterConfig4. 测试总结1. 依赖 <de

华为鸿蒙HarmonyOS 5.1官宣7月开启升级! 首批支持名单公布

《华为鸿蒙HarmonyOS5.1官宣7月开启升级!首批支持名单公布》在刚刚结束的华为Pura80系列及全场景新品发布会上,除了众多新品的发布,还有一个消息也点燃了所有鸿蒙用户的期待,那就是Ha... 在今日的华为 Pura 80 系列及全场景新品发布会上,华为宣布鸿蒙 HarmonyOS 5.1 将于 7

java连接opcua的常见问题及解决方法

《java连接opcua的常见问题及解决方法》本文将使用EclipseMilo作为示例库,演示如何在Java中使用匿名、用户名密码以及证书加密三种方式连接到OPCUA服务器,若需要使用其他SDK,原理... 目录一、前言二、准备工作三、匿名方式连接3.1 匿名方式简介3.2 示例代码四、用户名密码方式连接4

MySQL 表的内外连接案例详解

《MySQL表的内外连接案例详解》本文给大家介绍MySQL表的内外连接,结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录表的内外连接(重点)内连接外连接表的内外连接(重点)内连接内连接实际上就是利用where子句对两种表形成的笛卡儿积进行筛选,我

Apache 高级配置实战之从连接保持到日志分析的完整指南

《Apache高级配置实战之从连接保持到日志分析的完整指南》本文带你从连接保持优化开始,一路走到访问控制和日志管理,最后用AWStats来分析网站数据,对Apache配置日志分析相关知识感兴趣的朋友... 目录Apache 高级配置实战:从连接保持到日志分析的完整指南前言 一、Apache 连接保持 - 性

电脑蓝牙连不上怎么办? 5 招教你轻松修复Mac蓝牙连接问题的技巧

《电脑蓝牙连不上怎么办?5招教你轻松修复Mac蓝牙连接问题的技巧》蓝牙连接问题是一些Mac用户经常遇到的常见问题之一,在本文章中,我们将提供一些有用的提示和技巧,帮助您解决可能出现的蓝牙连接问... 蓝牙作为一种流行的无线技术,已经成为我们连接各种设备的重要工具。在 MAC 上,你可以根据自己的需求,轻松地

宝塔安装的MySQL无法连接的情况及解决方案

《宝塔安装的MySQL无法连接的情况及解决方案》宝塔面板是一款流行的服务器管理工具,其中集成的MySQL数据库有时会出现连接问题,本文详细介绍两种最常见的MySQL连接错误:“1130-Hostisn... 目录一、错误 1130:Host ‘xxx.xxx.xxx.xxx’ is not allowed

MySQL 多表连接操作方法(INNER JOIN、LEFT JOIN、RIGHT JOIN、FULL OUTER JOIN)

《MySQL多表连接操作方法(INNERJOIN、LEFTJOIN、RIGHTJOIN、FULLOUTERJOIN)》多表连接是一种将两个或多个表中的数据组合在一起的SQL操作,通过连接,... 目录一、 什么是多表连接?二、 mysql 支持的连接类型三、 多表连接的语法四、实战示例 数据准备五、连接的性

MySQL中的分组和多表连接详解

《MySQL中的分组和多表连接详解》:本文主要介绍MySQL中的分组和多表连接的相关操作,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录mysql中的分组和多表连接一、MySQL的分组(group javascriptby )二、多表连接(表连接会产生大量的数据垃圾)MySQL中的