微信小程序实现蓝牙打印
最近刚好完成了一个打印标签的项目,其中就涉及到了小程序的蓝牙功能。所以写下这篇粗略的文章记录一下,同时也是给即将做相关项目的亲们提供一个参考,也希望有什么描述不恰当或者技术上不正确的地方大家可以指出,一起进步。
蓝牙打印只要按这九个步骤(前六个步骤连接蓝牙,后三个步骤打印数据)就可以搞定啦!步骤如下:
第一步:初始化蓝牙模块wx.openBluetoothAdapter
wx.openBluetoothAdapter({
success(res){
console.log(res)//res:{errMsg:"openBluetoothAdapter:ok"}
}
})
第二步:开始搜寻附近的蓝牙外围设备wx.startBluetoothDevicesDiscovery
wx.startBluetoothDevicesDiscovery({
//services:['FEE7'],只搜索主服务UUID为FEE7的设备,如果明确知道主服务UUID可以用此项做筛选
success(res){
console.log(res)//res:{errCode:0,errMsg:"startBluetoothDevicesDiscovery:ok",isDiscovering:true}
}
})
第三步:获取已搜素到的蓝牙设备列表wx.getBluetoothDevices
wx.getBluetoothDevices({
success:function(res){
console.log(res)//res:{errMsg:"getBluetoothDevices:ok",devices:Array(3)}
}
})
第四步:监听寻找到新设备的事件wx.onBluetoothDeviceFound(有时候会第三步会搜不到所以需要使用监听器去随时监听搜索到的蓝牙设备并返回给你)
wx.onBluetoothDeviceFound(function(res){
console.log(res)//res:{devices:Array(1)}
})
第五步:连接蓝牙设备wx.createBLEConnection
wx.createBLEConnection({
deviceId,//上面选择蓝牙设备的deviceId,例:连接第一个设备devices[0].deviceId
success(res){
console.log(res)//{errCode:0,errMsg:"createBLEConnection:ok"}
}
})
第六步:停止搜寻附近的蓝牙外围设备wx.stopBluetoothDevicesDiscovery(可以写在第五步成功回调之后,或者是
onUnload()函数里)
wx.stopBluetoothDevicesDiscovery({
success(res){
console.log(res)
}
})
第七步:获取蓝牙设备所有服务wx.getBLEDeviceServices
wx.getBLEDeviceServices({
deviceId,//已连接的蓝牙设备ID
success(res){
console.log(res)//{errMsg:"getBLEDeviceServices:ok",services:Array(5),errCode:0}
}
})
//这边获取到了5个服务
第八步:获取蓝牙设备中某一个服务的所有特征值wx.getBLEDeviceCharacteristics
varcharacteristics="";
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,//第七步的服务ID,
success(res){
//res:{errMsg:"getBLEDeviceCharacteristics:ok",characteristics:Array(4),errCode:0}
//characteristics[0].properties:{read:true,write:false,notify:false,indicate:false}
//特征值有好几种类型,我们这边打印需要的是item.properties.write为true的特征值
for(vari=0;i
第九步:向蓝牙设备特征值中写入数据wx.writeBLECharacteristicValue
wx.writeBLECharacteristicValue({
deviceId,
serviceId,
characteristicId,//上面保存的特征值
value:buffer,//这里的value是ArrayBuffer类型,中间层传过来的打印数据前端自己做转换,转换过程我这边就不描述了;
success(res){
console.log('writeBLECharacteristicValuesuccess',res.errMsg)
}
})
//特别提醒建议每次写入的buffer不超过20字节,超过会有写入错误的风险,所以一个打印的内容可能要拆成N个20字节的buffer去循环writeBLECharacteristicValue,这样就能打印成功啦。
附:
微信小程序官方文档
示例代码(uniapp实现小程序蓝牙打印简易流程)
另注:无论是原生、WePY、mpvue或uniapp、调用步骤都是一样的,不过调用API的前缀需要改成对应的就OK了
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
4 带猫的祝福语简短
10 新年祝福语给长辈简短
11 送女孩的简短祝福语
12 岁月祝福语简短10字
13 冬至祝福语简短情话高级
14 医师考试祝福语毕业简短
15 我老公蛋糕祝福语简短
16 送米的祝福语简短
17 爸爸生日祝福语搞笑简短
18 托班祝福语大全简短