温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

微信小程序实现蓝牙打印

发布时间:2020-09-19 05:24:01 来源:脚本之家 阅读:592 作者:泠青云 栏目:web开发

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

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI