微信小程序蓝牙接口的实现。
实现安卓和IOS系统给蓝牙模块发送指令。
//index.js
//获取应用实例
var app = getApp();
var devices_list = []
Page({
data: {
status: "",
sousuo: "",
connectedDeviceId: "", //已连接设备uuid
services: "", // 连接设备的服务
characteristics: "", // 连接设备的状态值
writeServicweId: "", // 可写服务uuid
writeCharacteristicsId: "",//可写特征值uuid
readServicweId: "", // 可读服务uuid
readCharacteristicsId: "",//可读特征值uuid
notifyServicweId: "", //通知服务UUid
notifyCharacteristicsId: "", //通知特征值UUID
inputValue: "",
characteristics1: "", // 连接设备的状态值
},
onLoad: function () {
if (wx.openBluetoothAdapter) {
wx.openBluetoothAdapter()
} else {
// 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示
wx.showModal({
title: '提示',
content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
})
}
//打开蓝牙适配
var that = this;
this.lanya4();
},
// 初始化蓝牙适配器
lanya1: function () {
var that = this;
wx.openBluetoothAdapter({
success: function (res) {
that.setData({
msg: "初始化蓝牙适配器成功!" + JSON.stringify(res),
})
//监听蓝牙适配器状态
wx.onBluetoothAdapterStateChange(function (res) {
if (!res.available) {
wx.showModal({
title: '提示',
content: '请打开蓝牙!'
})
}
if (!res.discovering) {
wx.showModal({
title: '提示',
content: '已停止设备搜索'
})
}
})
}
})
},
// 本机蓝牙适配器状态
lanya2: function () {
var that = this;
wx.getBluetoothAdapterState({
success: function (res) {
if (!res.available) {
wx.showModal({
title: '提示',
content: '请打开蓝牙!'
})
}
//监听蓝牙适配器状态
wx.onBluetoothAdapterStateChange(function (res) {
if (!res.available) {
wx.showModal({
title: '提示',
content: '请打开蓝牙!'
})
}
})
}
})
},
//搜索设备
lanya3: function () {
var that = this;
wx.startBluetoothDevicesDiscovery({
success: function (res) {
that.setData({
msg: "搜索设备" + JSON.stringify(res),
})
//监听蓝牙适配器状态
wx.onBluetoothAdapterStateChange(function (res) {
if (!res.available) {
wx.showModal({
title: '提示',
content: '请打开蓝牙!'
})
}
})
}
})
},
// 获取所有已发现的设备
ab2hex: function (buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}, buf2hex: function (buffer) {
return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
},
lanya4: function () {
var that = this;
that.lanya2();
that.lanya3();
wx.getBluetoothDevices({
success: function (res) {
//是否有已连接设备
wx.getConnectedBluetoothDevices({
success: function (res) {
that.setData({
connectedDeviceId: res.deviceId
})
}
})
that.setData({
msg: "搜索设备" + JSON.stringify(res.devices),
devices: res.devices,
})
//监听蓝牙适配器状态
wx.onBluetoothAdapterStateChange(function (res) {
that.setData({
sousuo: res.discovering ? "在搜索。" : "未搜索。",
status: res.available ? "可用。" : "不可用。",
})
})
}
})
},
//停止搜索周边设备
lanya5: function () {
var that = this;
wx.stopBluetoothDevicesDiscovery({
success: function (res) {
that.setData({
msg: "停止搜索周边设备" + "/" + JSON.stringify(res.errMsg),
sousuo: res.discovering ? "在搜索。" : "未搜索。",
status: res.available ? "可用。" : "不可用。",
})
}
})
},
//连接设备
connectTO: function (e) {
var that = this;
that.lanya5();
wx.createBLEConnection({
deviceId: e.currentTarget.id,
success: function (res) {
console.log(res.errMsg);
that.setData({
connectedDeviceId: e.currentTarget.id,
msg: "已连接" + e.currentTarget.id,
msg1: "",
})
},
fail: function () {
console.log("调用失败");
},
complete: function () {
console.log("调用结束");
}
})
console.log(that.data.connectedDeviceId);
},
// 获取连接设备的service服务
lanya6: function () {
var that = this;
that.lanya5();
wx.getBLEDeviceServices({
// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: that.data.connectedDeviceId,
success: function (res) {
console.log('device services:', JSON.stringify(res.services));
that.setData({
services: res.services,
msg: JSON.stringify(res.services),
})
}
})
},
//获取连接设备的所有特征值 for循环获取不到值
lanya7: function () {
var that = this;
this.lanya6();
wx.getBLEDeviceCharacteristics({
// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: that.data.connectedDeviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
//serviceId: that.data.services[0].uuid,
serviceId: "6E400001-B5A3-F393-E0A9-E50E24DCCA9E",
success: function (res) {
for (var i = 0; i < res.characteristics.length; i++) {
if (res.characteristics[i].uuid.indexOf("6E400003") == 0) {
that.setData({
writeServicweId: that.data.services[0].uuid,
writeCharacteristicsId: res.characteristics[i].uuid,
})
}
}
console.log("service iD ", that.data.services[0].uuid);
console.log('device getBLEDeviceCharacteristics:', res.characteristics);
that.setData({
msg: JSON.stringify(res.characteristics),
})
},
fail: function () {
console.log("fail");
},
complete: function () {
console.log("complete");
}
})
},
//断开设备连接
lanya0: function () {
var that = this;
wx.closeBLEConnection({
deviceId: that.data.connectedDeviceId,
success: function (res) {
that.setData({
connectedDeviceId: "",
})
}
})
},
//启用低功耗蓝牙设备特征值变化时的 notify 功能
lanya9: function () {
var that = this;
//var notifyServicweId = that.data.notifyServicweId.toUpperCase();
//var notifyCharacteristicsId = that.data.notifyCharacteristicsId.toUpperCase();
//console.log("11111111", notifyServicweId);
//console.log("22222222222222222", notifyCharacteristicsId);
wx.notifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: that.data.connectedDeviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
serviceId: that.data.notifyServicweId,
// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
characteristicId: that.data.notifyCharacteristicsId,
success: function (res) {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
},
fail: function () {
console.log('shibai');
console.log(that.data.notifyServicweId);
console.log(that.data.notifyCharacteristicsId);
},
})
},
//监听input表单
inputTextchange: function (e) {
this.setData({
inputValue: e.detail.value
})
},
//发送数据
lanya8: function () {
var that = this;
// 向蓝牙设备发送一个0x00的16进制数据
let buffer = new ArrayBuffer(1)
buffer[0] = "a#";
let dataView = new DataView(buffer)
dataView.setUint8(0, 0)
console.log("buffer=", buffer);
// 这里的回调可以获取到 write 导致的特征值改变
wx.onBLECharacteristicValueChange(function (characteristic) {
console.log('characteristic value changed:1', characteristic)
})
console.log("characteristicId=", that.data.writeCharacteristicsId);
function send() {
wx.writeBLECharacteristicValue({
// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: that.data.connectedDeviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
serviceId: that.data.writeServicweId,
// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
characteristicId: that.data.writeCharacteristicsId,
// 这里的value是ArrayBuffer类型
value: buffer,
success: function (res) {
console.log('发送成功 success', res.errMsg)
},
fail: function (res) {
// fail
console.log('发送失败 fail', res);
}
})
}
setTimeout(send, 3000);
},
hexStringToArrayBuffer: function (str) {
if (!str) {
return new ArrayBuffer(0);
}
var buffer = new ArrayBuffer(str.length);
let dataView = new DataView(buffer)
let ind = 0;
for (var i = 0, len = str.length; i < len; i += 2) {
let code = parseInt(str.substr(i, 2), 16)
dataView.setUint8(ind, code)
ind++
}
return buffer;
},
//前进
lanyaN: function () {
var that = this;
this.lanya7();
let buffer = new ArrayBuffer(3);
let val1 = parseInt("23", 16);
let val2 = parseInt("3A", 16);
console.log("val1 = ", val1);
let dataView = new DataView(buffer);
dataView.setUint8(0, val1);
dataView.setUint8(1, val2);
dataView.setUint8(2, val1);
let UARTSERVICE_SERVICE_UUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E";
let UART_TX_CHARACTERISTIC_UUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E";
//let UART_TX_CHARACTERISTIC_UUID = "00002A26-0000-1000-8000-00805F9B34FB";
console.log('serviceId0 ===', UARTSERVICE_SERVICE_UUID);
console.log('serviceId1 ===', that.data.writeServicweId);
console.log('characteristicId0 ===', UART_TX_CHARACTERISTIC_UUID);
console.log('characteristicId1 ==', that.data.writeCharacteristicsId);
wx.writeBLECharacteristicValue({
deviceId: that.data.connectedDeviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
//serviceId: that.data.writeServicweId,
serviceId: UARTSERVICE_SERVICE_UUID,
// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
characteristicId: that.data.writeCharacteristicsId,
//characteristicId: UART_TX_CHARACTERISTIC_UUID,
// 这里的value是Arrayfffer类型
value: buffer,
success: function (res) {
console.log('发送成功 ok', res.errMsg);
},
fail: function (res) {
console.log('发送失败 fail', res.errMsg);
},
complete: function (res) {
console.log('writeBLECharacteristicValue complete', res.errMsg);
}
})
},
//向右
lanyaE: function () {
var that = this;
this.lanya7();
// 向蓝牙设备发送一个0x00的16进制数据
var that = this;
let buffer = new ArrayBuffer(3);
let val1 = parseInt("23", 16);
let val2 = parseInt("3A", 16);
console.log("val1 = ", val1);
let dataView = new DataView(buffer);
dataView.setUint8(0, val1);
dataView.setUint8(1, val2);
dataView.setUint8(2, val1);
let UARTSERVICE_SERVICE_UUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E";
let UART_TX_CHARACTERISTIC_UUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E";
//let UART_TX_CHARACTERISTIC_UUID = "00002A26-0000-1000-8000-00805F9B34FB";
console.log('serviceId0 ===', UARTSERVICE_SERVICE_UUID);
console.log('serviceId1 ===', that.data.writeServicweId);
console.log('characteristicId0 ===', UART_TX_CHARACTERISTIC_UUID);
console.log('characteristicId1 ==', that.data.writeCharacteristicsId);
wx.writeBLECharacteristicValue({
// 这里的 deviceId 需要在上面的 getuluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: that.data.connectedDeviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
//serviceId: that.data.writeServicweId,
serviceId: UARTSERVICE_SERVICE_UUID,
// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
characteristicId: that.data.writeCharacteristicsId,
//characteristicId: UART_TX_CHARACTERISTIC_UUID,
// 这里的value是Arrayfffer类型
value: buffer,
success: function (res) {
console.log('发送成功 ok', res.errMsg);
},
fail: function (res) {
console.log('发送失败 fail', res.errMsg);
},
complete: function (res) {
console.log('writeBLECharacteristicValue complete', res.errMsg);
}
})
setTimeout(send, 3000);
},
//向左
lanyaW: function () {
var that = this;
this.lanya7();
let buffer = new ArrayBuffer(3);
let val1 = parseInt("23", 16);
let val2 = parseInt("3A", 16);
console.log("val1 = ", val1);
let dataView = new DataView(buffer);
dataView.setUint8(0, val1);
dataView.setUint8(1, val2);
dataView.setUint8(2, val1);
let UARTSERVICE_SERVICE_UUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E";
let UART_TX_CHARACTERISTIC_UUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E";
//let UART_TX_CHARACTERISTIC_UUID = "00002A26-0000-1000-8000-00805F9B34FB";
console.log('serviceId0 ===', UARTSERVICE_SERVICE_UUID);
console.log('serviceId1 ===', that.data.writeServicweId);
console.log('characteristicId0 ===', UART_TX_CHARACTERISTIC_UUID);
console.log('characteristicId1 ==', that.data.writeCharacteristicsId);
wx.writeBLECharacteristicValue({
deviceId: that.data.connectedDeviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
//serviceId: that.data.writeServicweId,
serviceId: UARTSERVICE_SERVICE_UUID,
// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
characteristicId: that.data.writeCharacteristicsId,
//characteristicId: UART_TX_CHARACTERISTIC_UUID,
// 这里的value是Arrayfffer类型
value: buffer,
success: function (res) {
console.log('发送成功 ok', res.errMsg);
},
fail: function (res) {
console.log('发送失败 fail', res.errMsg);
},
complete: function (res) {
console.log('writeBLECharacteristicValue complete', res.errMsg);
}
})
setTimeout(send, 3000);
},
//后退
lanyaS: function () {
var that = this;
this.lanya7();
let buffer = new ArrayBuffer(3);
let val1 = parseInt("23", 16);
let val2 = parseInt("3A", 16);
console.log("val1 = ", val1);
let dataView = new DataView(buffer);
dataView.setUint8(0, val1);
dataView.setUint8(1, val2);
dataView.setUint8(2, val1);
let UARTSERVICE_SERVICE_UUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E";
let UART_TX_CHARACTERISTIC_UUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E";
//let UART_TX_CHARACTERISTIC_UUID = "00002A26-0000-1000-8000-00805F9B34FB";
console.log('serviceId0 ===', UARTSERVICE_SERVICE_UUID);
console.log('serviceId1 ===', that.data.writeServicweId);
console.log('characteristicId0 ===', UART_TX_CHARACTERISTIC_UUID);
console.log('characteristicId1 ==', that.data.writeCharacteristicsId);
wx.writeBLECharacteristicValue({
// 这里的 deviceId 需要在上面的 getuluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: that.data.connectedDeviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
//serviceId: that.data.writeServicweId,
serviceId: UARTSERVICE_SERVICE_UUID,
// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
characteristicId: that.data.writeCharacteristicsId,
//characteristicId: UART_TX_CHARACTERISTIC_UUID,
// 这里的value是Arrayfffer类型
value: buffer,
success: function (res) {
console.log('发送成功 ok', res.errMsg);
},
fail: function (res) {
console.log('发送失败 fail', res.errMsg);
},
complete: function (res) {
console.log('writeBLECharacteristicValue complete', res.errMsg);
}
})
setTimeout(send, 3000);
},
//接收消息
lanya10: 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("characteristic.value==", characteristic);
console.log("hex==", hex);
wx.request({
url: 'http://edu.eggtoy.com/getDecrypt',
data: { hexString: hex },
method: "POST",
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: function (data) {
//console.log(data)
console.log("data==", data.data.data);
var res = data.data.data;
that.setData({
jieshou: res,
})
}
})
})
console.log(that.data.readServicweId);
console.log(that.data.readCharacteristicsId);
wx.readBLECharacteristicValue({
// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: that.data.connectedDeviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
serviceId: that.data.readServicweId,
// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
characteristicId: that.data.readCharacteristicsId,
success: function (res) {
console.log('readBLECharacteristicValue:', res.errMsg);
}
})
},
})