You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

850 lines
22 KiB

<template>
<view class="kk-printer">
<view class="kk-printer-btn" @tap="handlePrintTap" style="color:#FFF;">
{{isPrinting?printingText:defaultText}}
</view>
<view class="kk-shadow" :class="isShowSearch?'show':''" @tap="handleSearchClose">
<view class="kk-modal" @tap.stop="doNothing">
<view class="kk-search-device">
<view class="kk-btn-wrap">
<view class="kk-btn-item confirm-btn" @tap="sousuo" v-if="!isSearching">
搜索设备
</view>
<view class="kk-btn-item confirm-btn" v-else>
搜索中...
</view>
<view class="kk-btn-item" @tap="stopSearchBtnTap">
停止搜索
</view>
</view>
<view class="kk-devices-wrap">
<view class="empty-wrap" v-if="devicesList.length <= 0">
<view class="empty-icon"></view>
<view class="empty-text">无可搜索到的设备</view>
</view>
<view class="" v-else>
<view class="kk-devices-item" v-for="(item,index) in devicesList" :key="index"
@tap="lianejieshebei(item.deviceId, { device: item })">
<view class="name" style="color:#000;display: flex;flex-direction: column;">
<text>{{item.isCached?'上次连接:':'设备名称:'}}</text>
<text>{{item.name || item.localName || '未命名'}}</text>
</view>
<!-- <view class="rssi">
<text>信号强度</text>
<text>({{item.RSSI}})</text>
</view> -->
</view>
</view>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
import gbk from '@/components/kk-printer/utils/printUtil-GBK.js';
import * as blesdk from './utils/bluetoolth';
import util from './utils/util.js';
export default {
data() {
return {
//是否正在打印
isPrinting: false,
//是否正在搜索设备
isSearching: false,
//是否显示蓝牙列表
isShowSearch: false,
//按蓝牙名过滤
filterName: '',
//按信号过滤
filterRSSI: -95,
//设备列表
devicesList: [],
//打印图片断开连接等待时间
picWaitTime:0,
//连接的设备ID
deviceId: '',
//根据设备ID获取的服务
services: '',
//获取特征值时返回的三要素
serviceId: '',
writeId: '',
readId: '',
iosNo: false,
deviceType: 'ios',
searchTimer: null,
connectTimer: null,
printFinishTimer: null,
isListeningBluetoothDeviceFound: false,
bluetoothDeviceFoundHandler: null,
currentDevice: null,
writeFailing: false,
isWriting: false
}
},
props: {
//按钮默认文字
defaultText: {
type: String,
default: '打印'
},
//按钮打印中的文字
printingText: {
type: String,
default: '打印中...'
},
bufferData: {
type: Array,
require: true
},
roomcode: {
type: String,
require: true
},
CustName: {
type: String,
require: true
},
roomid: {
type: String,
require: true
}
},
mounted() {
},
onLoad() {
},
beforeDestroy() {
this.stopSearchBtnTap();
this.clearTimers();
if (wx.offBluetoothDeviceFound && this.bluetoothDeviceFoundHandler) {
wx.offBluetoothDeviceFound(this.bluetoothDeviceFoundHandler);
}
},
methods: {
doNothing() {
return;
},
clearTimers() {
clearTimeout(this.searchTimer);
clearTimeout(this.connectTimer);
clearTimeout(this.printFinishTimer);
this.searchTimer = null;
this.connectTimer = null;
this.printFinishTimer = null;
},
showToast(title) {
if (this.tui && this.tui.toast) {
this.tui.toast(title);
return;
}
uni.showToast({
title,
icon: 'none'
});
},
getCachedPrinter() {
let printer = uni.getStorageSync('printerDevice') || {};
if (typeof printer == 'string') {
try {
printer = JSON.parse(printer);
} catch (e) {
printer = {};
}
}
const deviceId = uni.getStorageSync('deviceId') || printer.deviceId;
if (!deviceId) {
return null;
}
return {
...printer,
deviceId,
name: printer.name || printer.localName || uni.getStorageSync('printerName') || '上次连接的打印机',
localName: printer.localName || printer.name || '',
isCached: true
};
},
savePrinterCache(device, serviceId, characteristicId) {
const deviceName = device.name || device.localName || '上次连接的打印机';
uni.setStorageSync('deviceId', device.deviceId);
uni.setStorageSync('serviceId', serviceId);
uni.setStorageSync('characteristicId', characteristicId);
uni.setStorageSync('printerName', deviceName);
uni.setStorageSync('printerDevice', {
deviceId: device.deviceId,
name: deviceName,
localName: device.localName || device.name || '',
updatedAt: Date.now()
});
},
clearPrinterConnectionCache() {
uni.removeStorageSync('deviceId');
uni.removeStorageSync('serviceId');
uni.removeStorageSync('characteristicId');
},
addCachedDeviceToList() {
const cachedPrinter = this.getCachedPrinter();
if (cachedPrinter) {
this.addDevice(cachedPrinter, true);
}
},
addDevice(device, isCached = false) {
if (!device || !device.deviceId) {
return;
}
const deviceName = device.name || device.localName || '';
if (!deviceName && !isCached) {
return;
}
const cachedPrinter = this.getCachedPrinter();
const sameCachedName = cachedPrinter && deviceName && (
deviceName == cachedPrinter.name || deviceName == cachedPrinter.localName
);
const normalizedDevice = {
...device,
name: deviceName || '上次连接的打印机',
localName: device.localName || device.name || '',
isCached: isCached || sameCachedName
};
let index = this.devicesList.findIndex(item => item.deviceId == normalizedDevice.deviceId);
if (index == -1 && normalizedDevice.isCached) {
index = this.devicesList.findIndex(item => item.isCached);
}
if (index > -1) {
const mergedDevice = {
...this.devicesList[index],
...normalizedDevice,
isCached: this.devicesList[index].isCached || normalizedDevice.isCached
};
if (mergedDevice.isCached && deviceName) {
uni.setStorageSync('printerName', deviceName);
uni.setStorageSync('printerDevice', {
deviceId: mergedDevice.deviceId,
name: deviceName,
localName: mergedDevice.localName || deviceName,
updatedAt: Date.now()
});
}
this.$set(this.devicesList, index, mergedDevice);
return;
}
if (normalizedDevice.isCached) {
this.devicesList.unshift(normalizedDevice);
} else {
this.devicesList.push(normalizedDevice);
}
},
listenBluetoothDevices() {
if (this.isListeningBluetoothDeviceFound) {
return;
}
this.isListeningBluetoothDeviceFound = true;
this.bluetoothDeviceFoundHandler = (res4) => {
(res4.devices || []).forEach((device) => {
this.addDevice(device);
});
};
wx.onBluetoothDeviceFound(this.bluetoothDeviceFoundHandler);
},
refreshBluetoothDevices() {
wx.getBluetoothDevices({
success: (res) => {
(res.devices || []).forEach((device) => {
this.addDevice(device);
});
}
});
},
startSearchTimeout() {
clearTimeout(this.searchTimer);
this.searchTimer = setTimeout(() => {
this.isSearching = false;
this.stopSearchBtnTap();
uni.hideLoading();
if (this.devicesList.length <= 0) {
this.showToast('未搜索到打印机,请确认打印机已开机并靠近手机');
}
}, 12000);
},
closeCurrentConnection(delay = 0, deviceId = '') {
deviceId = deviceId || uni.getStorageSync('deviceId') || (this.currentDevice && this.currentDevice.deviceId);
if (!deviceId) {
return;
}
setTimeout(() => {
wx.closeBLEConnection({
deviceId,
success() {},
fail() {}
});
}, delay);
},
fallbackToSearch(message) {
clearTimeout(this.connectTimer);
this.closeCurrentConnection();
uni.hideLoading();
this.isPrinting = false;
this.isShowSearch = true;
this.clearPrinterConnectionCache();
if (message) {
this.showToast(message);
}
if (!this.isSearching) {
this.sousuo({
autoConnectCache: false,
keepList: true
});
}
},
//点击打印按钮
handlePrintTap() {
let that = this
if (that.isPrinting) {
return;
}
that.clearTimers();
that.isPrinting = true;
that.writeFailing = false;
uni.showLoading({
mask: true,
title: '打印中...'
});
uni.getSystemInfo({
success(res) {
that.deviceType = res.osName
},fail(err){
}
})
// 初始化蓝牙模块
wx.openBluetoothAdapter({ //111
mode: 'central',
success: (res2) => {
that.sousuo({
autoConnectCache: true
})
},
fail: (res) => {
if (res.errCode == '10001') {
uni.showToast({
duration: 2000,
title: "请打开蓝牙后,再进行连接",
icon: 'none',
mask: true
})
} else {
that.showToast('连接失败,请重启蓝牙或删除小程序重新进入-1')
that.isShowSearch = true
}
that.isPrinting = false;
uni.hideLoading();
}
})
},
// 开始搜索附近的蓝牙外围设备
sousuo(options = {}) {
let that = this;
if (!options.keepList) {
this.devicesList = []
}
this.addCachedDeviceToList();
this.listenBluetoothDevices();
this.isSearching = true;
wx.startBluetoothDevicesDiscovery({ //222
allowDuplicatesKey: false,
success(res3) {
that.refreshBluetoothDevices()
that.startSearchTimeout()
that.jiantingshebei(options.autoConnectCache === true)
},
fail(err) {
that.isSearching = false;
that.showToast('连接失败,请重启蓝牙或删除小程序重新进入-2')
wx.closeBLEConnection({
deviceId: uni.getStorageSync('deviceId'),
success(res2) {
},fail(err1){
}
})
wx.closeBluetoothAdapter({
success(res) {
},fail(err2){
}
})
that.clearPrinterConnectionCache()
that.isShowSearch = true
that.isPrinting = false;
uni.hideLoading();
}
})
},
//停止搜索蓝牙设备
stopSearchBtnTap() {
clearTimeout(this.searchTimer);
this.searchTimer = null;
this.isSearching = false;
wx.stopBluetoothDevicesDiscovery({
success() {},
fail() {}
})
},
/**
* jiantingshebei方法,判断缓存中有没有deviceId等数据的时候,
* 有: 直接拿到缓存中的deviceId等,直接请求 wx.createBLEConnection
* 没有:才会调用 wx.onBluetoothDeviceFound 搜索
*/
jiantingshebei(autoConnectCache = true) {
let that = this;
const cachedPrinter = that.getCachedPrinter();
if (autoConnectCache && cachedPrinter && cachedPrinter.deviceId) {
// that.huoqufuwu(uni.getStorageSync('deviceId'))
that.lianejieshebei(cachedPrinter.deviceId, {
device: cachedPrinter,
isCached: true
})
} else {
uni.hideLoading();
that.isShowSearch = true
}
},
lianejieshebei(deviceId, options = {}) {
let that = this;
const retryCount = options.retryCount || 0;
const device = options.device || that.devicesList.find(item => item.deviceId == deviceId) || that.getCachedPrinter() || {
deviceId,
name: '上次连接的打印机'
};
that.currentDevice = device;
that.isPrinting = true;
uni.showLoading({
mask: true,
title: '连接打印机...'
});
clearTimeout(that.connectTimer);
let finished = false;
that.connectTimer = setTimeout(() => {
if (finished) {
return;
}
finished = true;
wx.closeBLEConnection({
deviceId: deviceId,
success(res2) {
},fail(err1){
}
})
that.fallbackToSearch('上次连接的打印机连接超时,请从列表重新选择')
return
}, 8000);
// 连接设备
wx.createBLEConnection({ //555
deviceId: deviceId, // 搜索到设备的 deviceId
success: () => {
// 连接成功就清除定时器
if (finished) {
return;
}
finished = true;
clearTimeout(that.connectTimer);
that.isShowSearch = false
that.stopSearchBtnTap();
that.huoqufuwu(deviceId)
},
fail: (res) => {
if (finished) {
return;
}
finished = true;
clearTimeout(that.connectTimer);
if(res.errno == '1509007'){
that.huoqufuwu(deviceId)
return;
}
if((res.errno == '1509003' || res.errCode == 10003) && retryCount < 1){
wx.closeBLEConnection({
deviceId,
success() {},
fail() {}
});
setTimeout(() => {
that.lianejieshebei(deviceId, {
...options,
retryCount: retryCount + 1
});
}, 500);
return;
}
that.fallbackToSearch(options.isCached ? '上次连接的打印机连接失败,请从列表重新选择' : '打印机连接失败,请重新选择设备')
}
})
},
huoqufuwu(deviceId) {
let that = this;
//获取服务
wx.getBLEDeviceServices({ //666
deviceId: deviceId, // 搜索到设备的 deviceId
success: (res5) => {
if (!res5.services || res5.services.length <= 0) {
that.fallbackToSearch('未找到打印机服务,请重新选择设备')
return;
}
that.duxietezhengzhi(deviceId, res5.services, 0)
},
fail: (res) => {
that.showToast('连接失败,请重启蓝牙或删除小程序重新进入-4')
wx.closeBLEConnection({
deviceId: deviceId,
success(res1) {
}
})
that.fallbackToSearch()
}
})
},
duxietezhengzhi(deviceId, services, index = 0) {
let that = this;
if (!services || index >= services.length) {
that.fallbackToSearch('未找到可写入的打印机服务,请重新选择设备')
return;
}
const serviceId = services[index].uuid;
//读写特征值
wx.getBLEDeviceCharacteristics({ //777
deviceId: deviceId, // 搜索到设备的 deviceId
serviceId: serviceId, // 上一步中找到的某个服务
success: (res6) => {
const characteristics = res6.characteristics || [];
const notifyItem = characteristics.find(item => item.properties && (item.properties.notify || item.properties.indicate));
const writeItem = characteristics.find(item => item.properties && (item.properties.write || item.properties.writeNoResponse));
if (writeItem) { // 该特征值可写
if (notifyItem) {
that.startNoticeBle(deviceId, serviceId, notifyItem.uuid)
}
that.savePrinterCache({
...that.currentDevice,
deviceId
}, serviceId, writeItem.uuid);
that.xierushuju()
return;
}
that.duxietezhengzhi(deviceId, services, index + 1)
},
fail: (res) => {
that.duxietezhengzhi(deviceId, services, index + 1)
}
})
},
// 开启蓝牙数据监听
startNoticeBle(deviceId, serviceId, characteristicId) {
let _this = this
uni.notifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristicId,
success(res) {
_this.GetDataFromBle();
},
fail: function(err) {
}
})
},
// 设备返回的数据接收
GetDataFromBle() {
var _this = this;
uni.onBLECharacteristicValueChange((res) => {
// 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据,所以需要通过一个方法转换成字符串
_this.bleData = _this.ab2hex(res.value)
console.log('返回值是什么',_this.bleData)
if (_this.isWriting) {
return;
}
_this.finishPrint()
})
},
ab2hex(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
},
xierushuju() {
let that = this;
//写入数据
if (this.defaultText == '打印小票') {
that.$emit('onPrintSmall');
} else if (this.defaultText == '确认打印') {
that.$emit('goPrint');
} else if (this.defaultText == '小标签') {
that.$emit('onPrintSmall1');
}else {
that.$emit('onPrint');
}
that.$nextTick(() => {
var dataStr = ''
for (let m = 0; m < that.bufferData.length; m++) {
dataStr += that.bufferData[m]
}
const maxChunk = that.deviceType == 'android' ? 20 : 180;
const delay = that.deviceType == 'android' ? 20 : 180;
let buffer = gbk.strToGBKByte(dataStr)
if (!buffer || buffer.byteLength <= 0) {
that.finishPrint();
that.showToast('暂无打印内容');
return;
}
if(dataStr.indexOf('EG ') != -1){
that.picWaitTime = buffer.byteLength + 200
}
const chunks = [];
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);
chunks.push(subPackage);
}
that.isWriting = true;
that.writeChunks(chunks, 0, delay);
})
return;
},
writeChunks(chunks, index, delay) {
if (this.writeFailing) {
return;
}
if (index >= chunks.length) {
this.isWriting = false;
this.finishPrint();
return;
}
this._writeBLECharacteristicValue(chunks[index], () => {
setTimeout(() => {
this.writeChunks(chunks, index + 1, delay);
}, delay);
}, (res) => {
this.handleWriteFail(res);
});
},
_writeBLECharacteristicValue(buffer, success, fail) {
wx.writeBLECharacteristicValue({
deviceId: uni.getStorageSync('deviceId'),
serviceId: uni.getStorageSync('serviceId'),
characteristicId: uni.getStorageSync('characteristicId'),
value: buffer,
success(res) {
success && success(res);
},
fail(res) {
fail && fail(res);
}
})
},
handleWriteFail(res) {
this.writeFailing = true;
this.isWriting = false;
this.closeCurrentConnection();
this.fallbackToSearch('打印数据发送失败,请重新选择打印机后再试');
},
finishPrint() {
if (!this.isPrinting && !uni.getStorageSync('deviceId')) {
return;
}
clearTimeout(this.printFinishTimer);
uni.hideLoading();
this.isPrinting = false;
this.isWriting = false;
this.writeFailing = false;
this.printFinishTimer = setTimeout(() => {
this.closeCurrentConnection();
this.picWaitTime = 0;
}, this.picWaitTime || 300);
},
handleSearchClose() {
this.stopSearchBtnTap();
wx.closeBluetoothAdapter({
success(res) {
}
})
this.isShowSearch = false
this.isPrinting = false
}
}
}
</script>
<style lang="scss" scoped>
.kk-printer {
&-btn {
width: 100%;
height: 100%;
}
.kk-shadow {
display: none;
z-index: 999;
&.show {
display: block;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.4);
position: fixed;
top: 0;
left: 0;
display: flex;
justify-content: center;
align-items: center;
.kk-modal {
width: 420rpx;
height: 600rpx;
padding: 24rpx;
box-sizing: border-box;
overflow-y: auto;
border-radius: 20rpx;
background: #ffffff;
display: flex;
justify-content: center;
align-items: center;
.kk-search-device {
width: 100%;
height: 100%;
.kk-filter-wrap {
width: 100%;
height: 160rpx;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
&>slider {
width: 90%;
height: 90rpx;
}
&>input {
padding: 0 20rpx;
box-sizing: border-box;
border-radius: 10rpx;
height: 90rpx;
width: 100%;
border: 1rpx solid #ebebeb;
}
}
.kk-btn-wrap {
width: 100%;
height: 90rpx;
display: flex;
justify-content: space-between;
align-items: center;
padding: 20rpx;
&>view {
flex: 1 1 auto;
height: 60rpx;
line-height: 60rpx;
border-radius: 16rpx;
text-align: center;
color: #ffffff;
font-size: 26rpx;
&.confirm-btn {
background: #007AFF;
margin-right: 30rpx;
}
&:nth-last-child(1) {
background: #DD524D;
}
}
}
.kk-devices-wrap {
height: calc(100% - 80rpx);
overflow-y: auto;
padding: 10rpx 20rpx;
box-sizing: border-box;
border: 1rpx solid #ebebeb;
box-sizing: border-box;
border-radius: 20rpx;
.empty-wrap {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
.empty-icon {
width: 268rpx;
height: 240rpx;
background-size: 100% 100%;
margin-bottom: 26rpx;
}
.empty-text {
width: 100%;
line-height: 50rpx;
font-size: 30rpx;
text-align: center;
color: #999999;
}
}
.kk-devices-item {
width: 100%;
border-bottom: 1rpx solid #ebebeb;
padding: 10rpx 0;
box-sizing: border-box;
z-index: 500;
&:nth-last-child(1) {
border-bottom: none;
}
&>view {
width: 100%;
font-size: 30rpx;
}
}
}
}
}
}
}
}
</style>