首页IT科技小程序蓝牙连接打印机(uniapp微信小程序实现连接低功耗蓝牙打印功能)

小程序蓝牙连接打印机(uniapp微信小程序实现连接低功耗蓝牙打印功能)

时间2025-05-05 04:45:55分类IT科技浏览10468
导读:微信小程序项目中有使用到蓝牙连接打印,参考官方文档做了一个参考笔记,这样使用的时候就按着步骤查看。...

微信小程序项目中有使用到蓝牙连接打印              ,参考官方文档做了一个参考笔记                      ,这样使用的时候就按着步骤查看                。

uni-app蓝牙连接

蓝牙:

1              、初始化蓝牙

uni.openBluetoothAdapter(OBJECT)

uni.openBluetoothAdapter({ success(res) { console.log(res) // 接口调用成功的回调函数 }, fail:(res)=>{ // 接口调用失败的回调函数 }, complete:()=>{ // 接口调用结束的回调函数(调用成功                      、失败都会执行) } })

错误 :res.errCode

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有        ,系统版本低于 4.3 不支持 BLE

注意

其他蓝牙相关 API 必须在 uni.openBluetoothAdapter 调用之后使用                      。否则 API 会返回错误(errCode=10000)      。 在用户蓝牙开关未开启或者手机不支持蓝牙功能的情况下           ,调用 uni.openBluetoothAdapter 会返回错误(errCode=10001)                     ,表示手机蓝牙功能不可用            。此时APP蓝牙模块已经初始化完成            ,可通过 uni.onBluetoothAdapterStateChange 监听手机蓝牙状态的改变        ,也可以调用蓝牙模块的所有API                       。

2        、监听蓝牙适配器状态变化事件

uni.onBluetoothAdapterStateChange(CALLBACK)

CALLBACK 返回参数

属性 类型 说明 available boolean 蓝牙适配器是否可用 discovering boolean 蓝牙适配器是否处于搜索状态

示例代码

uni.onBluetoothAdapterStateChange((res) => { console.log(onBluetoothAdapterStateChange, res) // available:蓝牙适配器是否可用 if (res.available) { // 取消监听                     ,否则stopBluetoothDevicesDiscovery后仍会继续触发onBluetoothAdapterStateChange                , // 导致再次调用startBluetoothDevicesDiscovery uni.onBluetoothAdapterStateChange(() => {}); // 开始搜寻附近的蓝牙外围设备 uni.startBluetoothDevicesDiscovery(OBJECT) } })

3           、开始搜寻附近的蓝牙外围设备

uni.startBluetoothDevicesDiscovery(OBJECT)

此操作比较耗费系统资源    ,请在搜索并连接到设备后调用 uni.stopBluetoothDevicesDiscovery 方法停止搜索         。

OBJECT 参数说明

属性 类型 默认值 必填 说明 services Array 否 要搜索但蓝牙设备主 service 的 uuid 列表        。某些蓝牙设备会广播自己的主 service 的 uuid                        。如果设置此参数                     ,则只搜索广播包有对应 uuid 的主服务的蓝牙设备             。建议主要通过该参数过滤掉周边不需要处理的其他蓝牙设备    。 allowDuplicatesKey boolean false 否 是否允许重复上报同一设备                        。如果允许重复上报                    ,则 uni.onBlueToothDeviceFound 方法会多次上报同一设备,但是 RSSI 值会有不同                 。 interval number 0 否 上报设备的间隔。0 表示找到新设备立即上报                 ,其他数值根据传入的间隔上报                    。 success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功                     、失败都会执行)

错误

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有                       ,系统版本低于 4.3 不支持 BLE

注意:

App 端目前仅支持发现ble蓝牙设备    ,更多蓝牙设备发现              ,可以使用 Native.js                      ,参考:https://ask.dcloud.net.cn/article/114                     。也可以在插件市场获取原生插件

示例代码

// 以微信硬件平台的蓝牙智能灯为例        ,主服务的 UUID 是 FEE7   。传入这个参数           ,只搜索主服务 UUID 为 FEE7 的设备 uni.startBluetoothDevicesDiscovery({ services: [FEE7], success(res) { console.log(res) // 监听寻找到新设备的事件 uni.onBluetoothDeviceFound(OBJECT) } })

4            、监听寻找到新设备的事件

uni.onBluetoothDeviceFound(CALLBACK)

CALLBACK 返回参数

属性 类型 说明 devices Array 新搜索到的设备列表

devices 的结构

属性 类型 说明 name string 蓝牙设备名称                     ,某些设备可能没有 deviceId string 用于区分设备的 id RSSI number 当前蓝牙设备的信号强度 advertisData ArrayBuffer 当前蓝牙设备的广播数据段中的 ManufacturerData 数据段                。 advertisServiceUUIDs Array 当前蓝牙设备的广播数据段中的 ServiceUUIDs 数据段 localName string 当前蓝牙设备的广播数据段中的 LocalName 数据段 serviceData Object 当前蓝牙设备的广播数据段中的 ServiceData 数据段

注意

若在 uni.onBluetoothDeviceFound 回调了某个设备            ,则此设备会添加到 uni.getBluetoothDevices 接口获取到的数组中                      。

示例代码

// ArrayBuffer转16进度字符串示例 function ab2hex(buffer) { const hexArr = Array.prototype.map.call( new Uint8Array(buffer), function (bit) { return (00 + bit.toString(16)).slice(-2) } ) return hexArr.join() } uni.onBluetoothDeviceFound(function (devices) { console.log(new device list has founded) console.dir(devices) console.log(ab2hex(devices[0].advertisData)) })

5        、停止搜寻附近的蓝牙外围设备

uni.stopBluetoothDevicesDiscovery(OBJECT)

若已经找到需要的蓝牙设备并不需要继续搜索时        ,建议调用该接口停止蓝牙搜索      。

OBJECT 参数说明

属性 类型 默认值 必填 说明 success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功                     、失败都会执行)

错误

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有                     ,系统版本低于 4.3 不支持 BLE

示例代码

uni.stopBluetoothDevicesDiscovery({ success(res) { console.log(res) } })

6                、根据 uuid 获取处于已连接状态的设备

uni.getConnectedBluetoothDevices(OBJECT)

OBJECT 参数说明

属性 类型 默认值 必填 说明 services Array 是 蓝牙设备主 service 的 uuid 列表 success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功    、失败都会执行)

success 返回参数说明:

属性 类型 说明 devices Array 搜索到的设备列表

res.devices 的结构

属性 类型 说明 name string 蓝牙设备名称                ,某些设备可能没有 deviceId string 用于区分设备的 id

错误

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有    ,系统版本低于 4.3 不支持 BLE

示例代码

uni.getConnectedBluetoothDevices({ success(res) { console.log(res) } })

7                     、获取在蓝牙模块生效期间所有已发现的蓝牙设备

uni.getBluetoothDevices(OBJECT)

包括已经和本机处于连接状态的设备            。

OBJECT 参数说明

属性 类型 默认值 必填 说明 success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功                    、失败都会执行)

success 返回参数说明:

属性 类型 说明 devices Array uuid 对应的的已连接设备列表

res.devices 的结构

属性 类型 说明 name string 蓝牙设备名称                     ,某些设备可能没有 deviceId string 用于区分设备的 id RSSI number 当前蓝牙设备的信号强度 advertisData ArrayBuffer 当前蓝牙设备的广播数据段中的 ManufacturerData 数据段                       。 advertisServiceUUIDs Array 当前蓝牙设备的广播数据段中的 ServiceUUIDs 数据段 localName string 当前蓝牙设备的广播数据段中的 LocalName 数据段 serviceData Object 当前蓝牙设备的广播数据段中的 ServiceData 数据段

错误

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有                    ,系统版本低于 4.3 不支持 BLE

示例代码

// ArrayBuffer转16进度字符串示例 function ab2hex(buffer) { const hexArr = Array.prototype.map.call( new Uint8Array(buffer), function (bit) { return (00 + bit.toString(16)).slice(-2) } ) return hexArr.join() } uni.getBluetoothDevices({ success(res) { console.log(res) if (res.devices[0]) { console.log(ab2hex(res.devices[0].advertisData)) } } })

注意

该接口获取到的设备列表为蓝牙模块生效期间所有搜索到的蓝牙设备,若在蓝牙模块使用流程结束后未及时调用 uni.closeBluetoothAdapter 释放资源                 ,会存在调用该接口会返回之前的蓝牙使用流程中搜索到的蓝牙设备                       ,可能设备已经不在用户身边    ,无法连接         。 蓝牙设备在被搜索到时              ,系统返回的 name 字段一般为广播包中的 LocalName 字段中的设备名称                      ,而如果与蓝牙设备建立连接        ,系统返回的 name 字段会改为从蓝牙设备上获取到的 GattName        。若需要动态改变设备名称并展示           ,建议使用 localName 字段                        。

8、获取本机蓝牙适配器状态

uni.getBluetoothAdapterState(OBJECT)

OBJECT 参数说明

属性 类型 默认值 必填 说明 success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功                 、失败都会执行)

success 返回参数说明:

属性 类型 说明 discovering boolean 是否正在搜索设备 available boolean 蓝牙适配器是否可用

错误

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有                     ,系统版本低于 4.3 不支持 BLE

示例代码

uni.getBluetoothAdapterState({ success(res) { console.log(res) } })

9                       、关闭蓝牙模块

uni.closeBluetoothAdapter(OBJECT)

调用该方法将断开所有已建立的连接并释放系统资源             。建议在使用蓝牙流程后            ,与 uni.openBluetoothAdapter 成对调用    。

OBJECT 参数说明

属性 类型 默认值 必填 说明 success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功    、失败都会执行)

错误

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有        ,系统版本低于 4.3 不支持 BLE

示例代码

uni.closeBluetoothAdapter({ success(res) { console.log(res) } })

低功耗蓝牙:

1              、设置蓝牙最大传输单元

[uni.setBLEMTU(OBJECT)

需在 uni.createBLEConnection调用成功后调用                     ,mtu 设置范围 (22,512)                        。安卓5.1以上有效                 。

OBJECT 参数说明

属性 类型 默认值 必填 说明 deviceId string 是 用于区分设备的 id mtu number 是 最大传输单元(22,512) 区间内                ,单位 bytes success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功                      、失败都会执行)

2        、向低功耗蓝牙设备特征值中写入二进制数据

uni.writeBLECharacteristicValue(OBJECT)

注意:必须设备的特征值支持 write 才可以成功调用。

OBJECT 参数说明

属性 类型 默认值 必填 说明 deviceId string 是 蓝牙设备 id serviceId string 是 蓝牙特征值对应服务的 uuid characteristicId string 是 蓝牙特征值的 uuid value ArrayBuffer 是 蓝牙设备特征值对应的二进制值 success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功           、失败都会执行)

错误

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有    ,系统版本低于 4.3 不支持 BLE

注意

并行调用多次会存在写失败的可能性                    。 APP不会对写入数据包大小做限制                     ,但系统与蓝牙设备会限制蓝牙4.0单次传输的数据大小                    ,超过最大字节数后会发生写入错误,建议每次写入不超过20字节                     。 若单次写入数据过长                 ,iOS 上存在系统不会有任何回调的情况(包括错误回调)   。 安卓平台上                       ,在调用 notifyBLECharacteristicValueChange 成功后立即调用 writeBLECharacteristicValue 接口    ,在部分机型上会发生 10008 系统错误

示例代码

// 向蓝牙设备发送一个0x00的16进制数据 const buffer = new ArrayBuffer(1) const dataView = new DataView(buffer) dataView.setUint8(0, 0) uni.writeBLECharacteristicValue({ // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取 deviceId, // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取 serviceId, // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取 characteristicId, // 这里的value是ArrayBuffer类型 value: buffer, success(res) { console.log(writeBLECharacteristicValue success, res.errMsg) } })

3                     、读取低功耗蓝牙设备的特征值的二进制数据值

uni.readBLECharacteristicValue(OBJECT)

注意:必须设备的特征值支持 read 才可以成功调用                。

OBJECT 参数说明

属性 类型 默认值 必填 说明 deviceId string 是 蓝牙设备 id serviceId string 是 蓝牙特征值对应服务的 uuid characteristicId string 是 蓝牙特征值的 uuid success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功            、失败都会执行)

错误

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有              ,系统版本低于 4.3 不支持 BLE

注意

并行调用多次会存在读失败的可能性                      。 接口读取到的信息需要在 onBLECharacteristicValueChange 方法注册的回调中获取      。

示例代码

// 必须在这里的回调才能获取 uni.onBLECharacteristicValueChange(function (characteristic) { console.log(characteristic value comed:, characteristic) }) uni.readBLECharacteristicValue({ // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 deviceId, // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取 serviceId, // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取 characteristicId, success(res) { console.log(readBLECharacteristicValue:, res.errCode) } })

4        、监听低功耗蓝牙连接状态的改变事件

uni.onBLEConnectionStateChange(CALLBACK)

包括开发者主动连接或断开连接                      ,设备丢失        ,连接异常断开等等

CALLBACK 返回参数

属性 类型 说明 deviceId string 蓝牙设备ID connected boolean 是否处于已连接状态

示例代码

uni.onBLEConnectionStateChange(function (res) { // 该方法回调中可以用于处理连接意外断开等异常情况 console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`) })

5                     、监听低功耗蓝牙设备的特征值变化事件

uni.onBLECharacteristicValueChange(CALLBACK)

必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification            。

CALLBACK 返回参数

属性 类型 说明 deviceId string 蓝牙设备 id serviceId string 蓝牙特征值对应服务的 uuid characteristicId string 蓝牙特征值的 uuid value ArrayBuffer 特征值最新的值

示例代码

// ArrayBuffer转16进度字符串示例 function ab2hex(buffer) { const hexArr = Array.prototype.map.call( new Uint8Array(buffer), function (bit) { return (00 + bit.toString(16)).slice(-2) } ) return hexArr.join() } uni.onBLECharacteristicValueChange(function (res) { console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`) console.log(ab2hex(res.value)) })

6                、订阅特征值

uni.notifyBLECharacteristicValueChange(OBJECT)

启用低功耗蓝牙设备特征值变化时的 notify 功能           ,订阅特征值                       。注意:必须设备的特征值支持 notify 或者 indicate 才可以成功调用         。 另外                     ,必须先启用 notifyBLECharacteristicValueChange 才能监听到设备 characteristicValueChange 事件

OBJECT 参数说明

属性 类型 默认值 必填 说明 deviceId string 是 蓝牙设备 id serviceId string 是 蓝牙特征值对应服务的 uuid characteristicId string 是 蓝牙特征值的 uuid state boolean 是 是否启用 notify success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功    、失败都会执行)

错误

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有            ,系统版本低于 4.3 不支持 BLE

注意

订阅操作成功后需要设备主动更新特征值的 value        ,才会触发 uni.onBLECharacteristicValueChange 回调        。 安卓平台上                     ,在调用 notifyBLECharacteristicValueChange 成功后立即调用 writeBLECharacteristicValue 接口                ,在部分机型上会发生 10008 系统错误

示例代码

uni.notifyBLECharacteristicValueChange({ state: true, // 启用 notify 功能 // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 deviceId, // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取 serviceId, // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取 characteristicId, success(res) { console.log(notifyBLECharacteristicValueChange success, res.errMsg) } })

7                     、获取蓝牙设备所有服务(service)

uni.getBLEDeviceServices(OBJECT)

OBJECT 参数说明

属性 类型 默认值 必填 说明 deviceId string 是 蓝牙设备 id success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功                    、失败都会执行)

success 返回参数说明:

属性 类型 说明 services Array 设备服务列表

res.services 的结构

属性 类型 说明 uuid string 蓝牙设备服务的 uuid isPrimary boolean 该服务是否为主服务

错误

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有    ,系统版本低于 4.3 不支持 BLE

示例代码

uni.getBLEDeviceServices({ // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 deviceId, success(res) { console.log(device services:, res.services) } })

8、获取蓝牙设备的信号强度

uni.getBLEDeviceRSSI(OBJECT)

OBJECT 参数说明

属性 类型 默认值 必填 说明 deviceId string 是 蓝牙设备 id success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功                 、失败都会执行)

9                       、获取蓝牙设备某个服务中所有特征值(characteristic)                        。

uni.getBLEDeviceCharacteristics(OBJECT)

OBJECT 参数说明

属性 类型 默认值 必填 说明 deviceId string 是 蓝牙设备 id serviceId string 是 蓝牙服务 uuid                     ,需要使用 getBLEDeviceServices 获取 success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功    、失败都会执行)

success 返回参数说明:

属性 类型 说明 characteristics Array 设备服务列表

res.characteristics 的结构

属性 类型 说明 uuid string 蓝牙设备特征值的 uuid properties Object 该特征值支持的操作类型

properties 的结构

属性 类型 说明 read boolean 该特征值是否支持 read 操作 write boolean 该特征值是否支持 write 操作 notify boolean 该特征值是否支持 notify 操作 indicate boolean 该特征值是否支持 indicate 操作

错误

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有                    ,系统版本低于 4.3 不支持 BLE

示例代码

uni.getBLEDeviceCharacteristics({ // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 deviceId, // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取 serviceId, success(res) { console.log(device getBLEDeviceCharacteristics:, res.characteristics) } })

10              、连接低功耗蓝牙设备

uni.createBLEConnection(OBJECT)

若APP在之前已有搜索过某个蓝牙设备,并成功建立连接                 ,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备                       ,无需进行搜索操作             。

OBJECT 参数说明

属性 类型 默认值 必填 说明 deviceId string 是 用于区分设备的 id timeout number 否 超时时间    ,单位ms              ,不填表示不会超时 success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功                      、失败都会执行)

错误

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有                      ,系统版本低于 4.3 不支持 BLE

注意

请保证尽量成对的调用 createBLEConnection 和 closeBLEConnection 接口    。安卓如果多次调用 createBLEConnection 创建连接        ,有可能导致系统持有同一设备多个连接的实例           ,导致调用 closeBLEConnection 的时候并不能真正的断开与设备的连接                        。 蓝牙连接随时可能断开                     ,建议监听 uni.onBLEConnectionStateChange 回调事件            ,当蓝牙设备断开时按需执行重连操作 若对未连接的设备或已断开连接的设备调用数据读写操作的接口        ,会返回 10006 错误                     ,建议进行重连操作                 。

示例代码

uni.createBLEConnection({ // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 deviceId, success(res) { console.log(res) } })

11        、断开与低功耗蓝牙设备的连接。

uni.closeBLEConnection(OBJECT)

OBJECT 参数说明

属性 类型 默认值 必填 说明 deviceId string 是 用于区分设备的 id success function 否 接口调用成功的回调函数 fail function 否 接口调用失败的回调函数 complete function 否 接口调用结束的回调函数(调用成功           、失败都会执行)

错误

错误码 错误信息 说明 0 ok 正常 10000 not init 未初始化蓝牙适配器 10001 not available 当前蓝牙适配器不可用 10002 no device 没有找到指定设备 10003 connection fail 连接失败 10004 no service 没有找到指定服务 10005 no characteristic 没有找到指定特征值 10006 no connection 当前连接已断开 10007 property not support 当前特征值不支持此操作 10008 system error 其余所有系统上报的异常 10009 system not support Android 系统特有                ,系统版本低于 4.3 不支持 BLE

示例代码

uni.closeBLEConnection({ deviceId, success(res) { console.log(res) } })

实现代码:

<template> <!-- 蓝牙打印页面 --> <view class="page"> <button @click="openBluetoothAdapter">重新查询</button> <view class="title"> 可连接的蓝牙设备列表: <text style="color: red;font-size:22rpx;">(部分机型需要打开GPS定位服务)</text> </view> <view class="list"> <view class="item" v-for="(item, i) in devices" :key="i"> <!-- 设备名称 --> <text>{{ item.name }}</text> <!-- 连接状态 --> <view class="right"> <view class="font-color-3" @click="createBLEConnection(item)" v-show="!item.isShowConnect">连接设备</view> <view class="font-color-3" v-show="item.isShowConnect">已连接</view> </view> </view> <!-- v-if="devices.length" --> <button :class="isDisabled || isConnected ? submit disabled : submit" @click="writeBLECharacteristicValue" :disabled="isDisabled || isConnected">开始打印</button> <view class="no-devices" v-if="!devices.length">未搜索到蓝牙设备</view> </view> </view> </template> <script> const LAST_CONNECTED_DEVICE = last_connected_device; import PrinterJobs from ../../common/printer/printerjobs; import printerUtil from ../../common/printer/printerutil; function inArray(arr, key, val) { for (let i = 0; i < arr.length; i++) { if (arr[i][key] === val) { return i; } } return -1; } // ArrayBuffer转16进度字符串示例 function ab2hex(buffer) { const hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) { return (00 + bit.toString(16)).slice(-2); }); return hexArr.join(,); } function str2ab(str) { // Convert str to ArrayBuff and write to printer let buffer = new ArrayBuffer(str.length); let dataView = new DataView(buffer); for (let i = 0; i < str.length; i++) { dataView.setUint8(i, str.charAt(i).charCodeAt(0)); } return buffer; } export default { name: print, components: {}, props: {}, data() { return { devices: [], connected: false, isConnected: true, name: , deviceId: null }; }, onLoad() {}, onShow() {}, created() {}, mounted() { this.openBluetoothAdapter(); }, methods: { // 初始化蓝牙 openBluetoothAdapter() { console.log(初始化蓝牙模块 openBluetoothAdapter); if (!uni.openBluetoothAdapter) { console.log(微信版本过低); uni.showModal({ title: 提示, content: 当前微信版本过低    ,无法使用该功能                     ,请升级到最新微信版本后重试                    。 }); return; } uni.showLoading({ title: 开始搜索蓝牙设备 }); // uni.hideLoading(); uni.openBluetoothAdapter({ success: res => { console.log(初始化成功openBluetoothAdapter success, res); uni.hideLoading(); // 搜寻附近的蓝牙 this.startBluetoothDevicesDiscovery(); }, fail: res => { console.log(初始化失败openBluetoothAdapter fail, res); // uni.showModal({ // content: res.errMsg, // showCancel: false // }); uni.hideLoading(); if (res.errCode === 10001) { // 当前蓝牙适配器不可用 uni.showModal({ title: 错误, content: 未找到蓝牙设备, 请打开蓝牙后重试                     。, showCancel: false }); // 监听蓝牙适配器状态变化事件 uni.onBluetoothAdapterStateChange(res => { console.log(监听蓝牙适配器状态 onBluetoothAdapterStateChange, res); // available:蓝牙适配器是否可用 if (res.available) { // 取消监听                    ,否则stopBluetoothDevicesDiscovery后仍会继续触发onBluetoothAdapterStateChange, // 导致再次调用startBluetoothDevicesDiscovery // uni.onBluetoothAdapterStateChange(() => {}); // 开始搜寻附近的蓝牙外围设备 this.startBluetoothDevicesDiscovery(); } }); } } }); }, // 开始搜寻附近的蓝牙外围设备 startBluetoothDevicesDiscovery() { console.log(开始搜寻附近的蓝牙设备); uni.startBluetoothDevicesDiscovery({ allowDuplicatesKey: false, interval: 0, success: res => { console.log(搜寻附近的蓝牙外围设备 startBluetoothDevicesDiscovery success111, res); // 监听寻找到新设备的事件 this.onBluetoothDeviceFound(); }, fail: res => { console.log(搜寻附近的蓝牙外围设备 startBluetoothDevicesDiscovery fail, res); uni.hideLoading(); } }); }, // 监听寻找到新设备的事件 onBluetoothDeviceFound() { console.log(进入查询设备); uni.onBluetoothDeviceFound(res => { console.log(寻找设备, res.devices); res.devices.forEach(device => { if (!device.name && !device.localName) { return; } const foundDevices = this.devices; // 在数组中查找指定值                 ,并返回它的索引值(如果没有找到                       ,则返回-1) const idx = inArray(foundDevices, deviceId, device.deviceId); const data = {}; if (idx === -1) { this.$set(this.devices, `${foundDevices.length}`, device); } else { this.$set(this.devices, `${idx}`, device); } console.log(搜索结果, this.devices); uni.hideLoading(); }); }); }, // this.devices是蓝牙设备列表    ,渲染到页面显示点击执行蓝牙连接 // 点击链接蓝牙 createBLEConnection(e) { console.log(点击连接蓝牙, e); const deviceId = e.deviceId; const name = e.name; this._createBLEConnection(deviceId, name); }, _createBLEConnection(deviceId, name) { this.$myToast(连接设备中, loading); // 连接低功耗蓝牙设备 uni.createBLEConnection({ deviceId, // 用于区分设备的 id success: () => { console.log(连接蓝牙接口调用成功 createBLEConnection success, this.devices); this.devices.forEach((item, index) => { this.$set(this.devices[index], isShowConnect, false); if (item.deviceId === deviceId) { this.$set(this.devices[index], isShowConnect, true); } }); this.$myToast(设备连接成功, success); this.connected = true; this.isConnected = false; this.name = name; this.deviceId = deviceId; // 获取蓝牙设备所有服务(service) this.getBLEDeviceServices(deviceId); // 最后连接设备 uni.setStorage({ key: LAST_CONNECTED_DEVICE, data: name + : + deviceId }); }, complete() { uni.hideLoading(); }, fail: res => { // 连接蓝牙接口调用失败 console.log(连接蓝牙接口调用失败 createBLEConnection fail, res); uni.showModal({ title: this.$t(wechat.w227), content: 蓝牙连接失败, showCancel: false }); } }); // 已经找到需要的蓝牙设备,停止搜寻附近的蓝牙外围设备 this.stopBluetoothDevicesDiscovery(); }, // 获取蓝牙设备所有服务(service) getBLEDeviceServices(deviceId) { uni.getBLEDeviceServices({ deviceId, success: res => { console.log(获取蓝牙设备所有服务 getBLEDeviceServices, res); for (let i = 0; i < res.services.length; i++) { if (res.services[i].isPrimary) { this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid); return; } } } }); }, stopBluetoothDevicesDiscovery() { uni.stopBluetoothDevicesDiscovery({ complete: () => { // console.log(stopBluetoothDevicesDiscovery) this._discoveryStarted = false; } }); }, /* 获取蓝牙设备某个服务中所有特征值(characteristic) characteristic: uuid:蓝牙设备特征值的 uuid properties:该特征值支持的操作类型 */ getBLEDeviceCharacteristics(deviceId, serviceId) { uni.getBLEDeviceCharacteristics({ // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 deviceId, // 这里的 serviceId(蓝牙服务 uuid) 需要在 getBLEDeviceServices 接口中获取 serviceId, success: res => { console.log(特征值变化 getBLEDeviceCharacteristics success, res.characteristics); // 这里会存在特征值是支持write              ,写入成功但是没有任何反应的情况 // 只能一个个去试 // characteristics:设备服务列表 for (let i = 0; i < res.characteristics.length; i++) { const item = res.characteristics[i]; // if (item.properties.read) { // uni.readBLECharacteristicValue({ // deviceId, // serviceId, // characteristicId: item.uuid // }) // } if (item.properties.write) { this.canWrite = true; this._deviceId = deviceId; this._serviceId = serviceId; this._characteristicId = item.uuid; } if (item.properties.notify || item.properties.indicate) { uni.notifyBLECharacteristicValueChange({ deviceId, serviceId, characteristicId: item.uuid, state: true }); } if (item.properties.write) { this.canWrite = true; this._deviceId = deviceId; this._serviceId = serviceId; this._characteristicId = item.uuid; } if (item.properties.notify || item.properties.indicate) { uni.notifyBLECharacteristicValueChange({ deviceId, serviceId, characteristicId: item.uuid, state: true }); } } }, fail(res) { console.error(特征值变化 getBLEDeviceCharacteristics, res); } }); }, // 蓝牙连接成功后点击打印                      ,打印数据 // 点击打印:写入数据(根据项目需要打印内容来实现) writeBLECharacteristicValue() { console.log(写数据); let printerJobs = new PrinterJobs(); // 要打印的信息 printerJobs .setAlign(ct) .setSize(2, 2) .print(记录报告) .setSize(0, 0) .print() .setAlign(lt); // 打印 printerJobs.print(printerUtil.fillLine()); // 结尾 printerJobs .println() .print(签名) .println() .println(); let buffer = printerJobs.buffer(); // console.log(ArrayBuffer, length: + buffer.byteLength, hex: + ab2hex(buffer)); // 1.并行调用多次会存在写失败的可能性 // 2.建议每次写入不超过20字节 // 分包处理        ,延时调用 const maxChunk = 20; const delay = 40; console.log(111111); for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) { let subPackage = buffer.slice(i, i + maxChunk <= length ? i + maxChunk : length); // subPackage:参数 setTimeout(this._writeBLECharacteristicValue, j * delay, subPackage); } console.log(22222); }, // 向低功耗蓝牙设备特征值中写入二进制数据   。注意:必须设备的特征值支持 write 才可以成功调用                。 _writeBLECharacteristicValue(buffer) { console.log(写入数据); uni.writeBLECharacteristicValue({ deviceId: this._deviceId, // 蓝牙设备 id serviceId: this._serviceId, // 蓝牙特征值对应服务的 uuid characteristicId: this._characteristicId, // 蓝牙特征值的 uuid value: buffer, // 蓝牙设备特征值对应的二进制值 success(res) { console.log(writeBLECharacteristicValue success, res); }, fail(res) { console.log(writeBLECharacteristicValue fail, res); } }); } } }; </script> <style scoped lang="scss"> .page { margin: 20rpx; color: #323232; background-color: #f5f9ff; height: 100vh; } .title { font-weight: 600; margin: 20rpx 0rpx; } .list { .item { display: flex; justify-content: space-between; padding: 10rpx 20rpx; height: 60rpx; line-height: 60rpx; background-color: #ffffff; margin-bottom: 4rpx; } .right { } .no-devices { height: 400rpx; font-size: 32rpx; line-height: 400rpx; text-align: center; color: #969696; } } .font-color-3 { color: #1a8cff; } .submit { background-color: #4d88ff !important; color: #f5f9ff !important; } .disabled { background-color: #66b1ff !important; } </style>

页面布局效果:

可根据项目具体需求对打印数据做处理           ,打印效果:

其他文件:

printerutil.js // 打印机纸宽58mm                     ,页的宽度384            ,字符宽度为1        ,每行最多盛放32个字符 const PAGE_WIDTH = 384; const MAX_CHAR_COUNT_EACH_LINE = 32; /** * @param str * @returns {boolean} str是否全是中文 */ function isChinese(str) { return /^[\u4e00-\u9fa5]$/.test(str); } /** * 返回字符串宽度(1个中文=2个英文字符) * @param str * @returns {number} */ function getStringWidth(str) { let width = 0; for (let i = 0, len = str.length; i < len; i++) { width += isChinese(str.charAt(i)) ? 2 : 1; } return width; } /** * 同一行输出str1, str2                     ,str1居左, str2居右 * @param {string} str1 内容1 * @param {string} str2 内容2 * @param {number} fontWidth 字符宽度 1/2 * @param {string} fillWith str1 str2之间的填充字符 * */ function inline(str1, str2, fillWith = , fontWidth = 1) { const lineWidth = MAX_CHAR_COUNT_EACH_LINE / fontWidth; // 需要填充的字符数量 let fillCount = lineWidth - (getStringWidth(str1) + getStringWidth(str2)) % lineWidth; let fillStr = new Array(fillCount).fill(fillWith.charAt(0)).join(); return str1 + fillStr + str2; } /** * 用字符填充一整行 * @param {string} fillWith 填充字符 * @param {number} fontWidth 字符宽度 1/2 */ function fillLine(fillWith = -, fontWidth = 1) { const lineWidth = MAX_CHAR_COUNT_EACH_LINE / fontWidth; return new Array(lineWidth).fill(fillWith.charAt(0)).join(); } /** %2

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
如何优化网站建设,提升用户体验(掌握网站建设中的关键优化技巧,让用户爱上你的网站) pytorch中的优化器(Pytorch优化器全总结(一)SGD、ASGD、Rprop、Adagrad)