微信小程序实现蓝牙打印

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

微信小程序实现蓝牙打印

泠青云   2020-05-17 我要评论

最近刚好完成了一个打印标签的项目,其中就涉及到了小程序的蓝牙功能。所以写下这篇粗略的文章记录一下,同时也是给即将做相关项目的亲们提供一个参考,也希望有什么描述不恰当或者技术上不正确的地方大家可以指出,一起进步。

蓝牙打印只要按这九个步骤(前六个步骤连接蓝牙,后三个步骤打印数据)就可以搞定啦!步骤如下:

第一步:初始化蓝牙模块 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

var characteristics="";
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 (var i = 0; i < res.characteristics.length; i++) {
 var item = res.characteristics[i];
 if (item.properties.write) {
 characteristics = item.uuid;
 }
 }
 //保存特征值
 }
})

第九步:向蓝牙设备特征值中写入数据 wx.writeBLECharacteristicValue

wx.writeBLECharacteristicValue({
 deviceId,
 serviceId,
 characteristicId,//上面保存的特征值
 value: buffer, // 这里的value是ArrayBuffer类型,中间层传过来的打印数据前端自己做转换,转换过程我这边就不描述了;
 success (res) {
 console.log('writeBLECharacteristicValue success', res.errMsg)
 }
})
//特别提醒建议每次写入的buffer不超过20字节,超过会有写入错误的风险,所以一个打印的内容可能要拆成N个20字节的buffer去循环writeBLECharacteristicValue,这样就能打印成功啦。

附:

微信小程序官方文档

示例代码(uniapp实现小程序蓝牙打印简易流程)

另注:无论是原生、WePY、mpvue或uniapp、调用步骤都是一样的,不过调用API的前缀需要改成对应的就OK了

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们