微信小程序之蓝牙开发(详细读数据、写数据、附源码)
本文将详细介绍微信小程序的蓝牙开发流程(附源码)
准备:
微信只支持低功耗蓝牙也就是蓝牙4.0,普通的蓝牙模块是用不了的,一定要注意。
蓝牙可以连TTL接到电脑上,再用XCOM调试
一开始定义的变量
var deviceId;
var i=0;
var serviceId=[];
var characteristicId=[];
蓝牙开发流程:
1.打开蓝牙适配器
2.搜索周围蓝牙
3.获取搜索过程中所搜索到的设备信息
4.连接想要连接的设备
5.获取服务、特征值
6.写数据、读数据
具体实现:
1.打开蓝牙适配器
wx.openBluetoothAdapter({
success: function(res) {
console.log(res,"success")
},
fail: function (res) {
console.log("fail")
},
})
2.适配器打开后可以开始搜索蓝牙设备了
wx.startBluetoothDevicesDiscovery({
services: [],
success: function (res) {
console.log(res)
},
fail: function (res) {
console.log("fail")
},
})
sevices里不要填参数,要不然只能搜索特定的设备
3.搜索一小段时间后可以查看搜索到的设备,一般时间很短,1s都不用,搜不到可以多等等
wx.getBluetoothDevices({
success: function (res) {
console.log(res)
i=0;
while (res.devices[i]) {
console.log(i);
console.log(res.devices[i].name,res.devices[i].deviceId);
if(res.devices[i].name=='YahBoom_BL'){
deviceId=res.devices[i].deviceId;
console.log(deviceId);
}
i++;
}
}
})
这一步将所有搜索到的设备的名字和ID输出,并将名字为'YahBoom_BL'的设备的Id存到deviceId里去,这个设备就是我所需要使用的
4.现在我们可以获取一个特定设备的所有服务了
wx.getBLEDeviceServices({
deviceId: deviceId,
success: function(res) {
console.log(res.services);
i=0;
while(res.services[i]){
serviceId[i]=res.services[i].uuid;
console.log(serviceId[i]);
i++;
}
},
})
这一步我们获取YahBoom_BL的所有服务并储存到serviceId数组里去
5.现在我们可以针对一个特定服务查看这个服务所支持的操作
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serviceId[1],
success: function (res) {
i=0;
while(res.characteristics[i]){
characteristicId[i]=res.characteristics[i].uuid;
console.log(characteristicId[i]);
i++;
}
}
})
在这里我们获取YahBoom_BL的第二个服务(第一个服务下标为0,选第二个因为我的设备的第二个服务的第一个特征值支持notif、read、write,可以把一个服务的所有特征值打印出来查看)的特征值,并将特征值ID存到characteristicId数组里去
6.开启notify并读取蓝牙发过来的数据,开启这个后我们就能实时获取蓝牙发过来的值了
wx.notifyBLECharacteristicValueChange({
state: true,
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
success: function (res) {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
}
})
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
wx.onBLECharacteristicValueChange(function (res) {
console.log('characteristic value comed:', ab2hex(res.value))
})
这里第一个函数是开启notify服务,deviceId、serviceId、characteristicId都是之前我们获取的,第二个函数是将bufferArray类型转为string类型,因为buffer不能直接在console.log里输出,会显示null,第三个函数就是监听蓝牙发送过来的值了,蓝牙每次发送一个值,都会回调这个函数,res.value就是一个bufferArray类型,存的是发送过来的值
7.写数据到蓝牙
let buffer = new ArrayBuffer(3)
let dataView = new DataView(buffer)
dataView.setUint8(1, 100)
wx.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
value: buffer,
success: function (res) {
console.log('writeBLECharacteristicValue success', res.errMsg)
}
})
传数据给蓝牙时只能用buffer类型,let buffer = new ArrayBuffer(3)这句话定义一个三个长度的buffer,dataView.setUint8(1, 100)这句话将第一个值设置为100,所以传递过去的值就是00 64 00 (十六进制)
附录(直接复制粘贴就能运行)
JS源码:
var app = getApp();
var deviceId;
var i=0;
var serviceId=[];
var characteristicId=[];
Page({
data: {
},
onLoad:function(){
wx.onBluetoothAdapterStateChange(function (res) {
console.log('adapterState changed, now is', res)
})
},
openadapter:function(){
wx.openBluetoothAdapter({
success: function(res) {
console.log(res,"success")
},
fail: function (res) {
console.log(res,"fail")
},
})
// wx.getBluetoothAdapterState({
// complete: function (res) {
// console.log("currentstate:",res)
// }
// })
},
closeadapter: function () {
wx.closeBluetoothAdapter({
success: function (res) {
console.log(res, "success")
},
fail: function (res) {
console.log(res, "fail")
},
})
// wx.getBluetoothAdapterState({
// complete: function (res) {
// console.log("currentstate:", res)
// }
// })
},
opendiscovery:function(){
wx.startBluetoothDevicesDiscovery({
services: [],
success: function (res) {
console.log(res)
},
fail: function (res) {
console.log(res, "fail")
},
})
},
closediscovery:function(){
wx.stopBluetoothDevicesDiscovery({
success: function (res) {
console.log(res)
},
fail: function (res) {
console.log(res, "fail")
},
})
},
getdevice:function(){
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
wx.getBluetoothDevices({
success: function (res) {
console.log(res)
i=0;
while (res.devices[i]) {
console.log(i);
console.log(res.devices[i].name,res.devices[i].deviceId);
if(res.devices[i].name=='YahBoom_BL'){
deviceId=res.devices[i].deviceId;
console.log(deviceId);
}
i++;
}
}
})
},
getconnecteddevice:function(){
wx.getConnectedBluetoothDevices({
//services:[],
success: function (res) {
console.log(res)
}
})
},
connecteddevice:function(){
wx.createBLEConnection({
deviceId: deviceId,
success: function(res) {
console.log(res);
},
})
},
getservice:function(){
wx.getBLEDeviceServices({
deviceId: deviceId,
success: function(res) {
console.log(res.services);
i=0;
while(res.services[i]){
serviceId[i]=res.services[i].uuid;
console.log(serviceId[i]);
i++;
}
},
})
},
getcharacteristics:function(){
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serviceId[0],
success: function (res) {
console.log('device getBLEDeviceCharacteristics:', res.characteristics)
}
})
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serviceId[1],
success: function (res) {
i=0;
while(res.characteristics[i]){
characteristicId[i]=res.characteristics[i].uuid;
console.log(characteristicId[i]);
i++;
}
}
})
},
startread:function(){
wx.readBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
success: function (res) {
console.log('readBLECharacteristicValue:', res.errCode)
}
})
},
startnotify:function(){
wx.notifyBLECharacteristicValueChange({
state: true,
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
success: function (res) {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
}
})
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
wx.onBLECharacteristicValueChange(function (res) {
console.log('characteristic value comed:', ab2hex(res.value))
})
},
startwrite:function(){
let buffer = new ArrayBuffer(3)
let dataView = new DataView(buffer)
dataView.setUint8(1, 100)
wx.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId[1],
characteristicId: characteristicId[0],
value: buffer,
success: function (res) {
console.log('writeBLECharacteristicValue success', res.errMsg)
}
})
}
})
WXML源码:
<button bindtap='openadapter'>打开适配器</button>
<button bindtap='closeadapter'>关闭适配器</button>
<button bindtap='opendiscovery'>开始搜索</button>
<button bindtap='closediscovery'>关闭搜索</button>
<button bindtap='getdevice'>获取设备</button>
<button bindtap='getconnecteddevice'>获取已连接设备</button>
<button bindtap='connecteddevice'>连接我的设备</button>
<button bindtap='getservice'>获取服务</button>
<button bindtap='getcharacteristics'>获取特征值</button>
<button bindtap='startread'>读取值</button>
<button bindtap='startnotify'>开启notify</button>
<button bindtap='startwrite'>写数据</button>
微信小程序之蓝牙开发(详细读数据、写数据、附源码)的更多相关文章
- 微信小程序中如何使用WebSocket实现长连接(含完整源码)
本文由腾讯云技术团队原创,感谢作者的分享. 1.前言 微信小程序提供了一套在微信上运行小程序的解决方案,有比较完整的框架.组件以及 API,在这个平台上面的想象空间很大.腾讯云研究了一番之后,发现 ...
- 微信小程序调用蓝牙功能控制车位锁
第一次学用微信小程序,项目需要,被逼着研究了一下,功能是调用微信小程序的蓝牙功能,连接上智能车位锁,控制升降,大概步骤及调用的小程序接口API如下: 1.打开蓝牙模块 wx.openBluetooth ...
- 微信小程序的功能开发工具跟公众号的差别,小程序是一种减负思维对简单APP是巨大打击
微信小程序的功能开发工具跟公众号的差别,小程序是一种减负思维对简单APP是巨大打击 摘要: 小程序和公众号最大的区别有如下四点:1.小程序没有粉丝,开发者在后台能看到的只能是累计用户访问数以及实时统计 ...
- 利用python实现微信小程序游戏跳一跳详细教程
利用python实现微信小程序游戏跳一跳详细教程 1 先安装python 然后再安装pip <a href="http://newmiracle.cn/wp-content/uploa ...
- 微信小程序--使用云开发完成支付闭环
微信小程序--使用云开发完成支付闭环 1.流程介绍 2. 代码实现和逻辑思想描述 云函数统一下单 对应云函数 unipay [CloudPay.unifiedOrder] 函数思路 : 调用云函数封装 ...
- Slog71_选取、上传和显示本地图片GET !(微信小程序之云开发-全栈时代3)
ArthurSlog SLog-71 Year·1 Guangzhou·China Sep 12th 2018 ArthurSlog Page GitHub NPM Package Page 掘金主页 ...
- openlayers5-webpack 入门开发系列结合 echarts4 实现散点图(附源码下载)
前言 openlayers5-webpack 入门开发系列环境知识点了解: node 安装包下载webpack 打包管理工具需要依赖 node 环境,所以 node 安装包必须安装,上面链接是官网下载 ...
- 基于微信小程序的系统开发准备工作
腾讯推出微信小程序也有一段时间了,在各种行业里面也都掀起一阵阵的热潮,很多APP应用被简化为小程序的功能迅速推出,同时也根据小程序的特性推出各种独具匠心的应用,相对传统的APP来说,微信小程序确实能够 ...
- 微信小程序之蓝牙 BLE 踩坑记录
前言 前段时间接手了一个微信小程序的开发,主要使用了小程序在今年 3 月开放的蓝牙 API ,此过程踩坑无数,特此记录一下跳坑过程.顺便开了另一个相关的小项目,欢迎 start 和 fork: BLE ...
随机推荐
- C++宏定义不受命名空间的约束
// xxx.h namespace A { #define xxx() xxxxx } // 在其他文件中,引入xxx.h文件,使用宏定义时,不需要加命名空间 // yyy.cpp #include ...
- 对 Kotlin 与 Java 编程语言的思考
从长远来看,排名前10的也基本上是Java.C.C++.Python.C#.VB.PHP.JavaScript.至于Kotlin的排名,11月份在编程语言仅排41名,Ratings仅有0.216%. ...
- ubuntu配置zsh和oh-my-zsh
1安装zsh sudo apt-get install -y zsh chsh -s /bin/zsh 2安装oh-my-zsh $ sh -c "$(curl -fsSL https:// ...
- PHP标准库SPL
SPL是Standard PHP Library(PHP标准库)的缩写.用来解决典型(常见)问题(common problems)的一组接口与类的集合 典型问题(common problems) - ...
- Interactive Reporting , SQL*Net not loaded successfully 问题的解决。
.bashrc 什么的,早就把 TNS_ADMIN , 和 LD_LIBRARY_PATH 加进去了,可就是不好使. 终极方法还是在 workspace 的 R&A -> Service ...
- border可以这样给控件加边框
<Border.BorderBrush> <SolidColorBrush Color="Red" Opacity="0" / ...
- spoj Help the Military Recruitment Office!
题意:给出名字和地方,地方会重定向,最后再给出名字,问现在属于哪里? 用并查集. //#pragma comment(linker,"/STACK:1024000000,1024000000 ...
- Party CodeForces - 906C (状压)
大意: 给定n(n<=22)个人, m个关系谁跟谁是朋友, 朋友关系是双向的, 每次操作可以选择一个人, 使他的朋友互相成为朋友, 求最少多少次操作可以使所有人互相认识 这个题挺巧妙的了, 关键 ...
- Leetcode 77
//这似乎是排列组合的标准写法了已经class Solution { public: vector<vector<int>> combine(int n, int k) { v ...
- OC Copy自定义类