当前位置:首页 > 代码 > 正文

微信小程序蓝牙源代码(微信小程序蓝牙模块)

admin 发布:2022-12-19 21:20 145


本篇文章给大家谈谈微信小程序蓝牙源代码,以及微信小程序蓝牙模块对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

微信小程序蓝牙模块开发

//index.js

//获取应用实例

const app = getApp()

const util = require('../../utils/util.js')

const bletool = require('../../utils/bletool.js')

Page({

data: {

// lists: [{ 'order_no': '1111', 'car_no': '321', 'car_type': '尚好捷', 'order_date': '2018-01-02 08:00', 'order_money': '16.00', 'order_time': '4' }],

car_no: '',

order_no: '',

lists: [],

bleList: [], //蓝牙设备数组

serviceId: '',//592B3370-3900-9A71-4535-35D4212D2837

serviceMac: '',//C9:9B:4C:E7:DE:10

service_psd: '',//855525B837253705595800000329

service_uuid: '',

deviceId:'',

characteristics:[] //特征值

},

onLoad: function (options) {

this.initBle();

},

onReady: function () {

// 页面渲染完成

},

onShow: function () {

if (app.globalData.car_no.length0){

this.getDeviceInfo();

}

},

onHide: function () {

// 页面隐藏

},

onUnload: function () {

// 页面关闭

app.globalData.car_no=''

},

//蓝牙相关

//初始化蓝牙

initBle: function () {

var that = this;

wx.onBluetoothAdapterStateChange(function (res) {

console.log('adapterState changed, now is', res)

app.globalData.ble_state = res.available;

if (res.available) {

that.initBle();

} else {

util.showToast('手机蓝牙已关闭');

app.globalData.ble_isonnectting = false;

}

})

//打开蓝牙适配器

wx.openBluetoothAdapter({

success: function (res) {

console.log('打开蓝牙适配器成功');

that.getBluetoothAdapterState();

app.globalData.ble_state = true;

that.onBluetoothDeviceFound();

},

fail: function (res) {

// fail

console.log(res)

util.showToast('请打开手机蓝牙');

},

complete: function (res) {

// complete

}

})

},

onBluetoothDeviceFound:function(){

var that = this;

//监听扫描

wx.onBluetoothDeviceFound(function (res) {

// res电脑模拟器返回的为数组;手机返回的为蓝牙设备对象

console.log('监听搜索新设备:', res);

that.updateBleList([res])

})

},

getBluetoothAdapterState: function () {

var that = this;

wx.getBluetoothAdapterState({

success: function (res) {

var available = res.available;

var discovering = res.discovering;

if (!available) {

util.showToast('蓝牙不可用');

} else {

if (!discovering) {

// that.startBluetoothDevicesDiscovery();

}

}

}

})

},

startBluetoothDevicesDiscovery: function () {

var that = this;

var services = [];

services.push(this.data.serviceId);

wx.showLoading({

title: '设备搜索中'

});

setTimeout(function () {

wx.hideLoading();

if (app.globalData.deviceId.length==0){

util.showModal('设备搜索失败,请重试');

}

}, 10000)

if(bletool.isIOS()){

wx.startBluetoothDevicesDiscovery({

services: services,

allowDuplicatesKey: true,

success: function (res) {

console.log('ios搜索成功');

console.log(res);

},

fail: function (err) {

console.log(err);

}

});

}else{

wx.startBluetoothDevicesDiscovery({

// services: services,

allowDuplicatesKey: true,

success: function (res) {

console.log('Android搜索成功');

console.log(res);

},

fail: function (err) {

console.log(err);

wx.hideLoading();

that.startBluetoothDevicesDiscovery();

// that.getBluetoothAdapterState();

util.showToast('搜索失败');

}

});

}

},

startConnectDevices: function (ltype, array) {

var that = this;

clearTimeout(that.getConnectedTimer);

that.getConnectedTimer = null;

wx.stopBluetoothDevicesDiscovery({

success: function (res) {

// success

}

})

app.globalData.ble_isonnectting = true;

console.log('连接前:'+that.deviceId);

wx.createBLEConnection({

deviceId: that.deviceId,

success: function (res) {

if (res.errCode == 0) {

console.log('连接成功:');

that.getService(that.deviceId);

}

},

fail: function (err) {

console.log('连接失败:', err);

wx.hideLoading();

util.showModal('设备连接失败,请重试');

// if (ltype == 'loop') {

// that.connectDeviceIndex += 1;

// that.loopConnect(array);

// } else {

// that.startBluetoothDevicesDiscovery();

// that.getConnectedBluetoothDevices();

// }

app.globalData.ble_isonnectting = false;

},

complete: function () {

}

});

},

getService: function (deviceId) {

var that = this;

// 监听蓝牙连接

wx.onBLEConnectionStateChange(function (res) {

console.log(res);

app.globalData.ble_isonnectting = res.connected

if (!res.connected) {

util.showToast('连接断开');

}

});

// 获取蓝牙设备service值

wx.getBLEDeviceServices({

deviceId: deviceId,

success: function (res) {

console.log('获取蓝牙设备service值');

console.log(res);

that.getCharacter(deviceId, res.services);

}

})

},

getCharacter: function (deviceId, services) {

var that = this;

services.forEach(function (value, index, array) {

if (value.isPrimary) {

that.setData({

service_uuid: value.uuid,

deviceId: deviceId

})

app.globalData.service_uuid= value.uuid;

app.globalData.deviceId=deviceId;

}

});

//监听通知

wx.onBLECharacteristicValueChange(function (res) {

// callback

console.log('value change', res)

const hex = bletool.buf2char(res.value)

console.log('返回的数据:', hex)

//配对密码

if (hex.indexOf('855800000106') != -1) {

wx.hideLoading();

var charact_write = that.data.characteristics[1]

bletool.writeDataToDevice(that.data.deviceId, that.data.service_uuid, charact_write, that.data.service_psd);

wx.showToast({

title: '设备已连接',

icon: 'success',

duration: 3000

})

setTimeout(function () {

bletool.writeDataToDevice(that.data.deviceId, that.data.service_uuid, charact_write, '235525B837253705590400000273');

}, 2000)

} else if (hex.indexOf('23040000') != -1) {

//启动成功

that.starRenting();

}

})

wx.getBLEDeviceCharacteristics({

deviceId: deviceId,

serviceId: that.getServiceUUID(),

success: function (res) {

wx.getBLEDeviceCharacteristics({

deviceId: deviceId,

serviceId: that.getServiceUUID(),

success: function (res) {

console.log('特征', res)

that.setData({

characteristics:res.characteristics

})

app.globalData.characteristics = res.characteristics;

var charact_read = res.characteristics[0]

},

loopConnect: function (devicesId) {

var that = this;

var listLen = devicesId.length;

if (devicesId[this.connectDeviceIndex]) {

this.deviceId = devicesId[this.connectDeviceIndex];

this.startConnectDevices('loop', devicesId);

} else {

console.log('已配对的设备小程序蓝牙连接失败');

that.startBluetoothDevicesDiscovery();

that.getConnectedBluetoothDevices();

}

},

//更新数据 devices为数组类型

updateBleList: function (devices) {

console.log('设备数据:',devices);

var newData = this.data.bleList

var that = this

var tempDevice = null;

for (var i = 0; i devices.length; i++) {

//ios设备

if (devices[i].devices != null) {

if (devices[i].devices.length 0) {

tempDevice = devices[i].devices[0];

}

else {

continue

}

}

//安卓

else {

tempDevice = devices[i];

}

if (!this.isExist(tempDevice)) {

newData.push(tempDevice)

}

}

console.log('数据:');

console.log(newData)

this.setData({

bleList: newData

})

if (!app.globalData.ble_isonnectting) {

var that = this;

this.data.bleList.forEach(function (value, index, array) {

//找到对应id的设备,ios判断服务id安卓判断mac地址

var deviceId = value['deviceId'];

if(bletool.isIOS()){

let advertisServiceUUID = value['advertisServiceUUIDs'][0];

if (advertisServiceUUID == that.data.serviceId.toUpperCase()){

that.deviceId = deviceId;

console.log(that.deviceId);

that.startConnectDevices();

}

}else{

if (deviceId == that.data.serviceMac) {

that.deviceId = deviceId;

console.log(that.deviceId);

that.startConnectDevices();

}

}

});

}

},

//是否已存在 存在返回true 否则false

isExist: function (device) {

var tempData = this.data.bleList

for (var i = 0; i tempData.length; i++) {

if (tempData[i].deviceId == device.deviceId) {

return true

}

}

return false

},

//服务uuid

getServiceUUID: function () {

return bletool.stringTransition(this.data.service_uuid);

},

getDeviceInfo: function () {

let car_no = app.globalData.car_no;

var that = this;

wx.request({

url: app.globalData.serverURL + '?c=cara=getDeviceInfoopen_id=' + app.globalData.open_id + 'car_no=' + car_no,

method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT

header: { 'content-type': 'application/json' }, // 设置请求的 header

success: function (res) {

// success

var data = res.data;

console.log(data);

if (data.result == 1) {

app.globalData.serviceId = data.data.service_id;

app.globalData.serviceMac = data.data.service_mac,

app.globalData.service_psd = '85' + data.data.service_psd + '5800000329';

that.setData({

serviceId: data.data.service_id,

serviceMac: data.data.service_mac,

service_psd: '85' + data.data.service_psd+'5800000329',

})

app.startBluetoothDevicesDiscovery();

// that.onBLECharacteristicValueChange();

} else {

util.showModal(data.msg);

}

},

fail: function () {

},

complete: function () {

// complete

}

});

},

})

小程序 蓝牙连接

//初始化蓝牙

initBlue() {

var that = this;

wx.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口

success: function (res) {

console.log('1.初始化蓝牙成功')

},

//监听手机蓝牙的开关

monitorTheBlue:function(){

var that =this;

wx.onBluetoothAdapterStateChange(function(res){

})

},

//开始获取附近的蓝牙设备

//. 获取到附近的蓝牙数组 通过蓝牙特定的名称获取自己想要连接的蓝牙设备

//. 获取附近蓝牙设备的数组

findBlue() {

console.log(new Date())

var that = this

wx.startBluetoothDevicesDiscovery({

allowDuplicatesKey: false,

interval: 0,

success: function (res) {

console.log('2.正在搜索设备.............')

if (that.data.isFirestShow) {

wx.showLoading({

title: '正在搜索设备'

})

}

},

//搜索获取附近的所有蓝牙设备 获取附近所有的蓝牙设备的相关信息 获取需要连接蓝牙设备的deviceID

//. 通过bluetoothDeviceName 和 localName 来确定制定蓝牙

//. 一般根据制定设备的名字去连接 设备的名字 是出产厂家设定

getBlue() {

var that = this

wx.getBluetoothDevices({

success: function (res) {

console.log('3.找到设备列表........')

wx.hideLoading()

// return false

var index = 10

for (var i = 0; i res.devices.length; i++) {

if (res.devices[i].name res.devices[i].localName) {

var arr = res.devices[i].name.split("-")

var secArr = res.devices[i].localName.split("-")

if (arr[0] == that.data.bluetoothDeviceName || secArr[0] == that.data.bluetoothDeviceName) {

},

//连接蓝牙设备

//通过deviceId 连接蓝牙

/**

},

//6 连接上需要的蓝牙设备之后,获取这个蓝牙设备的服务uuid

//获取设备的uuid

getServiceId() {

var that = this

wx.getBLEDeviceServices({

// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接

deviceId: that.data.deviceId,

success: function (res) {

var model = res.services[1]

that.setData({

servicesUUID: model.uuid

})

console.log('7.获取设备 uuid 成功....')

that.getCharacteId() //6.0

}

})

},

//7 如果一个蓝牙设备需要进行数据的写入以及数据传输,就必须具有某些特征值,所以通过上面步骤获取的id可以查看当前蓝牙设备的特征值

//notify write read 当只有 notify为true的时候才能 接收蓝牙设备传来的数据,

//write 为true 才能传入数据

//read 为true 才能读取设备数据

getCharacteId() {

var that = this

wx.getBLEDeviceCharacteristics({

// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接

deviceId: that.data.deviceId,

// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取

serviceId: that.data.servicesUUID,

success: function (res) {

for (var i = 0; i res.characteristics.length; i++) { //2个值

var model = res.characteristics[i]

if (model.properties.notify == true) {

that.setData({

characteristicId: model.uuid //监听的值

})

console.log('8.model.properties.notify == true')

that.startNotice(model.uuid) //7.0

}

// if (model.properties.read == true) {

// that.readData(model.uuid)

// }

// if (model.properties.write == true) {

// that.setData({

// writeId: model.uuid//用来写入的值

// })

// }

}

}

})

},

fordateTime1(){

let now = new Date(),hour = now.getHours()

console.log(hour)

let str = ''

if(hour 7){str = '早餐前'}

else if ((7 hour) (hour= 9)){str = '早餐后'}

else if ((9 hour) (hour= 11)){str = '午餐前'}

else if ((11 hour) (hour= 13)){str = '午餐后'}

else if ((13 hour) (hour= 17)){str = '晚餐前'}

else if ((17 hour) (hour= 19)){str = '晚餐后'}

else if ((19 hour) (hour= 24)){str = '睡觉前'}

return str

},

//8 如果一个蓝牙设备需要进行数据的写入以及数据传输,就必须具有某些特征值,所以通过上面步骤获取的id可以查看当前蓝牙设备的特征值

//开启设备数据监听 监听蓝牙设备返回来的数据

startNotice(uuid) {

var that = this;

wx.notifyBLECharacteristicValueChanged({

state: true, // 启用 notify 功能

deviceId: that.data.deviceId,

serviceId: that.data.servicesUUID,

characteristicId: uuid, //第一步 开启监听 notityid 第二步发送指令 write

success: function (res) {

// that.closeConnect(that.data.deviceId)

// 设备返回的方法

let tip = 0

wx.onBLECharacteristicValueChange(res1 = {

},

/**

//监听蓝牙设备是否会异常断开

getTheBlueDisConnectWithAccident() {

},

// 断开设备连接

closeConnect: function(v) {

var that = this

if (v) {

wx.closeBLEConnection({

deviceId: v,

success: function(res) {

console.log("蓝牙断开连接")

that.closeBluetoothAdapter()

},

fail(res) {

}

})

} else {

that.closeBluetoothAdapter()

}

},

// 关闭蓝牙模块

closeBluetoothAdapter:function () {

wx.closeBluetoothAdapter({

success: function(res) {

console.log("关闭蓝牙模块")

},

fail: function(err) {

}

})

},

断网了,如何让微信小程序,可以用蓝牙

微信小程序怎么实现蓝牙连接?(代码示例)

微信小程序 2022-03-13

微信小程序如何实现蓝牙连接?本篇文章给大家带来的内容是介绍微信小程序实现蓝牙连接的方法(步骤)。有一定的参考价值,有需要的朋友可以参考一下,希望对你们有所帮助。

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

1、初始化蓝牙设备

一般使用蓝牙功能肯定是想连接某一个蓝牙设备,所以需要知道这个蓝牙设备的名称,一般来说都是扫描二维码连接,那么当你扫描这个设备二维码的时候,就需要去初始化你手机上的蓝牙模块了

/**

* 初始化蓝牙设备

*/

initBlue:function(){

var that = this;

wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口

success: function (res) {

// console.log(res)

wx.showToast({

title: '初始化成功',

icon: 'success',

duration: 800

})

that.findBlue();//2.0

},

fail: function (res) {//如果手机上的蓝牙没有打开,可以提醒用户

wx.showToast({

title: '请开启蓝牙',

icon: 'fails',

duration: 1000

})

}

})

},

2、搜索蓝牙设备

手机蓝牙初始化成功之后,就会去搜索周边的蓝牙设备

/**

*开始搜索蓝牙设备

*/

findBlue(){

var that = this

wx.startBluetoothDevicesdiscovery({

allowDuplicatesKey: false,

interval: 0,

success: function (res) {

微信小程序如何获取本机蓝牙mac地址

流程是这样的:先初始化蓝牙适配器,然后获取本机蓝牙适配器的状态,然后开始搜索,当停止搜索以后在开始搜索,就会触发蓝牙是配置状态变化的事件,搜索完成以后获取所有已经发现的蓝牙设备,就可以将devices中的设备Array取出来了。然后就可以得到所有已经连接的设备了,至于链接功能,还没有真机可测,所以没有测试。

我的电脑上蓝牙连接的设备:

以下是案例代码:

// pages/bluetooth/bluetooth.js

Page({

data:{},

onLoad:function(options){

// 页面初始化 options为页面跳转所带来的参数

},

//初始化蓝牙适配器

openBluetooth:function(){

wx.openBluetoothAdapter({

success: function(res){

console.log(res.errMsg)

// success

wx.showToast({

title:"初始化蓝牙适配器成功",

duration:2000

})

},

})

},

//关闭蓝牙模块

closeBluetooth:function(){

wx.openBluetoothAdapter()

wx.closeBluetoothAdapter({

success: function(res){

// success

console.log("success"+res)

}

})

},

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

getBluetoothAdapterState:function(){

wx.getBluetoothAdapterState({

success: function(res){

// success

console.log("res:"+res)

console.log("errMsg:"+res.errMsg)

}

})

},

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

onBluetoothAdapterStateChange:function(){

wx.onBluetoothAdapterStateChange(function(res) {

console.log(`adapterState changed, now is`, res)

})

},

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

startBluetoothDevicesDiscovery:function(){

wx.startBluetoothDevicesDiscovery({

success: function (res) {

console.log(res)

}

})

},

// 停止搜寻附近的蓝牙外围设备

stopBluetoothDevicesDiscovery:function(){

wx.stopBluetoothDevicesDiscovery({

success: function (res) {

console.log(res)

}

})

},

//获取所有已发现的蓝牙设备

getBluetoothDevices:function(){

wx.getBluetoothDevices({

success: function(res){

// success

console.log(res)

},

})

},

//监听寻找到新设备的事件

onBluetoothDeviceFound:function(){

wx.onBluetoothDeviceFound(function(res) {

// callback

console.log(res)

})

},

//根据 uuid 获取处于已连接状态的设备

getConnectedBluetoothDevices:function(){

wx.getConnectedBluetoothDevices({

success: function (res) {

console.log(res)

}

})

},

//连接低功耗蓝牙设备

createBLEConnection:function(){

wx.createBLEConnection({

deviceId: 'AC:BC:32:C1:47:80',

success: function(res){

// success

console.log(res)

},

fail: function(res) {

// fail

},

complete: function(res) {

// complete

}

})

},

//断开与低功耗蓝牙设备的连接

closeBLEConnection:function(){

wx.closeBLEConnection({

deviceId: 'AC:BC:32:C1:47:80',

success: function (res) {

console.log(res)

}

})

},

//监听低功耗蓝牙连接的错误事件,包括设备丢失,连接异常断开等等

onBLEConnectionStateChanged:function(){

wx.onBLEConnectionStateChanged(function(res) {

console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)

})

},

//获取蓝牙设备所有 service(服务)

getBLEDeviceServices:function(){

wx.getBLEDeviceServices({

deviceId: '48:3B:38:88:E3:83',

success: function(res){

// success

console.log('device services:', res.services.serviceId)

},

fail: function(res) {

// fail

},

complete: function(res) {

// complete

}

})

},

//获取蓝牙设备所有 characteristic(特征值)

getBLEDeviceCharacteristics:function(){

wx.getBLEDeviceCharacteristics({

deviceId: '48:3B:38:88:E3:83',

serviceId: 'serviceId',

success: function(res){

// success

},

fail: function(res) {

// fail

},

complete: function(res) {

// complete

}

})

}

})

微信小程序蓝牙教程--完整版亲测

#使用mpvue 开发小程序过程中 简单介绍一下微信小程序蓝牙连接过程

#在蓝牙连接的过程中部分api需要加定时器延时1秒到2秒左右再执行,原因为何不知道,小程序有这样的要求

#1.首先是要初始化蓝牙:openBluetoothAdapter()

```js

if (wx.openBluetoothAdapter) {

wx.openBluetoothAdapter({

        success: function(res) {

            /* 获取本机的蓝牙状态 */

            setTimeout(() = {

                getBluetoothAdapterState()

            }, 1000)

        },

        fail: function(err) {

            // 初始化失败

        }

    })

    } else {    

    }

```

#2.检测本机蓝牙是否可用:

#  要在上述的初始化蓝牙成功之后回调里调用

```js

getBluetoothAdapterState() {

    var that= this;

    that.toastTitle= '检查蓝牙状态'

wx.getBluetoothAdapterState({

        success: function(res) {

startBluetoothDevicesDiscovery()

},

        fail(res) {

            console.log(res)

}

})

}

```

#3. 开始搜索蓝牙设备:

```js

startBluetoothDevicesDiscovery() {

    var that= this;

    setTimeout(() = {

wx.startBluetoothDevicesDiscovery({

            success: function(res) {

/* 获取蓝牙设备列表 */

                that.getBluetoothDevices()

},

            fail(res) {

}

})

}, 1000)

}

```

#4. 获取搜索到的蓝牙设备列表

# /* that.deviceName 是获取到的蓝牙设备的名称, 因为蓝牙设备在安卓和苹果手机上搜到的蓝牙地址显示是不一样的,所以根据设备名称匹配蓝牙*/

```js

getBluetoothDevices() {

    var that= this;

    setTimeout(() = {

wx.getBluetoothDevices({

            services: [],

            allowDuplicatesKey: false,

            interval: 0,

            success: function(res) {

                if (res.devices.length 0) {

                    if (JSON.stringify(res.devices).indexOf(that.deviceName) !== -1) {

                        for (let i = 0; i res.devices.length; i++) {

                            if (that.deviceName === res.devices[i].name) {

/* 根据指定的蓝牙设备名称匹配到deviceId */

                                that.deviceId = that.devices[i].deviceId;

                                setTimeout(() = {

                                    that.connectTO();

}, 2000);

};

};

} else {

}

} else {

}

},

            fail(res) {

                console.log(res, '获取蓝牙设备列表失败=====')

}

})

}, 2000)

},

```

#5.连接蓝牙

# 匹配到的蓝牙设备ID 发送连接蓝牙的请求, 连接成功之后 应该断开蓝牙搜索的api,然后去获取所连接蓝牙设备的service服务

```js

connectTO() {

wx.createBLEConnection({

        deviceId: deviceId,

        success: function(res) {

            that.connectedDeviceId = deviceId;

/* 4.获取连接设备的service服务 */

that.getBLEDeviceServices();

wx.stopBluetoothDevicesDiscovery({

                success: function(res) {

                    console.log(res, '停止搜索')

},

                fail(res) {

}

})

},

        fail: function(res) {

}

})

}

```

#6. 获取蓝牙设备的service服务,获取的serviceId有多个要试着连接最终确定哪个是稳定版本的service 获取服务完后获取设备特征值

```js

getBLEDeviceServices() {

    setTimeout(() = {

wx.getBLEDeviceServices({

            deviceId: that.connectedDeviceId,

            success: function(res) {

                that.services= res.services

/* 获取连接设备的所有特征值 */

that.getBLEDeviceCharacteristics()

},

            fail: (res) = {

}

})

}, 2000)

},

```

#7.获取蓝牙设备特征值

# 获取到的特征值有多个,最后要用的事能读,能写,能监听的那个值的uuid作为特征值id,

```js

getBLEDeviceCharacteristics() {

            setTimeout(() = {

wx.getBLEDeviceCharacteristics({

                    deviceId: connectedDeviceId,

                    serviceId: services[2].uuid,

                    success: function(res) {

                        for (var i = 0; i res.characteristics.length; i++) {

                            if ((res.characteristics[i].properties.notify || res.characteristics[i].properties.indicate)

                                (res.characteristics[i].properties.read res.characteristics[i].properties.write)) {

                                console.log(res.characteristics[i].uuid, '蓝牙特征值 ==========')

/* 获取蓝牙特征值 */

                                that.notifyCharacteristicsId = res.characteristics[i].uuid

// 启用低功耗蓝牙设备特征值变化时的 notify 功能

that.notifyBLECharacteristicValueChange()

}

}

},

                    fail: function(res) {

}

})

}, 1000)

},

```

#8.启动notify 蓝牙监听功能 然后使用 wx.onBLECharacteristicValueChange用来监听蓝牙设备传递数据

#接收到的数据和发送的数据必须是二级制数据, 页面展示的时候需要进行转换

```js

notifyBLECharacteristicValueChange() { // 启用低功耗蓝牙设备特征值变化时的 notify 功能

            var that= this;

            console.log('6.启用低功耗蓝牙设备特征值变化时的 notify 功能')

wx.notifyBLECharacteristicValueChange({

                state: true,

                deviceId: that.connectedDeviceId,

                serviceId: that.notifyServicweId,

                characteristicId: that.notifyCharacteristicsId,

                complete(res) {

/*用来监听手机蓝牙设备的数据变化*/

wx.onBLECharacteristicValueChange(function(res) {

/**/

                        that.balanceData += that.buf2string(res.value)

                        that.hexstr += that.receiveData(res.value)

})

},

                fail(res) {

                    console.log(res, '启用低功耗蓝牙设备监听失败')

                    that.measuringTip(res)

}

})

},

/*转换成需要的格式*/

buf2string(buffer) {

                    var arr = Array.prototype.map.call(new Uint8Array(buffer), x = x)

                    return arr.map((char, i) = {

                        return String.fromCharCode(char);

                    }).join('');

},

receiveData(buf) {

return this.hexCharCodeToStr(this.ab2hex(buf))

},

/*转成二进制*/

ab2hex (buffer) {

              var hexArr = Array.prototype.map.call(

                  new Uint8Array(buffer), function (bit) {

                      return ('00' + bit.toString(16)).slice(-2)

}

)

              return hexArr.join('')

},

/*转成可展会的文字*/

hexCharCodeToStr(hexCharCodeStr) {

              var trimedStr = hexCharCodeStr.trim();

              var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;

              var len = rawStr.length;

              var curCharCode;

              var resultStr= [];

              for (var i = 0; i len; i = i+ 2) {

                  curCharCode = parseInt(rawStr.substr(i, 2), 16);

                  resultStr.push(String.fromCharCode(curCharCode));

}

              return resultStr.join('');

},

```

# 向蓝牙设备发送数据

```js

sendData(str) {

    let that= this;

    let dataBuffer = new ArrayBuffer(str.length)

    let dataView = new DataView(dataBuffer)

    for (var i = 0; i str.length; i++) {

        dataView.setUint8(i, str.charAt(i).charCodeAt())

}

    let dataHex = that.ab2hex(dataBuffer);

    this.writeDatas = that.hexCharCodeToStr(dataHex);

wx.writeBLECharacteristicValue({

        deviceId: that.connectedDeviceId,

        serviceId: that.notifyServicweId,

        characteristicId: that.notifyCharacteristicsId,

        value: dataBuffer,

        success: function (res) {

            console.log('发送的数据:' + that.writeDatas)

            console.log('message发送成功')

},

        fail: function (res) {

},

        complete: function (res) {

}

})

},

```

# 当不需要连接蓝牙了后就要关闭蓝牙,并关闭蓝牙模块

```js

// 断开设备连接

closeConnect() {

if (that.connectedDeviceId) {

wx.closeBLEConnection({

            deviceId: that.connectedDeviceId,

            success: function(res) {

that.closeBluetoothAdapter()

},

            fail(res) {

}

})

} else {

that.closeBluetoothAdapter()

}

},

// 关闭蓝牙模块

closeBluetoothAdapter() {

wx.closeBluetoothAdapter({

        success: function(res) {

},

        fail: function(err) {

}

})

},

```

#在向蓝牙设备传递数据和接收数据的过程中,并未使用到read的API 不知道有没有潜在的问题,目前线上运行为发现任何的问题

#今天的蓝牙使用心得到此结束,谢谢

关于微信小程序蓝牙源代码和微信小程序蓝牙模块的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

版权说明:如非注明,本站文章均为 AH站长 原创,转载请注明出处和附带本文链接;

本文地址:http://ahzz.com.cn/post/24708.html


取消回复欢迎 发表评论:

分享到

温馨提示

下载成功了么?或者链接失效了?

联系我们反馈

立即下载