蓝牙部分知识

  • 关于Service:

每个设备包含有多个Service,每个Service对应一个uuid

  • 关于Characteristic

每个Service包含多个Characteristic,每个Characteristic对应一个uuid

  • 如何得到数据

我们想要的数据是包含在每一个Characteristic

微信小程序目前提供的蓝牙API:详细参数请见小程序开发文档

1.操作蓝牙适配器的4个API  

wx.openBluetoothAdapter //初始化蓝牙适配器

wx.closeBluetoothAdapter //关闭蓝牙模块

wx.getBluetoothAdapterState //获取本机蓝牙适配器状态

wx.onBluetoothAdapterStateChange //监听蓝牙适配器状态变化事件

2.连接前使用的共有4个,分别是

wx.startBluetoothDevicesDiscovery //开始搜寻附近的蓝牙外围设备
wx.stopBluetoothDevicesDiscovery //停止搜寻附近的蓝牙外围设备
wx.getBluetoothDevices //获取所有已发现的蓝牙设备
wx.onBluetoothDeviceFound //监听寻找到新设备的事件

3.连接和断开时使用的共有2个,分别是

wx.createBLEConnection //连接低功耗蓝牙设备
wx.closeBLEConnection //断开与低功耗蓝牙设备的连接

4.连接成功后使用的共有8个,分别是

wx.getConnectedBluetoothDevices //根据 uuid 获取处于已连接状态的设备
wx.getBLEDeviceServices //获取蓝牙设备所有 service(服务)
wx.getBLEDeviceCharacteristics //获取蓝牙设备所有 characteristic(特征值)
wx.readBLECharacteristicValue //读取低功耗蓝牙设备的特征值的二进制数据值
wx.writeBLECharacteristicValue //向低功耗蓝牙设备特征值中写入二进制数据
wx.notifyBLECharacteristicValueChange //启用低功耗蓝牙设备特征值变化时的 notify 功能
wx.onBLECharacteristicValueChange //监听低功耗蓝牙设备的特征值变化
wx.onBLEConnectionStateChange //监听低功耗蓝牙连接的错误事件

基本操作流程

1.初始化蓝牙适配器

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

3.监听寻找到新设备的事件

4.连接低功耗蓝牙设备

5获取蓝牙设备所有 service 和 characteristic

6.读取或写入低功耗蓝牙设备的特征值的二进制数据值。

示例:

<!--index.wxml-->
<view class="container"> <view class="content">
<text class="status">适配器状态:{{ status }}</text>
<text class="sousuo">是否搜索:{{ sousuo }}</text>
<text class="msg">消息:{{ msg }} </text> <button type="default" class="button" bindtap="initializeBluetooth">初始化蓝牙适配器</button>
<button type="default" class="button" bindtap="searchBluetooth">搜索蓝牙设备 </button>
<button type="default" class="button" bindtap="getServices">获取连接设备所有service</button>
<button type="default" class="button" bindtap="sendMessages">发送消息</button>
<button type="default" class="button" bindtap="startBletNotify">启用设备特征值变化时的notify</button>
<button type="default" class="button" bindtap="receiveMessages">接收消息</button>
<button type="default" class="button" bindtap="closeBluetooth">断开蓝牙连接</button> <view class="section">
<text class="status">接收到消息:{{ jieshou }}</text>
</view>
</view> <view class="venues_list" >
<block wx:for="{{devices}}" wx:key="{{test}}">
<view class="venues_item">
<text class="status1">设备名称: {{item.name}} </text>
<text class="status">设备ID: {{item.deviceId}} </text>
<text class='status'>广播数据: {{item.advertisData}} </text>
<text class='status'>信号强度RSSI: {{item.RSSI}} </text>
<text class="status">连接状态:{{connectedDeviceId == item.deviceId?"已连接":"未连接"}} </text>
<view class="section">
</view>
<view class="section">
<button type="warn" class="button" id="{{item.deviceId}}" bindtap="connectTO">连接</button>
</view>
</view>
</block>
</view> </view>
//index.js
//获取应用实例
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
status: "",
sousuo: "",
connectedDeviceId: "", //已连接设备uuid
services: [], // 连接设备的服务
serviceId: "",
characteristics: "", // 连接设备的状态值
writeServicweId: "", // 可写服务uuid
writeCharacteristicsId: "",//可写特征值uuid
readServicweId: "", // 可读服务uuid
readCharacteristicsId: "",//可读特征值uuid
notifyServicweId: "", //通知服务UUid
notifyCharacteristicsId: "", //通知特征值UUID
inputValue: "",
characteristics1: "", // 连接设备的状态值
},
onLoad: function () {
}, // 初始化蓝牙适配器
initializeBluetooth: function () {
var that = this;
if (!wx.openBluetoothAdapter) {
console.log('蓝牙适配器打开失败,请检查微信版本或手机是否支持小程序蓝牙模块!')
} else {
wx.openBluetoothAdapter({
success: function (res) {
that.setData({
msg: "初始化蓝牙适配器成功!"
})
wx.getBluetoothAdapterState({//获取本机蓝牙适配器状态
success: function (res) {
console.log('本机蓝牙适配器状态:')
console.log(res)
}
})
}
})
}
}, //搜索获取已发现设备
searchBluetooth: function () {
var that = this;
wx.startBluetoothDevicesDiscovery({//开始搜寻附近的蓝牙外围设备
success: function (res) {
console.log('开始搜索周边蓝牙设备')
console.log(res)
wx.getBluetoothDevices({//sucess返回uuid 对应的的已连接设备列表,Array类型
success: function (res) {
//是否有已连接设备
wx.getConnectedBluetoothDevices({////根据 uuid 获取处于已连接状态的设备
success: function (res) {
console.log('已连接的蓝牙设备:')
console.log(JSON.stringify(res.devices));
that.setData({
connectedDeviceId: res.deviceId
})
}
})
that.setData({
devices: res.devices,
})
}
})
}
})
}, //连接设备
connectTO: function (e) {
var that = this;
wx.stopBluetoothDevicesDiscovery({ //先停止搜索周边设备
success: function (res) {
console.log('连接设备前,先停止搜索周边设备:')
console.log(res)
}
})
wx.showLoading({
title: '连接蓝牙设备中...',
})
wx.createBLEConnection({//若小程序在之前已有搜索过某个蓝牙设备,并成功建立链接,可直接传入之前搜索获取的deviceId直接尝试连接该设备,无需进行搜索操作。
deviceId: e.currentTarget.id,
success: function (res) {
console.log('连接成功:')
console.log(res)
wx.hideLoading()
that.setData({
connectedDeviceId: e.currentTarget.id, //currentTarget: 事件绑定的元素
msg: "已连接" + e.currentTarget.id,
})
},
fail: function () {
console.log("调用失败");
},
complete: function () {
console.log('已连接设备ID:' + that.data.connectedDeviceId);
console.log("调用结束");
}
})
}, // 获取连接设备的service服务
getServices: function () {
var that = this;
wx.getBLEDeviceServices({//获取在小程序蓝牙模块生效期间所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备
// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: that.data.connectedDeviceId,
success: function (res) {
//console.log('获取蓝牙设备所有服务成功:', res);
that.data.services = res.services
console.log('获取蓝牙设备所有服务成功:', that.data.services);
that.setData({
serviceId: that.data.services[0].uuid,
})
console.log("服务uuid:", that.data.serviceId)
wx.getBLEDeviceCharacteristics({
// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: that.data.connectedDeviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
serviceId: that.data.serviceId, //-----注意是that.data.services[0].uuid
success: function (res) {
console.log('serviceId: that.data.services[0].uuid: ', that.data.serviceId)
console.log(res)
for (var i = 0; i < res.characteristics.length; i++) {
if (res.characteristics[i].properties.notify) { //注意characteristic(特征值)信息,properties对象
that.setData({
notifyServicweId: that.data.services[0].uuid,
notifyCharacteristicsId: res.characteristics[i].uuid,
})
console.log("notifyServicweId:", that.data.notifyServicweId,"notifyCharacteristicsId", that.data.notifyCharacteristicsId)
}
if (res.characteristics[i].properties.write) {
that.setData({
writeServicweId: that.data.services[0].uuid,
writeCharacteristicsId: res.characteristics[i].uuid,
})
console.log("writeServicweId:", that.data.writeServicweId, "writeCharacteristicsId", that.data.writeCharacteristicsId)
} else if (res.characteristics[i].properties.read) {
that.setData({
readServicweId: that.data.services[0].uuid,
readCharacteristicsId: res.characteristics[i].uuid,
})
console.log("readServicweId:", that.data.readServicweId, "readCharacteristicsId", that.data.readCharacteristicsId)
}
}
},
fail: function () {
console.log("获取连接设备的所有特征值:", res);
},
complete: function () {
console.log("complete!");
}
})
}
})
}, //断开设备连接
closeBluetooth: function () {
var that = this;
wx.closeBLEConnection({
deviceId: that.data.connectedDeviceId,
success: function (res) {
console.log('断开设备连接: ', devicedId)
console.log(res)
}
})
}, //发送
sendMessages: function () {
var that = this;
// 这里的回调可以获取到 write 导致的特征值改变
wx.onBLECharacteristicValueChange(function (characteristic) {
console.log('characteristic value changed:1', characteristic)
})
var buf = new ArrayBuffer(16)
var dataView = new DataView(buf)
dataView.setUint8(0, 99)
wx.writeBLECharacteristicValue({
deviceId: that.data.connectedDeviceId,
serviceId: that.data.writeServicweId,
characteristicId: that.data.writeCharacteristicsId,
value: buf,
success: function (res) {
console.log('writeBLECharacteristicValue success', res)
}
})
}, //启用低功耗蓝牙设备特征值变化时的 notify 功能
startBletNotify: function () {
var that = this;
wx.notifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
deviceId: that.data.connectedDeviceId,
serviceId: that.data.notifyServicweId,
characteristicId: that.data.notifyCharacteristicsId,
success: function (res) {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
},
fail: function () {
console.log('启用notify功能失败!');
console.log(that.data.notifyServicweId);
console.log(that.data.notifyCharacteristicsId);
},
})
}, //接收消息
receiveMessages: function () {
var that = this;
// 必须在这里的回调才能获取
wx.onBLECharacteristicValueChange(function (characteristic) {
let hex = Array.prototype.map.call(new Uint8Array(characteristic.value), x => ('00' + x.toString(16)).slice(-2)).join('');
console.log(hex)
})
console.log(that.data.readServicweId);
console.log(that.data.readCharacteristicsId);
wx.readBLECharacteristicValue({
deviceId: that.data.connectedDeviceId,
serviceId: that.data.readServicweId,
characteristicId: that.data.readCharacteristicsId,
success: function (res) {
console.log('readBLECharacteristicValue:', res.errMsg);
}
})
}, onHide: function () {
var that = this
this.setData({
devices_list: []
})
if (this.data.searching) {
wx.stopBluetoothDevicesDiscovery({//隐藏界面是建议停止
success: function (res) {
console.log(res)
that.setData({
searching: false
})
}
})
}
}
})

微信小程序蓝牙模块的更多相关文章

  1. 微信小程序蓝牙开发

    微信小程序蓝牙控制方案: 蓝牙模块如何快速改名并绑定用户手机?这样即使多台蓝牙设备在同一个地方使用也可以互不干扰,燧星科技给出解决方案. 长按控制板5秒进入待绑定下状态,点击"添加蓝牙设备& ...

  2. Odoo 开源微信小程序商城模块

    详见:http://oejia.net/blog/2018/09/13/oejia_weshop_about.html oejia_weshop Odoo 微信小程序商城模块 oejia_weshop ...

  3. 微信小程序-蓝牙连接

    最近的项目需要使用小程序的蓝牙功能与硬件设备进行连接相互传送数据指令,联调过程中发现一些问题,于是想着记录下来,方便以后查看! 1.0一般使用蓝牙功能肯定是想连接某一个蓝牙设备,所以需要知道这个蓝牙设 ...

  4. 微信小程序地图模块

    微信小程序的地图模块官方提供的API比较少,详情请见   官方文档 以下为一个示例                               <!--pages/location/locati ...

  5. .NET开发微信小程序-Template模块开发

    1.添加一个文件目录,里面放模板信息 例:我在根目录添加一个文件夹:template 然后在这个文件夹下面添加相应的页面.比如我添加一个promodel.wxml文件.主要是放商品相关的模块信息(注: ...

  6. 微信小程序蓝牙连接小票打印机

    1.连接蓝牙 (第一次发表博客)   第一步打开蓝牙并搜索附近打印机设备// startSearch: function() { var that = this wx.openBluetoothAda ...

  7. 微信小程序周报(第十三期)-极乐商店(store.dreawer.com)出品

    重要:极乐商店域名变更:wxapp.dreawer.com/变更为store.dreawer.com/ 每周一笑 当年刚学打篮球的时候,疯狂地迷恋上了乔丹,然后迷恋上了NIKE,更熟记了NIKE的那句 ...

  8. 微信小程序调用用百度地图天气功能

    #小程序之调用百度地图天气功能 本篇博客主要介绍小程序在百度地图中获取天气信息,如有不全请指出.下面先上效果图 主要内容 百度地图API的个人密钥,也就是AK 请求百度地图API接口数据 获取到的信息 ...

  9. 记录使用微信小程序的NFC和蓝牙功能读取15693芯片的开发历程

    开发目标: (1) 对于Android手机,直接通过微信小程序调用手机的NFC功能,对15693协议的芯片进行读写操作: (2)对于苹果手机(及没有NFC模块的手机),通过微信小程序的蓝牙功能连接到蓝 ...

随机推荐

  1. tar 命令显示进度条

    实现该功能需要安装 pv,然后把需要处理的数据通过管道传给 pv,最后再进行操作. 传给 pv 的目的是为了知道已经处理的数据量大小,同时需要通过 -s 指定总共需要处理的数据量大小. pv 的安装一 ...

  2. k-Nearest Neighbor algorithm 思想

    转载      KNN--K最邻近算法思想 KNN算法的决策过程 k-Nearest Neighbor algorithm  上图中,绿色圆要被决定赋予哪个类,是红色三角形还是蓝色四方形?如果K=3, ...

  3. 2015/11/4用Python写游戏,pygame入门(4):获取鼠标的位置及运动

    按昨天的说法,今天将开始做一个简单的游戏了. 目标是拷贝微信的飞机大战,当然拷贝完以后大家就具备自己添加不同内容的能力了. 首先是要拿到一些图片素材,熟悉使用图像处理软件和绘画的人可以自己制作,并没有 ...

  4. SQL语句(十八_补充)——存储过程

    一. 变量 1. 形式: @x (局部), @@x(全局) 2. 定义: declare @x 3. 赋值:Set @x = ? 4. 作用: 通用化 存储在服务器 5. 存储过程(预编译过的T-SQ ...

  5. eclipse 无法解析导入 javax.servlet 的解决方法

    出现上述问题的原因是你的Eclipse项目没有导入JSP运行所需要的Tomcat类库,主要是servlet-api.jar文件(或者servlet.jar),tomcat容器里面有这文件,在以下位置: ...

  6. Mockserver -MOCO的使用

    转自: http://blog.csdn.net/shensky711/article/details/52770686

  7. 微信 js-sdk

    使用方法 http://mp.weixin.qq.com/wiki/11/74ad127cc054f6b80759c40f77ec03db.html Demo http://203.195.235.7 ...

  8. JS 数组 foreach 和 map

    本文地址:http://www.cnblogs.com/veinyin/p/8794677.html  foreach 和 map 都是数组的迭代方法,对数组的每一项执行给定函数,不会改变原数组. 两 ...

  9. oracle建表,设置主键,修改属性等

    --建表 create table book( book_id number(10), book_name varchar2(20), book_price number(10,2), book_au ...

  10. perl6 HTTP::UserAgent发送post

    use HTTP::UserAgent; my $ua = HTTP::UserAgent.new; say 'All method:'; say $ua.^methods; my %data = : ...