蓝牙打印功能
我引用的代码是【https://github.com/qihang666/BluetoothPrinter】qihang666提供的代码。
用的是佳博打印机。
测试的手机是红米note 9 pro。
打印的是条形码打印,纸的长宽是40mm*50mm。
第一步:写页面
1,编写连接蓝牙的页面
<view>
<button @click="searchBle">搜索蓝牙</button>
<view :class="{aaa:bbb}" style="display: none;">蓝牙已经连接</view>
<view style="margin-top: 30upx;" :key="index" v-for="(item,index) in devices">
<button style="width: 400upx; color: #0081FF;" @click="onConn(item)">{{item.name}}</button>
</view>
<button style="margin-top: 300upx;" @click="tomy()">退出蓝牙</button>
<button style="margin-top: 100upx;" @click="fanhui()">返回</button>
</view>
2,引入tsc文件和esc文件
var tsc = require('../../../components/gprint/tsc.js')
var esc = require('../../../components/gprint/esc.js')
3,定义数据
data() {
return {
devices: [],//搜索到的蓝牙设备,渲染到页面上
currDev: null,
connId: '',
bbb:uni.getStorageSync('bbb')
}
},
第二步:初始化蓝牙,连接蓝牙
1,点击搜索蓝牙
//点击搜索蓝牙
searchBle() {
var that = this
if(uni.getStorageSync('deviceId')){
uni.showToast({
title: '蓝牙已连接!要搜索蓝牙请先退出',
icon: 'none',
duration: 2000
})
return
}
console.log("点击搜索蓝牙")
uni.openBluetoothAdapter({
success(res) {
console.log("打开 蓝牙模块")
console.log(res)
that.onDevice()
uni.getBluetoothAdapterState({ //获取本机蓝牙适配状态
success: function(res) {
console.log(res)
if (res.available) {
if (res.discovering) {
that.stopFindBule()
}
//搜索蓝牙
//开始搜寻附近的蓝牙外围设备
console.log("开始搜寻附近的蓝牙外围设备")
uni.startBluetoothDevicesDiscovery({
success(res) {
console.log("搜寻附近的蓝牙外围设备")
console.log(res)
}
})
}
else {
console.log('本机蓝牙不可用')
}
},
})
}
})
},
//监听寻找到新设备的事件
onDevice(){
console.log("监听寻找到新设备的事件---------------")
var that = this
//监听寻找到新设备的事件
uni.onBluetoothDeviceFound(function(devices) {
console.log('--------------new-----------------------'+JSON.stringify(devices))
var re = JSON.parse(JSON.stringify(devices))
console.log("搜索到的蓝牙设备名字",re.devices[0].name + " 搜索到的蓝牙设备id " + re.devices[0].deviceId)
let name = re.devices[0].name
if (name != "") {
// this.getBluetoothDevices()
console.log("搜索到的蓝牙:",name)
let deviceId = re.devices[0].deviceId
that.devices.push({ //把搜索到的新设备保存起来
name: name,
deviceId: deviceId,
services: []
})
}
})
},
2,点击蓝牙设备的名字,连接蓝牙
//点击链接蓝牙
onConn(item) {
if(uni.getStorageSync('deviceId')){
uni.showToast({
title: '蓝牙已连接!',
icon: 'none',
duration: 2000
})
return
}
console.log(item)
uni.showLoading({
title: '蓝牙连接中',
mask: true
}) //显示加载动画
var that = this
console.log("保存到的设备有;",that.devices)
console.log("连接蓝牙---------------" + item.deviceId)
let deviceId = item.deviceId
console.log(deviceId)
uni.createBLEConnection({
deviceId: deviceId,
success:(res) => {
if (res.errMsg == "createBLEConnection:ok") {
console.log("连接蓝牙-[" + item.name + "]--成功")
that.connId = deviceId;
that.currDev = item
setTimeout(function() {
that.getBLEServices(deviceId)
}, 1500)
uni.setStorageSync("deviceId",item.deviceId)//把已经连接的蓝牙设备信息放入缓存
} else {
uni.showToast({
title: '连接蓝牙失败!请退出蓝牙重新连接',
icon: 'none',
duration: 2000
})
console.log(res)
}
//连接成功 关闭搜索
that.stopFindBule()
},
})
},
//获取已经连接的蓝牙设备的所有服务
getBLEServices(_deviceId) {
var that = this;
let deviceId = _deviceId
console.log("获取蓝牙设备所有服务(service)。---------------")
uni.getBLEDeviceServices({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: deviceId,
success:(res) => {
console.log(res)
let serviceId = ""
console.log("获取蓝牙设备成功的信息:",res)
if(res.services.length == 0){
uni.hideNavigationBarLoading() //关闭加载动画
uni.showToast({
title: '获取蓝牙服务失败!请退出蓝牙重新连接',
icon: 'none',
duration: 2000
})
}
for (var s = 0; s < res.services.length; s++) {
let serviceId = res.services[s].uuid
uni.getBLEDeviceCharacteristics({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId: serviceId,
success:(res) => {
var re = JSON.parse(JSON.stringify(res))
console.log('deviceId = [' + deviceId + '] serviceId = [' + serviceId + ']')
for (var c = 0; c < re.characteristics.length; c++) {
if (re.characteristics[c].properties.write == true) {
let uuid = re.characteristics[c].uuid
console.log(' deviceId = [' + deviceId + '] serviceId = [' + serviceId + '] characteristics=[' +
uuid)
for (var index in that.devices) {
if (that.devices[index].deviceId == deviceId) {
uni.showToast({
title: '连接蓝牙成功',
icon: 'success',
duration: 2000
})
uni.hideNavigationBarLoading() //关闭加载动画
that.bbb = true
uni.setStorageSync("bbb",true)
uni.setStorageSync("characteristicId",uuid)//把已经连接的蓝牙设备标识放入缓存
uni.setStorageSync("serviceId",serviceId)//把已经连接的蓝牙设备ID放入缓存
that.devices[index].services.push({
serviceId: serviceId,
characteristicId: uuid
})
break
}
}
}
}
}
})
}
},
fail(res) {
console.log(res)
},
})
},
到这里,蓝牙就已经连接了
第三步:打印
1,,点击蓝牙打印,开始打印
我的蓝牙打印是在另一个页面应用的,用到的代码如下:
//打印的数据
senBlData(deviceId, serviceId, characteristicId,uint8Array) {
console.log('************deviceId = [' + deviceId + '] serviceId = [' + serviceId + '] characteristics=[' +characteristicId+ "]")
var uint8Buf = Array.from(uint8Array);
console.log("这个是什么。。。。。",uint8Buf)
function split_array(datas,size){
console.log("data是什么:",datas)
var result = {};
var j = 0
for (var i = 0; i < datas.length; i += size) {
result[j] = datas.slice(i, i + size)
j++
}
console.log(result)
return result
}
var sendloop = split_array(uint8Buf, 20);
// console.log(sendloop.length)
function realWriteData(sendloop, i) {
var data = sendloop[i]
if(typeof(data) == "undefined"){
return
}
console.log("第【" + i + "】次写数据"+data)
var buffer = new ArrayBuffer(data.length)
var dataView = new DataView(buffer)
for (var j = 0; j < data.length; j++) {
dataView.setUint8(j, data[j]);
}
uni.writeBLECharacteristicValue({
deviceId,
serviceId,
characteristicId,
value: buffer,
success(res) {
realWriteData(sendloop, i + 1);
}
})
}
var i = 0;
realWriteData(sendloop, i);
},
//打印条形码
daying(){
console.log("开始打印条码")
// this.$nav('/pages/component/stamp')
console.log("条码的内容:",this.sPopupList.wbHalfId)
let deviceId = uni.getStorageSync('deviceId')
let serviceId = uni.getStorageSync('serviceId')
let characteristicId = uni.getStorageSync('characteristicId')
var command = tsc.jpPrinter.createNew()
// console.log(command)
command.setSize(40, 50)
command.setGap(2)
command.setCls()
command.setText(300, 100, "TSS24.BF2", 2, 2, this.sPopupList.procedured)
// (x, y, codetype, height, readable, narrow, wide, content)
command.setBar(230,25,"128",160,1,4,3,this.sPopupList.wbHalfId)
// command.setQR(50, 50, "L", 5, "A", "977767937@qq.com")
// (x, y, level, width, mode, content)
command.setPagePrint()
this.senBlData(deviceId, serviceId, characteristicId,command.getData())
},
第四步:断开蓝牙
需要断开蓝牙的时候点击退出蓝牙
// 点击断开蓝牙连接
tomy (){
var _this = this
uni.closeBluetoothAdapter({
success(res) {
uni.removeStorageSync('deviceId')
uni.removeStorageSync("serviceId");
uni.removeStorageSync("characteristicId");
uni.setStorageSync("bbb",false);
console.log(_this.bbb)
console.log("退出蓝牙:",uni.getStorageSync('deviceId')+"和"+uni.getStorageSync("serviceId"))
_this.$navtab('/pages/about/my')
}
})
},
点击返回:这只是个简单的页面跳转
//点击返回
fanhui (){
this.$navtab('/pages/about/my') //页面跳转
},
到这个就做完了,我来记录一下我遇到的问题吧!
总是获取不到设备服务,需要退出两次才可以连接蓝牙,要不就是连接蓝牙成功但是不能打印,卡了我好久,最后的解决问题的,因为我的后台蓝牙已经连接了设备,把本机连接的设备断开就好了。
我是一个菜鸡,记录一下我所踩过的坑!