只需要把下面第二个文件复制到项目里面,然后引入就可以了

主要流程:

1.初始化蓝牙适配器openBluetoothAdapter,如果不成功就onBluetoothAdapterStateChange监听蓝牙适配器状态变化事件

2.startBluetoothDevicesDiscovery开始搜寻附近的蓝牙外围设备

3.onBluetoothDeviceFound监听寻找到新设备的事件,在这里你可以用代码匹配设备

4.createBLEConnection创建蓝牙连接,顺便在stopBluetoothDevicesDiscovery关闭搜寻附近的蓝牙外围设备

5.getBLEDeviceServices获取蓝牙设备所有服务

6.getBLEDeviceCharacteristics获取蓝牙设备某个服务中所有特征值

7.onBLECharacteristicValueChange监听蓝牙设备发送给你的数据

8.writeBLECharacteristicValue向蓝牙设备发送一个0x00的16进制数据或者writeBLECharacteristicValueString发送字符串

<template><view></view></template><script>import bt from '../../utils/bluetooth.vue';export default {data() {return {}},methods: {},onLoad(opt) {bt.openBluetoothAdapter("DEMO1");}}</script><style></style>


<template><view></view></template><script>var _discoveryStarted = false;var _deviceId = null;var _serviceId = null;var _characteristicId = null;var chs = [];var btvalue = null;function inArray(arr, key, val) {  for (let i = 0; i < arr.length; i++) {    if (arr[i][key] === val) {      return i;    }  }  return -1;}// ArrayBuffer转16进度字符串示例function ab2hex(buffer) {  var hexArr = Array.prototype.map.call(    new Uint8Array(buffer),    function (bit) {      return ('00' + bit.toString(16)).slice(-2)    }  )  return hexArr.join('');}//准备开始扫描function $openBluetoothAdapter(devicename){//初始化蓝牙模块uni.openBluetoothAdapter({success: (res) => {    console.log('openBluetoothAdapter success', res);    $startBluetoothDevicesDiscovery(devicename);},fail: (res) => {uni.showToast({    title: '请打开蓝牙',    duration: 1000});    if (res.errCode === 10001) {//监听蓝牙适配器状态变化事件uni.onBluetoothAdapterStateChange(function(res){console.log('onBluetoothAdapterStateChange', res);if (res.available) {//开始扫描$startBluetoothDevicesDiscovery(devicename)}})    }}})}function $startBluetoothDevicesDiscovery(devicename){if (_discoveryStarted) {    return;}_discoveryStarted = true;//开始搜寻附近的蓝牙外围设备uni.startBluetoothDevicesDiscovery({allowDuplicatesKey: true,    success: (res) => {    console.log('startBluetoothDevicesDiscovery success', res);//监听寻找到新设备的事件    $onBluetoothDeviceFound(devicename)},})}function $onBluetoothDeviceFound(devicename) {//监听寻找到新设备的事件uni.onBluetoothDeviceFound(function(res){res.devices.forEach(device => {if (!device.name && !device.localName) {  return;}console.log(device);//如果名字相同连接设备if(device.name == devicename){$createBLEConnection(device.deviceId);}})})}function $createBLEConnection(deviceId){//创建连接uni.createBLEConnection({deviceId:deviceId,success: (res) => {console.log(res);$getBLEDeviceServices(deviceId);},fail: (err) =>{console.log(err);}});$stopBluetoothDevicesDiscovery();}function $getBLEDeviceServices(deviceId) {//获取蓝牙设备所有服务(service)uni.getBLEDeviceServices({deviceId,success: (res) => {  for (let i = 0; i < res.services.length; i++) {    if (res.services[i].isPrimary) {      $getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);  return;    }  }}});}function $getBLEDeviceCharacteristics(deviceId, serviceId){//获取蓝牙设备某个服务中所有特征值(characteristic)。uni.getBLEDeviceCharacteristics({deviceId,serviceId,success: (res) => {console.log('getBLEDeviceCharacteristics success', res.characteristics);for (let i = 0; i < res.characteristics.length; i++) {    let item = res.characteristics[i]    if (item.properties.read) {//读取低功耗蓝牙设备的特征值的二进制数据值。1uni.readBLECharacteristicValue({deviceId,serviceId,characteristicId: item.uuid,})    }    if (item.properties.write) {        _deviceId = deviceId;        _serviceId = serviceId;        _characteristicId = item.uuid;        $writeBLECharacteristicValue();    }    if (item.properties.notify || item.properties.indicate) {//启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。uni.notifyBLECharacteristicValueChange({            deviceId,            serviceId,            characteristicId: item.uuid,            state: true,        });    }}},fail(res) {    console.error('getBLEDeviceCharacteristics', res)}})//监听数据// 操作之前先监听,保证第一时间获取数据uni.onBLECharacteristicValueChange(function(characteristic){const idx = inArray(chs, 'uuid', characteristic.characteristicId)const data = {}if (idx === -1) {  data[`chs[${chs.length}]`] = {    uuid: characteristic.characteristicId,    value: ab2hex(characteristic.value)  }} else {  data[`chs[${idx}]`] = {    uuid: characteristic.characteristicId,    value: ab2hex(characteristic.value)  }}console.log(data);btvalue = data;})}function $writeBLECharacteristicValue() {// 向蓝牙设备发送一个0x00的16进制数据let buffer = new ArrayBuffer(1)let dataView = new DataView(buffer)dataView.setUint8(0, 0x61 | 0);uni.writeBLECharacteristicValue({      deviceId: _deviceId,      serviceId: "0000FFE0-0000-1000-8000-00805F9B34FB",      characteristicId: _characteristicId,      value: buffer,      success: function(res){        console.log(res);      },      fail: function(res){        console.log(res);      }})};function $writeBLECharacteristicValueString(str) {// 向蓝牙设备发送16进制数据let buffer = new ArrayBuffer(str.length);let dataView = new DataView(buffer);for (let i in str) {dataView.setUint8(i, str[i].charCodeAt() | 0);}uni.writeBLECharacteristicValue({      deviceId: _deviceId,      serviceId: "0000FFE0-0000-1000-8000-00805F9B34FB",      characteristicId: _characteristicId,      value: buffer,      success: function(res){        console.log(res);      },      fail: function(res){        console.log(res);      }})};function $stopBluetoothDevicesDiscovery(){//关闭搜索uni.stopBluetoothDevicesDiscovery({success(res) {console.log(res);}})}export default {data() {return {}},methods: {},openBluetoothAdapter: $openBluetoothAdapter,writeBLECharacteristicValue: $writeBLECharacteristicValue,writeBLECharacteristicValueString: $writeBLECharacteristicValueString}</script><style></style>


 

©著作权归作者所有:来自51CTO博客作者卡哇伊大喵的原创作品,如需转载,请注明出处,否则将追究法律责任

更多相关文章

  1. 【DB笔试面试276】什么是字符设备、块设备和裸设备?
  2. Google Play上出现了针对移动设备的恶意软件
  3. dd命令详解
  4. 如何在Mac上打开蓝牙并配对新设备
  5. 一种新的Android恶意软件HiddenMiner,影响印度和中国的用户
  6. 盘点物联网设备7大***面及其应对措施
  7. Linux设备驱动之Ioctl控制
  8. linux设备驱动程序中的阻塞机制
  9. IIC驱动移植在linux3.14.78上的实现和在linux2.6.29上实现对比

随机推荐

  1. Android(安卓)基于Http协议的文件上传
  2. android 为activity添加optionMenu选项菜
  3. Android练手小项目(KTReader)基于mvp架构(二
  4. android性能测试工具
  5. android 自定义加减按钮
  6. android main.xml分析。。一点点补充
  7. Android(安卓)Things(一)-简介篇
  8. Android绘图三大基本类
  9. 解决 Android N 7.0 上 报错:android.os.F
  10. android 添加 iconv 支持