本文将详细介绍微信小程序的蓝牙开发流程(附源码)
准备:
微信只支持低功耗蓝牙也就是蓝牙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>

微信小程序之蓝牙开发(详细读数据、写数据、附源码)的更多相关文章

  1. 微信小程序中如何使用WebSocket实现长连接(含完整源码)

    本文由腾讯云技术团队原创,感谢作者的分享. 1.前言   微信小程序提供了一套在微信上运行小程序的解决方案,有比较完整的框架.组件以及 API,在这个平台上面的想象空间很大.腾讯云研究了一番之后,发现 ...

  2. 微信小程序调用蓝牙功能控制车位锁

    第一次学用微信小程序,项目需要,被逼着研究了一下,功能是调用微信小程序的蓝牙功能,连接上智能车位锁,控制升降,大概步骤及调用的小程序接口API如下: 1.打开蓝牙模块 wx.openBluetooth ...

  3. 微信小程序的功能开发工具跟公众号的差别,小程序是一种减负思维对简单APP是巨大打击

    微信小程序的功能开发工具跟公众号的差别,小程序是一种减负思维对简单APP是巨大打击 摘要: 小程序和公众号最大的区别有如下四点:1.小程序没有粉丝,开发者在后台能看到的只能是累计用户访问数以及实时统计 ...

  4. 利用python实现微信小程序游戏跳一跳详细教程

    利用python实现微信小程序游戏跳一跳详细教程 1 先安装python 然后再安装pip <a href="http://newmiracle.cn/wp-content/uploa ...

  5. 微信小程序--使用云开发完成支付闭环

    微信小程序--使用云开发完成支付闭环 1.流程介绍 2. 代码实现和逻辑思想描述 云函数统一下单 对应云函数 unipay [CloudPay.unifiedOrder] 函数思路 : 调用云函数封装 ...

  6. Slog71_选取、上传和显示本地图片GET !(微信小程序之云开发-全栈时代3)

    ArthurSlog SLog-71 Year·1 Guangzhou·China Sep 12th 2018 ArthurSlog Page GitHub NPM Package Page 掘金主页 ...

  7. openlayers5-webpack 入门开发系列结合 echarts4 实现散点图(附源码下载)

    前言 openlayers5-webpack 入门开发系列环境知识点了解: node 安装包下载webpack 打包管理工具需要依赖 node 环境,所以 node 安装包必须安装,上面链接是官网下载 ...

  8. 基于微信小程序的系统开发准备工作

    腾讯推出微信小程序也有一段时间了,在各种行业里面也都掀起一阵阵的热潮,很多APP应用被简化为小程序的功能迅速推出,同时也根据小程序的特性推出各种独具匠心的应用,相对传统的APP来说,微信小程序确实能够 ...

  9. 微信小程序之蓝牙 BLE 踩坑记录

    前言 前段时间接手了一个微信小程序的开发,主要使用了小程序在今年 3 月开放的蓝牙 API ,此过程踩坑无数,特此记录一下跳坑过程.顺便开了另一个相关的小项目,欢迎 start 和 fork: BLE ...

随机推荐

  1. python 时间戳转元组

    #!/usr/bin/python # -*- coding: UTF- -*- import time localtime = time.localtime(time.time()) print(& ...

  2. 转载: 华为内部Web安全测试原则

    原链接:http://www.ha97.com/5520.html Web安全原则 1.认证模块必须采用防暴力破解机制,例如:验证码或者多次连续尝试登录失败后锁定帐号或IP. 说明:如采用多次连续尝试 ...

  3. 技术分享:SSH实战项目

    1.需求分析 系统概述: 企业人事管理系统. 要求对员工信息进行维护. 后台系统先登录,才能操作员工;添加.修改.删除. 没有登录,只能查看列表,不能操作. 功能分类: 1)[管理员模块] 注册/登录 ...

  4. TimeZone 时区 (JS .NET JSON MYSQL) + work week 闰年

    来源参考 : http://www.cnblogs.com/qiuyi21/archive/2008/03/04/1089456.html 来源参考 : http://walkingice.blogs ...

  5. url 中需要转义的字符

    1. +  URL 中+号表示空格 %2B 2. 空格 URL中的空格可以用+号或者编码 %20 3. /  分隔目录和子目录 %2F  4. ?  分隔实际的 URL 和参数 %3F  5. % 指 ...

  6. infra 仪表盘效果

    private void Gauge2() { // Infragistics.WebUI.UltraWebGauge.UltraGauge ultraGauge2 = //new Infragist ...

  7. 20161227xlVBA多文件合并计算

    Sub NextSeven_CodeFrame() '应用程序设置 Application.ScreenUpdating = False Application.DisplayAlerts = Fal ...

  8. (GoRails) 如何去掉form输入框头尾的空格;何时用callbacks,gem;

    视频:https://gorails.com/episodes/when-callbacks-and-adding-dependencies-are-good?autoplay=1 主题:应当在什么时 ...

  9. Python多线程多进程

    一.线程&进程 对于操作系统来说,一个任务就是一个进程(Process),比如打开一个浏览器就是启动一个浏览器进程,打开一个记事本就启动了一个记事本进程,打开两个记事本就启动了两个记事本进程, ...

  10. Oracle12c中性能优化&amp;功能增强新特性之全局索引DROP和TRUNCATE 分区的异步维护

    Oracle 12c中,通过延迟相关索引的维护可以优化某些DROP和TRUNCATE分区命令的性能,同时,保持全局索引为有效. 1.   设置 下面的例子演示带全局索引的表创建和加载数据的过程. -- ...