wxml
<van-nav-bar title="" left-text="蓝牙测试" left-arrow bind:click-left="onClickLeft" />
<button type="primary" style="width: 100%;" bind:tap="createBLE">创建服务模式(从机广播)</button>
<button type="primary" style="width: 100%;margin-top: 5px;" bind:tap="stopAdvertising">停止广播</button>
<view>
<canvas type="2d" style="width:700rpx; height: 700rpx;margin:50rpx auto" id="myQrcode"></canvas>
</view>
js
import drawQrcode from 'weapp-qrcode-canvas-2d' // 微信小程序生成二维码 canvas-2d接口
Page({
data: {
Slave: '',
QRcodeImg: '',
server: null, //建立本地服务端返回的对象
value: '', //写的数据
},
// 生命周期函数--监听页面加载
onLoad() {
var res = wx.getSystemInfoSync()
if (res.platform == 'android') {
console.log('机型:android');
this.openBluetoothed()
} else {
console.log('111');
}
// 监听蓝牙设备连接状态变化
wx.onBLEPeripheralConnectionStateChanged((res) => {
console.log("连接成功后的返回值")
if (res.connected) {
wx.showToast({
title: '蓝牙设备已连接',
icon: 'success'
})
} else {
wx.showToast({
title: '蓝牙设备已断开',
icon: 'success'
})
}
});
},
// 初始化蓝牙模块。iOS 上开启主机/从机(外围设备)模式时需分别调用一次,并指定对应的 mode。
openBluetoothed() {
wx.openBluetoothAdapter({
mode: "peripheral",
success(res) {
console.log("成功:" + res.errMsg)
// 获取本机蓝牙适配器状态。
wx.getBluetoothAdapterState({
success(res) {
console.log("是否正在搜索设备:" + res.discovering)
console.log("蓝牙适配器是否可用:" + res.available)
}
})
}
})
},
// 创建从机服务端
createBLE() {
let _this = this
wx.createBLEPeripheralServer({
success: (res) => {
_this.setData({
Slave: "成功",
server: res.server
})
if (res.errMsg == "createBLEPeripheralServer:ok") {
wx.showToast({
title: '创建成功',
icon: 'success'
})
}
res.server.addService({
service: {
uuid: "000018f0-0000-1000-8000-00805f9b34fb",
characteristics: [{
uuid: "00002af0-0000-1000-8000-00805f9b34fb",
properties: {
read: true,
notify: true
},
permission: {
readable: true
},
value: _this.string2buffer("1234"),
},
{
uuid: "00002af1-0000-1000-8000-00805f9b34fb",
properties: {
writeNoResponse: true,
extendedProperties: true
},
permission: {
writeable: true
},
value: _this.string2buffer("4321"),
}
]
},
success(res) {
console.log('添加服务成功:', res);
_this.setOnRequest(); //监听读写操作
_this.startAdvertising(); //开启广播
},
fail(err) {
console.log('添加服务失败:', err)
}
});
}
})
},
setOnRequest() {
var that = this;
console.log("设置监听读写");
if (that.data.server) {
that.data.server.onCharacteristicWriteRequest(function callback(res) {
console.log('写入请求监听')
console.log("写入的数据:" + that.buf2string(res.value))
that.setData({
value: that.buf2string(res.value)
})
that.data.server.writeCharacteristicValue({
serviceId: res.serviceId,
characteristicId: res.characteristicId,
value: res.value,
needNotify: true,
callbackId: res.callbackId
})
})
that.data.server.onCharacteristicReadRequest(function callback(res) {
console.log('读取请求监听')
that.data.server.writeCharacteristicValue({
serviceId: res.serviceId,
characteristicId: res.characteristicId,
value: that.string2buffer("5555"),
needNotify: true,
callbackId: res.callbackId
})
})
}
},
buf2string(buffer) {
var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
var str = ''
for (var i = 0; i < arr.length; i++) {
str += String.fromCharCode(arr[i])
}
return str
},
string2buffer(str) {
// 首先将字符串转为16进制
let val = ""
for (let i = 0; i < str.length; i++) {
if (val === '') {
val = str.charCodeAt(i).toString(16)
} else {
val += ',' + str.charCodeAt(i).toString(16)
}
}
// 将16进制转化为ArrayBuffer
return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
})).buffer
},
startAdvertising() {
this.data.server.startAdvertising({
advertiseRequest: {
deviceName: "0804",
serviceUuids: ["000018f0-0000-1000-8000-00805f9b34fb"]
},
powerLevel: 'high',
success: res => {
if (res.errMsg == "startBLEPeripheralAdvertising:ok") {
wx.showToast({
title: '已开启广播',
icon: 'success'
})
}
const query = wx.createSelectorQuery()
query.select('#myQrcode')
.fields({
node: true,
size: true
})
.exec(async (res) => {
var canvas = res[0].node
console.log(res);
var img = canvas.createImage();
console.log(img);
img.src = "../../images/yinxinlogo.png" // logo图片
img.onload = function () {
// img.onload完成后才能调用 drawQrcode方法
var options = {
canvas: canvas, // 画布标识,传入canvas组件实例
canvasId: 'myQrcode', // 绘制的canvasId
width: 260, // 二维码宽度
padding: 30, // 空白内边距
paddingColor: '#fff', // 内边距颜色
background: '#fff', // 二维码背景颜色,默认值白色
foreground: '#000000', // 二维码前景色,默认值黑色
text: "1A2B3F4D", // 二维码内容 md5加密形式
}
drawQrcode(options) // 调用方法drawQrcode生成二维码
console.log("当前text长度为:" + options.text.length);
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 260,
height: 260,
destWidth: 600,
destHeight: 600,
canvasId: 'myQrcode',
canvas: canvas,
success(res) {
console.log(res);
console.log('二维码临时路径为:', res.tempFilePath);
// this.setData({
// QRcodeImg: res.tempFilePath
// })
},
fail(res) {
console.error(res)
}
})
};
})
},
fail: error => {
console.log("startAdvertising fail:" + JSON.stringify(error));
}
});
},
onClickLeft() {
wx.navigateBack({
delta: 1
})
},
// 停止广播
stopAdvertising() {
console.log("停止广播");
this.data.server.stopAdvertising({
success(res) {
console.log(res);
wx.showToast({
title: '广播已停止',
icon: 'success'
})
}
})
}
})